index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/services/sfn/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/sfn/src/it/java/software/amazon/awssdk/services/sfn/SfnIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sfn;
import static org.junit.Assert.assertNotNull;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase;
public class SfnIntegrationTest extends AwsIntegrationTestBase {
private static SfnClient sfnClient;
private static String activityArn;
@BeforeClass
public static void setUpClient() {
sfnClient = SfnClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build();
activityArn = sfnClient.createActivity(b -> b.name("test")).activityArn();
}
@AfterClass
public static void cleanUp() {
if (activityArn != null) {
sfnClient.deleteActivity(b -> b.activityArn(activityArn));
}
}
@Test
public void getActivityTask_shouldWorkByDefault(){
assertNotNull(sfnClient.getActivityTask(b -> b.activityArn(activityArn)));
}
}
| 5,100 |
0 | Create_ds/aws-sdk-java-v2/services/sfn/src/main/java/software/amazon/awssdk/services/sfn | Create_ds/aws-sdk-java-v2/services/sfn/src/main/java/software/amazon/awssdk/services/sfn/internal/SfnHttpConfigurationOptions.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sfn.internal;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Sfn specific http configurations.
*/
@SdkInternalApi
public final class SfnHttpConfigurationOptions {
private static final AttributeMap OPTIONS = AttributeMap
.builder()
// Sfn has long polling APIs such as getActivityTask that could take up to
// 60 seconds to respond
.put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(65))
.build();
private SfnHttpConfigurationOptions() {
}
public static AttributeMap defaultHttpConfig() {
return OPTIONS;
}
}
| 5,101 |
0 | Create_ds/aws-sdk-java-v2/services/devicefarm/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/devicefarm/src/it/java/software/amazon/awssdk/services/devicefarm/DeviceFarmIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.devicefarm;
import static org.junit.Assert.assertNotNull;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.devicefarm.model.CreateProjectRequest;
import software.amazon.awssdk.services.devicefarm.model.CreateProjectResponse;
import software.amazon.awssdk.services.devicefarm.model.DeleteProjectRequest;
import software.amazon.awssdk.services.devicefarm.model.ListDevicePoolsRequest;
import software.amazon.awssdk.services.devicefarm.model.Project;
import software.amazon.awssdk.testutils.service.AwsTestBase;
/**
* Smoke tests for device farm service.
*/
public class DeviceFarmIntegrationTest extends AwsTestBase {
private static final String PROJECT_NAME = "df-java-project-"
+ System.currentTimeMillis();
private static DeviceFarmClient client;
private static String projectArn;
@BeforeClass
public static void setup() throws Exception {
setUpCredentials();
client = DeviceFarmClient.builder()
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.region(Region.US_WEST_2)
.build();
}
@AfterClass
public static void teardown() {
client.deleteProject(DeleteProjectRequest.builder().arn(projectArn).build());
}
@Test
public void testCreateProject() {
CreateProjectResponse result = client
.createProject(CreateProjectRequest.builder()
.name(PROJECT_NAME)
.build());
final Project project = result.project();
assertNotNull(project);
projectArn = project.arn();
assertNotNull(projectArn);
}
@Test(expected = SdkServiceException.class)
public void testExceptionHandling() {
client.listDevicePools(ListDevicePoolsRequest.builder().nextToken("fake-token").build());
}
}
| 5,102 |
0 | Create_ds/aws-sdk-java-v2/services/polly/src/test/java/software/amazon/awssdk/services/polly/internal | Create_ds/aws-sdk-java-v2/services/polly/src/test/java/software/amazon/awssdk/services/polly/internal/presigner/DefaultPollyPresignerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.polly.internal.presigner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.time.Duration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.polly.model.OutputFormat;
import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest;
import software.amazon.awssdk.services.polly.presigner.PollyPresigner;
import software.amazon.awssdk.services.polly.presigner.model.PresignedSynthesizeSpeechRequest;
import software.amazon.awssdk.services.polly.presigner.model.SynthesizeSpeechPresignRequest;
/**
* Tests for {@link DefaultPollyPresigner}.
*/
class DefaultPollyPresignerTest {
private static final SynthesizeSpeechRequest BASIC_SYNTHESIZE_SPEECH_REQUEST = SynthesizeSpeechRequest.builder()
.voiceId("Salli")
.outputFormat(OutputFormat.PCM)
.text("Hello presigners!")
.build();
private IdentityProvider<AwsCredentialsIdentity> credentialsProvider;
@BeforeEach
public void methodSetup() {
credentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"));
}
@Test
void presign_requestLevelCredentials_honored() {
IdentityProvider<AwsCredentialsIdentity> requestCedentialsProvider = StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid2", "skid2")
);
PollyPresigner presigner = DefaultPollyPresigner.builder()
.region(Region.US_EAST_1)
.credentialsProvider(credentialsProvider)
.build();
SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder()
.overrideConfiguration(AwsRequestOverrideConfiguration.builder()
.credentialsProvider(requestCedentialsProvider).build())
.build();
SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
.synthesizeSpeechRequest(synthesizeSpeechRequest)
.signatureDuration(Duration.ofHours(3))
.build();
PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest);
assertThat(presignedSynthesizeSpeechRequest.url().getQuery()).contains("X-Amz-Credential=akid2");
}
@Test
void presign_requestLevelHeaders_included() {
PollyPresigner presigner = DefaultPollyPresigner.builder()
.region(Region.US_EAST_1)
.credentialsProvider(credentialsProvider)
.build();
SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder()
.overrideConfiguration(AwsRequestOverrideConfiguration.builder()
.putHeader("Header1", "Header1Value")
.putHeader("Header2", "Header2Value")
.build())
.build();
SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
.synthesizeSpeechRequest(synthesizeSpeechRequest)
.signatureDuration(Duration.ofHours(3))
.build();
PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest);
assertThat(presignedSynthesizeSpeechRequest.httpRequest().headers().keySet()).contains("Header1", "Header2");
}
@Test
void presign_includesRequestLevelHeaders_notBrowserCompatible() {
PollyPresigner presigner = DefaultPollyPresigner.builder()
.region(Region.US_EAST_1)
.credentialsProvider(credentialsProvider)
.build();
SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder()
.overrideConfiguration(AwsRequestOverrideConfiguration.builder()
.putHeader("Header1", "Header1Value")
.putHeader("Header2", "Header2Value")
.build())
.build();
SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
.synthesizeSpeechRequest(synthesizeSpeechRequest)
.signatureDuration(Duration.ofHours(3))
.build();
PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest);
assertThat(presignedSynthesizeSpeechRequest.isBrowserExecutable()).isFalse();
}
@Test
void presign_includesRequestLevelQueryParams_included() {
PollyPresigner presigner = DefaultPollyPresigner.builder()
.region(Region.US_EAST_1)
.credentialsProvider(credentialsProvider)
.build();
SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder()
.overrideConfiguration(AwsRequestOverrideConfiguration.builder()
.putRawQueryParameter("QueryParam1", "Param1Value")
.build())
.build();
SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
.synthesizeSpeechRequest(synthesizeSpeechRequest)
.signatureDuration(Duration.ofHours(3))
.build();
PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest);
assertThat(presignedSynthesizeSpeechRequest.httpRequest().rawQueryParameters().keySet()).contains("QueryParam1");
}
@Test
void presign_endpointOverriden() {
PollyPresigner presigner = DefaultPollyPresigner.builder()
.region(Region.US_EAST_1)
.credentialsProvider(credentialsProvider)
.endpointOverride(URI.create("http://some-other-polly-endpoint.aws:1234"))
.build();
SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
.synthesizeSpeechRequest(BASIC_SYNTHESIZE_SPEECH_REQUEST)
.signatureDuration(Duration.ofHours(3))
.build();
PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest);
URL presignedUrl = presignedSynthesizeSpeechRequest.url();
assertThat(presignedUrl.getProtocol()).isEqualTo("http");
assertThat(presignedUrl.getHost()).isEqualTo("some-other-polly-endpoint.aws");
assertThat(presignedUrl.getPort()).isEqualTo(1234);
}
@Test
void close_closesCustomCloseableCredentialsProvider() throws IOException {
TestCredentialsProvider mockCredentialsProvider = mock(TestCredentialsProvider.class);
PollyPresigner presigner = DefaultPollyPresigner.builder()
.region(Region.US_EAST_1)
.credentialsProvider(mockCredentialsProvider)
.build();
presigner.close();
verify(mockCredentialsProvider).close();
}
@Test
void presigner_credentialsProviderSetAsAwsCredentialsProvider_delegatesCorrectly() {
AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"));
DefaultPollyPresigner presigner1 = (DefaultPollyPresigner)
DefaultPollyPresigner.builder()
.region(Region.US_EAST_1)
.credentialsProvider(credentialsProvider)
.build();
DefaultPollyPresigner presigner2 = (DefaultPollyPresigner)
DefaultPollyPresigner.builder()
.region(Region.US_EAST_1)
.credentialsProvider((IdentityProvider<AwsCredentialsIdentity>) credentialsProvider)
.build();
assertThat(presigner1.credentialsProvider()).isSameAs(presigner2.credentialsProvider());
}
@Test
void presigner_credentialsProviderSetToNullByBuilder_createsDefaultCredentialsProvider() {
DefaultPollyPresigner presigner = (DefaultPollyPresigner)
DefaultPollyPresigner.builder()
.region(Region.US_EAST_1)
.credentialsProvider(null)
.build();
IdentityProvider<? extends AwsCredentialsIdentity> awsCredentialsProvider = presigner.credentialsProvider();
assertThat(awsCredentialsProvider).isNotNull();
}
private interface TestCredentialsProvider extends IdentityProvider<AwsCredentialsIdentity>, Closeable {
}
}
| 5,103 |
0 | Create_ds/aws-sdk-java-v2/services/polly/src/test/java/software/amazon/awssdk/services/polly/internal/presigner/model | Create_ds/aws-sdk-java-v2/services/polly/src/test/java/software/amazon/awssdk/services/polly/internal/presigner/model/transform/SynthesizeSpeechRequestMarshallerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.polly.internal.presigner.model.transform;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest;
public class SynthesizeSpeechRequestMarshallerTest {
private static Map<String, Object> properties;
@BeforeAll
public static void setup() {
properties = new HashMap<>();
properties.put("Engine", "engine");
properties.put("LanguageCode", "languageCode");
properties.put("LexiconNames", Arrays.asList("Lexicon1", "Lexicon2", "Lexicon3"));
properties.put("OutputFormat", "outputFormat");
properties.put("SampleRate", "sampleRate");
properties.put("SpeechMarkTypes", Arrays.asList("SpeechMark1", "SpeechMark2"));
properties.put("Text", "text");
properties.put("TextType", "textType");
properties.put("VoiceId", "voiceId");
}
// Test to ensure that we are testing with all the known properties for
// this request. If this test fails, it means Polly added a new field to
// SynthesizeSpeechRequest and the marshaller and/or properties map above
// wasn't updated.
@Test
public void marshall_allPropertiesAccountedFor() {
SynthesizeSpeechRequest request = SynthesizeSpeechRequest.builder().build();
request.sdkFields().forEach(f -> assertThat(properties.containsKey(f.locationName())).isTrue());
}
@Test
public void marshall_allPropertiesMarshalled() {
SynthesizeSpeechRequest.Builder builder = setAllProperties(SynthesizeSpeechRequest.builder());
SdkHttpFullRequest.Builder marshalled = SynthesizeSpeechRequestMarshaller.getInstance().marshall(builder.build());
Map<String, List<String>> queryParams = marshalled.rawQueryParameters();
properties.keySet().forEach(k -> {
Object expected = properties.get(k);
List<String> actual = queryParams.get(k);
if (expected instanceof List) {
assertThat(actual).isEqualTo(expected);
} else {
assertThat(actual).containsExactly((String) expected);
}
});
assertThat(marshalled.contentStreamProvider()).isNull();
}
@Test
public void marshall_correctPath() {
SdkHttpFullRequest.Builder marshalled = SynthesizeSpeechRequestMarshaller.getInstance()
.marshall(SynthesizeSpeechRequest.builder().build());
assertThat(marshalled.encodedPath()).isEqualTo("/v1/speech");
}
@Test
public void marshall_correctMethod() {
SdkHttpFullRequest.Builder marshalled = SynthesizeSpeechRequestMarshaller.getInstance()
.marshall(SynthesizeSpeechRequest.builder().build());
assertThat(marshalled.method()).isEqualTo(SdkHttpMethod.GET);
}
private SynthesizeSpeechRequest.Builder setAllProperties(SynthesizeSpeechRequest.Builder builder) {
SynthesizeSpeechRequest request = SynthesizeSpeechRequest.builder().build();
List<SdkField<?>> sdkFields = request.sdkFields();
sdkFields.forEach(f -> f.set(builder, properties.get(f.locationName())));
return builder;
}
}
| 5,104 |
0 | Create_ds/aws-sdk-java-v2/services/polly/src/it/java/software/amazon/awssdk/services/polly/internal | Create_ds/aws-sdk-java-v2/services/polly/src/it/java/software/amazon/awssdk/services/polly/internal/presigner/DefaultPollyPresignerIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.polly.internal.presigner;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.URL;
import java.time.Duration;
import javax.net.ssl.HttpsURLConnection;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.services.polly.model.OutputFormat;
import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest;
import software.amazon.awssdk.services.polly.model.VoiceId;
import software.amazon.awssdk.services.polly.presigner.PollyPresigner;
import software.amazon.awssdk.services.polly.presigner.model.SynthesizeSpeechPresignRequest;
import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase;
/**
* Integration tests for {@link DefaultPollyPresigner}.
*/
public class DefaultPollyPresignerIntegrationTest extends AwsIntegrationTestBase {
private static PollyPresigner presigner;
@BeforeClass
public static void setup() {
presigner = DefaultPollyPresigner.builder()
.credentialsProvider(getCredentialsProvider())
.build();
}
@Test
public void presign_requestIsValid() throws IOException {
SynthesizeSpeechRequest request = SynthesizeSpeechRequest.builder()
.text("hello world!")
.outputFormat(OutputFormat.PCM)
.voiceId(VoiceId.SALLI)
.build();
SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
.signatureDuration(Duration.ofMinutes(45))
.synthesizeSpeechRequest(request)
.build();
URL presignedUrl = presigner.presignSynthesizeSpeech(presignRequest).url();
HttpsURLConnection urlConnection = null;
try {
urlConnection = ((HttpsURLConnection) presignedUrl.openConnection());
urlConnection.connect();
assertThat(urlConnection.getResponseCode()).isEqualTo(200);
assertThat(urlConnection.getHeaderField("Content-Type")).isEqualTo("audio/pcm");
} finally {
urlConnection.getInputStream().close();
}
}
}
| 5,105 |
0 | Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/internal | Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/internal/presigner/DefaultPollyPresigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.polly.internal.presigner;
import static java.util.stream.Collectors.toMap;
import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.PRESIGNER_EXPIRATION;
import java.net.URI;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.SdkInternalApi;
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.auth.signer.Aws4Signer;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.awscore.AwsExecutionAttribute;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
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.presigner.PresignRequest;
import software.amazon.awssdk.awscore.presigner.PresignedRequest;
import software.amazon.awssdk.core.ClientType;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.core.signer.Presigner;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme;
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.identity.spi.IdentityProviders;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain;
import software.amazon.awssdk.services.polly.auth.scheme.PollyAuthSchemeProvider;
import software.amazon.awssdk.services.polly.internal.presigner.model.transform.SynthesizeSpeechRequestMarshaller;
import software.amazon.awssdk.services.polly.model.PollyRequest;
import software.amazon.awssdk.services.polly.presigner.PollyPresigner;
import software.amazon.awssdk.services.polly.presigner.model.PresignedSynthesizeSpeechRequest;
import software.amazon.awssdk.services.polly.presigner.model.SynthesizeSpeechPresignRequest;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Validate;
/**
* Default implementation of {@link PollyPresigner}.
*/
@SdkInternalApi
public final class DefaultPollyPresigner implements PollyPresigner {
private static final String SIGNING_NAME = "polly";
private static final String SERVICE_NAME = "polly";
private static final Aws4Signer DEFAULT_SIGNER = Aws4Signer.create();
private final Supplier<ProfileFile> profileFile;
private final String profileName;
private final Region region;
private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider;
private final URI endpointOverride;
private final Boolean dualstackEnabled;
private final Boolean fipsEnabled;
private DefaultPollyPresigner(BuilderImpl builder) {
this.profileFile = ProfileFile::defaultProfileFile;
this.profileName = ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
this.region = builder.region != null ? builder.region
: DefaultAwsRegionProviderChain.builder()
.profileFile(profileFile)
.profileName(profileName)
.build()
.getRegion();
this.credentialsProvider = builder.credentialsProvider != null ? builder.credentialsProvider
: DefaultCredentialsProvider.builder()
.profileFile(profileFile)
.profileName(profileName)
.build();
this.endpointOverride = builder.endpointOverride;
this.dualstackEnabled = builder.dualstackEnabled != null ? builder.dualstackEnabled
: DualstackEnabledProvider.builder()
.profileFile(profileFile)
.profileName(profileName)
.build()
.isDualstackEnabled()
.orElse(false);
this.fipsEnabled = builder.fipsEnabled != null ? builder.fipsEnabled
: FipsEnabledProvider.builder()
.profileFile(profileFile)
.profileName(profileName)
.build()
.isFipsEnabled()
.orElse(false);
}
IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider() {
return credentialsProvider;
}
@Override
public void close() {
IoUtils.closeIfCloseable(credentialsProvider, null);
}
public static PollyPresigner.Builder builder() {
return new BuilderImpl();
}
@Override
public PresignedSynthesizeSpeechRequest presignSynthesizeSpeech(
SynthesizeSpeechPresignRequest synthesizeSpeechPresignRequest) {
return presign(PresignedSynthesizeSpeechRequest.builder(),
synthesizeSpeechPresignRequest,
synthesizeSpeechPresignRequest.synthesizeSpeechRequest(),
SynthesizeSpeechRequestMarshaller.getInstance()::marshall)
.build();
}
private <T extends PollyRequest> SdkHttpFullRequest marshallRequest(
T request, Function<T, SdkHttpFullRequest.Builder> marshalFn) {
SdkHttpFullRequest.Builder requestBuilder = marshalFn.apply(request);
applyOverrideHeadersAndQueryParams(requestBuilder, request);
applyEndpoint(requestBuilder);
return requestBuilder.build();
}
/**
* Generate a {@link PresignedRequest} from a {@link PresignedRequest} and {@link PollyRequest}.
*/
private <T extends PresignedRequest.Builder, U extends PollyRequest> T presign(T presignedRequest,
PresignRequest presignRequest,
U requestToPresign,
Function<U, SdkHttpFullRequest.Builder> requestMarshaller) {
ExecutionAttributes execAttrs = createExecutionAttributes(presignRequest, requestToPresign);
SdkHttpFullRequest marshalledRequest = marshallRequest(requestToPresign, requestMarshaller);
SdkHttpFullRequest signedHttpRequest = presignRequest(requestToPresign, marshalledRequest, execAttrs);
initializePresignedRequest(presignedRequest, execAttrs, signedHttpRequest);
return presignedRequest;
}
private void initializePresignedRequest(PresignedRequest.Builder presignedRequest,
ExecutionAttributes execAttrs,
SdkHttpFullRequest signedHttpRequest) {
List<String> signedHeadersQueryParam = signedHttpRequest.firstMatchingRawQueryParameters("X-Amz-SignedHeaders");
Map<String, List<String>> signedHeaders =
signedHeadersQueryParam.stream()
.flatMap(h -> Stream.of(h.split(";")))
.collect(toMap(h -> h, h -> signedHttpRequest.firstMatchingHeader(h)
.map(Collections::singletonList)
.orElseGet(ArrayList::new)));
boolean isBrowserExecutable = signedHttpRequest.method() == SdkHttpMethod.GET &&
(signedHeaders.isEmpty() ||
(signedHeaders.size() == 1 && signedHeaders.containsKey("host")));
presignedRequest.expiration(execAttrs.getAttribute(PRESIGNER_EXPIRATION))
.isBrowserExecutable(isBrowserExecutable)
.httpRequest(signedHttpRequest)
.signedHeaders(signedHeaders);
}
private SdkHttpFullRequest presignRequest(PollyRequest requestToPresign,
SdkHttpFullRequest marshalledRequest,
ExecutionAttributes executionAttributes) {
Presigner presigner = resolvePresigner(requestToPresign);
SdkHttpFullRequest presigned = presigner.presign(marshalledRequest, executionAttributes);
List<String> signedHeadersQueryParam = presigned.firstMatchingRawQueryParameters("X-Amz-SignedHeaders");
Validate.validState(!signedHeadersQueryParam.isEmpty(),
"Only SigV4 presigners are supported at this time, but the configured "
+ "presigner (%s) did not seem to generate a SigV4 signature.", presigner);
return presigned;
}
private ExecutionAttributes createExecutionAttributes(PresignRequest presignRequest, PollyRequest requestToPresign) {
Instant signatureExpiration = Instant.now().plus(presignRequest.signatureDuration());
AwsCredentialsIdentity credentials = resolveCredentials(resolveCredentialsProvider(requestToPresign));
Validate.validState(credentials != null, "Credential providers must never return null.");
return new ExecutionAttributes()
.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, CredentialUtils.toCredentials(credentials))
.putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, SIGNING_NAME)
.putAttribute(AwsExecutionAttribute.AWS_REGION, region)
.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, region)
.putAttribute(SdkInternalExecutionAttribute.IS_FULL_DUPLEX, false)
.putAttribute(SdkExecutionAttribute.CLIENT_TYPE, ClientType.SYNC)
.putAttribute(SdkExecutionAttribute.SERVICE_NAME, SERVICE_NAME)
.putAttribute(PRESIGNER_EXPIRATION, signatureExpiration)
.putAttribute(SdkInternalExecutionAttribute.AUTH_SCHEME_RESOLVER, PollyAuthSchemeProvider.defaultProvider())
.putAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES, authSchemes())
.putAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS,
IdentityProviders.builder()
.putIdentityProvider(credentialsProvider())
.build());
}
private Map<String, AuthScheme<?>> authSchemes() {
AwsV4AuthScheme awsV4AuthScheme = AwsV4AuthScheme.create();
return Collections.singletonMap(awsV4AuthScheme.schemeId(), awsV4AuthScheme);
}
private IdentityProvider<? extends AwsCredentialsIdentity> resolveCredentialsProvider(PollyRequest request) {
return request.overrideConfiguration().flatMap(AwsRequestOverrideConfiguration::credentialsIdentityProvider)
.orElse(credentialsProvider);
}
private AwsCredentialsIdentity resolveCredentials(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
return CompletableFutureUtils.joinLikeSync(credentialsProvider.resolveIdentity());
}
private Presigner resolvePresigner(PollyRequest request) {
Signer signer = request.overrideConfiguration().flatMap(AwsRequestOverrideConfiguration::signer)
.orElse(DEFAULT_SIGNER);
return Validate.isInstanceOf(Presigner.class, signer,
"Signer of type %s given in request override is not a Presigner", signer.getClass().getSimpleName());
}
private void applyOverrideHeadersAndQueryParams(SdkHttpFullRequest.Builder httpRequestBuilder, PollyRequest request) {
request.overrideConfiguration().ifPresent(o -> {
o.headers().forEach(httpRequestBuilder::putHeader);
o.rawQueryParameters().forEach(httpRequestBuilder::putRawQueryParameter);
});
}
private void applyEndpoint(SdkHttpFullRequest.Builder httpRequestBuilder) {
URI uri = resolveEndpoint();
httpRequestBuilder.protocol(uri.getScheme())
.host(uri.getHost())
.port(uri.getPort());
}
private URI resolveEndpoint() {
if (endpointOverride != null) {
return endpointOverride;
}
return new DefaultServiceEndpointBuilder(SERVICE_NAME, "https")
.withRegion(region)
.withProfileFile(profileFile)
.withProfileName(profileName)
.withDualstackEnabled(dualstackEnabled)
.withFipsEnabled(fipsEnabled)
.getServiceEndpoint();
}
public static class BuilderImpl implements PollyPresigner.Builder {
private Region region;
private IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider;
private URI endpointOverride;
private Boolean dualstackEnabled;
private Boolean fipsEnabled;
@Override
public Builder region(Region region) {
this.region = region;
return this;
}
@Override
public Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) {
return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider);
}
@Override
public Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
this.credentialsProvider = credentialsProvider;
return this;
}
@Override
public Builder dualstackEnabled(Boolean dualstackEnabled) {
this.dualstackEnabled = dualstackEnabled;
return this;
}
@Override
public Builder fipsEnabled(Boolean fipsEnabled) {
this.fipsEnabled = fipsEnabled;
return this;
}
@Override
public Builder endpointOverride(URI endpointOverride) {
this.endpointOverride = endpointOverride;
return this;
}
@Override
public PollyPresigner build() {
return new DefaultPollyPresigner(this);
}
}
}
| 5,106 |
0 | Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/internal/presigner/model | Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/internal/presigner/model/transform/SynthesizeSpeechRequestMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.polly.internal.presigner.model.transform;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest;
/**
* Marshaller for {@link SynthesizeSpeechRequest} that marshalls the request into a form that can be presigned.
*/
@SdkInternalApi
public final class SynthesizeSpeechRequestMarshaller {
private static final SynthesizeSpeechRequestMarshaller INSTANCE = new SynthesizeSpeechRequestMarshaller();
public SdkHttpFullRequest.Builder marshall(SynthesizeSpeechRequest synthesizeSpeechRequest) {
SdkHttpFullRequest.Builder builder = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.encodedPath("/v1/speech");
if (synthesizeSpeechRequest.text() != null) {
builder.putRawQueryParameter("Text", synthesizeSpeechRequest.text());
}
if (synthesizeSpeechRequest.textType() != null) {
builder.putRawQueryParameter("TextType", synthesizeSpeechRequest.textTypeAsString());
}
if (synthesizeSpeechRequest.voiceId() != null) {
builder.putRawQueryParameter("VoiceId", synthesizeSpeechRequest.voiceIdAsString());
}
if (synthesizeSpeechRequest.sampleRate() != null) {
builder.putRawQueryParameter("SampleRate", synthesizeSpeechRequest.sampleRate());
}
if (synthesizeSpeechRequest.outputFormat() != null) {
builder.putRawQueryParameter("OutputFormat", synthesizeSpeechRequest.outputFormatAsString());
}
if (synthesizeSpeechRequest.lexiconNames() != null) {
builder.putRawQueryParameter("LexiconNames", synthesizeSpeechRequest.lexiconNames());
}
if (synthesizeSpeechRequest.speechMarkTypes() != null) {
builder.putRawQueryParameter("SpeechMarkTypes", synthesizeSpeechRequest.speechMarkTypesAsStrings());
}
if (synthesizeSpeechRequest.languageCode() != null) {
builder.putRawQueryParameter("LanguageCode", synthesizeSpeechRequest.languageCodeAsString());
}
if (synthesizeSpeechRequest.engine() != null) {
builder.putRawQueryParameter("Engine", synthesizeSpeechRequest.engineAsString());
}
return builder;
}
public static SynthesizeSpeechRequestMarshaller getInstance() {
return INSTANCE;
}
}
| 5,107 |
0 | Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly | Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/presigner/PollyPresigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.polly.presigner;
import java.net.URI;
import java.net.URLConnection;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.awscore.presigner.PresignedRequest;
import software.amazon.awssdk.awscore.presigner.SdkPresigner;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.polly.internal.presigner.DefaultPollyPresigner;
import software.amazon.awssdk.services.polly.model.PollyRequest;
import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest;
import software.amazon.awssdk.services.polly.presigner.model.PresignedSynthesizeSpeechRequest;
import software.amazon.awssdk.services.polly.presigner.model.SynthesizeSpeechPresignRequest;
/**
* Enables signing a {@link PollyRequest} so that it can be executed without requiring any additional authentication on the
* part of the caller.
* <p/>
*
* <b>Signature Duration</b>
* <p/>
*
* Pre-signed requests are only valid for a finite period of time, referred to as the signature duration. This signature
* duration is configured when the request is generated, and cannot be longer than 7 days. Attempting to generate a signature
* longer than 7 days in the future will fail at generation time. Attempting to use a pre-signed request after the signature
* duration has passed will result in an access denied response from the service.
* <p/>
*
* <b>Example Usage</b>
* <p/>
*
* <pre>
* {@code
* // Create a PollyPresigner using the default region and credentials.
* // This is usually done at application startup, because creating a presigner can be expensive.
* PollyPresigner presigner = PollyPresigner.create();
*
* // Create a SynthesizeSpeechRequest to be pre-signed
* SynthesizeSpeechRequest synthesizeSpeechRequest =
* SynthesizeSpeechRequest.builder()
* .text("Hello Polly!")
* .voiceId(VoiceId.SALLI)
* .outputFormat(OutputFormat.PCM)
* .build();
*
* // Create a SynthesizeSpeechRequest to specify the signature duration
* SynthesizeSpeechPresignRequest synthesizeSpeechPresignRequest =
* SynthesizeSpeechPresignRequest.builder()
* .signatureDuration(Duration.ofMinutes(10))
* .synthesizeSpeechRequest(synthesizeSpeechRequest)
* .build();
*
* // Generate the presigned request
* PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest =
* presigner.presignSynthesizeSpeech(SynthesizeSpeechPresignRequest);
*
* // Log the presigned URL, for example.
* System.out.println("Presigned URL: " + presignedSynthesizeSpeechRequest.url());
*
* // It is recommended to close the presigner when it is done being used, because some credential
* // providers (e.g. if your AWS profile is configured to assume an STS role) require system resources
* // that need to be freed. If you are using one presigner per application (as recommended), this
* // usually is not needed.
* presigner.close();
* }
* </pre>
* <p/>
*
* <b>Browser Compatibility</b>
* <p/>
*
* Some pre-signed requests can be executed by a web browser. These "browser compatible" pre-signed requests
* do not require the customer to send anything other than a "host" header when performing an HTTP GET against
* the pre-signed URL.
* <p/>
*
* Whether a pre-signed request is "browser compatible" can be determined by checking the
* {@link PresignedRequest#isBrowserExecutable()} flag. It is recommended to always check this flag when the pre-signed
* request needs to be executed by a browser, because some request fields will result in the pre-signed request not
* being browser-compatible.
* <p />
*
* <b>Executing a Pre-Signed Request from Java code</b>
* <p />
*
* Browser-compatible requests (see above) can be executed using a web browser. All pre-signed requests can be executed
* from Java code. This documentation describes two methods for executing a pre-signed request: (1) using the JDK's
* {@link URLConnection} class, (2) using an SDK synchronous {@link SdkHttpClient} class.
*
* <p />
* <i>Using {code URLConnection}:</i>
*
* <p />
* <pre>
* // Create a pre-signed request using one of the "presign" methods on PollyPresigner
* PresignedRequest presignedRequest = ...;
*
* // Create a JDK HttpURLConnection for communicating with Polly
* HttpURLConnection connection = (HttpURLConnection) presignedRequest.url().openConnection();
*
* // Specify any headers that are needed by the service (not needed when isBrowserExecutable is true)
* presignedRequest.httpRequest().headers().forEach((header, values) -> {
* values.forEach(value -> {
* connection.addRequestProperty(header, value);
* });
* });
*
* // Download the result of executing the request
* try (InputStream content = connection.getInputStream()) {
* System.out.println("Service returned response: ");
* IoUtils.copy(content, myFileOutputstream);
* }
* </pre>
*/
@SdkPublicApi
public interface PollyPresigner extends SdkPresigner {
/**
* Presign a {@link SynthesizeSpeechRequest} so that it can be executed at a later time without requiring additional
* signing or authentication.
*
* @param synthesizeSpeechPresignRequest The presign request.
* @return The presigned request.
*/
PresignedSynthesizeSpeechRequest presignSynthesizeSpeech(SynthesizeSpeechPresignRequest synthesizeSpeechPresignRequest);
/**
* Create an instance of this presigner using the default region and credentials chains to resolve the region and
* credentials to use.
*/
static PollyPresigner create() {
return builder().build();
}
/**
* @return the builder for a {@link PollyPresigner}.
*/
static Builder builder() {
return DefaultPollyPresigner.builder();
}
interface Builder extends SdkPresigner.Builder {
@Override
Builder region(Region region);
@Override
default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) {
return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider);
}
@Override
Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider);
@Override
Builder dualstackEnabled(Boolean dualstackEnabled);
@Override
Builder fipsEnabled(Boolean fipsEnabled);
@Override
Builder endpointOverride(URI endpointOverride);
@Override
PollyPresigner build();
}
} | 5,108 |
0 | Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/presigner | Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/presigner/model/SynthesizeSpeechPresignRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.polly.presigner.model;
import java.time.Duration;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.awscore.presigner.PresignRequest;
import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A request to pre-sign a {@link software.amazon.awssdk.services.polly.presigner.PollyPresigner} so that it can be
* executed at a later time without requiring additional signing or authentication.
*
* @see software.amazon.awssdk.services.polly.presigner.PollyPresigner#presignSynthesizeSpeech(SynthesizeSpeechPresignRequest)
* @see #builder()
*/
@SdkPublicApi
@Immutable
@ThreadSafe
public final class SynthesizeSpeechPresignRequest
extends PresignRequest
implements ToCopyableBuilder<SynthesizeSpeechPresignRequest.Builder, SynthesizeSpeechPresignRequest> {
private final SynthesizeSpeechRequest synthesizeSpeechRequest;
private SynthesizeSpeechPresignRequest(BuilderImpl builder) {
super(builder);
this.synthesizeSpeechRequest = builder.synthesizeSpeechRequest;
}
public SynthesizeSpeechRequest synthesizeSpeechRequest() {
return synthesizeSpeechRequest;
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder extends PresignRequest.Builder,
CopyableBuilder<SynthesizeSpeechPresignRequest.Builder, SynthesizeSpeechPresignRequest> {
Builder synthesizeSpeechRequest(SynthesizeSpeechRequest synthesizeSpeechRequest);
@Override
Builder signatureDuration(Duration signatureDuration);
/**
* Build the presigned request, based on the configuration on this builder.
*/
@Override
SynthesizeSpeechPresignRequest build();
}
private static class BuilderImpl extends PresignRequest.DefaultBuilder<BuilderImpl> implements Builder {
private SynthesizeSpeechRequest synthesizeSpeechRequest;
BuilderImpl() {
}
private BuilderImpl(SynthesizeSpeechPresignRequest synthesizeSpeechPresignRequest) {
super(synthesizeSpeechPresignRequest);
this.synthesizeSpeechRequest = synthesizeSpeechPresignRequest.synthesizeSpeechRequest();
}
@Override
public Builder synthesizeSpeechRequest(SynthesizeSpeechRequest synthesizeSpeechRequest) {
this.synthesizeSpeechRequest = synthesizeSpeechRequest;
return this;
}
@Override
public SynthesizeSpeechPresignRequest build() {
return new SynthesizeSpeechPresignRequest(this);
}
}
}
| 5,109 |
0 | Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/presigner | Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/presigner/model/PresignedSynthesizeSpeechRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.polly.presigner.model;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.awscore.presigner.PresignedRequest;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A pre-signed a {@link SynthesizeSpeechPresignRequest} that can be executed at a later time without requiring
* additional signing or authentication.
*
* @see software.amazon.awssdk.services.polly.presigner.PollyPresigner#presignSynthesizeSpeech(SynthesizeSpeechPresignRequest)
* @see #builder()
*/
@SdkPublicApi
@Immutable
@ThreadSafe
public final class PresignedSynthesizeSpeechRequest
extends PresignedRequest
implements ToCopyableBuilder<PresignedSynthesizeSpeechRequest.Builder, PresignedSynthesizeSpeechRequest> {
private PresignedSynthesizeSpeechRequest(BuilderImpl builder) {
super(builder);
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
public interface Builder extends PresignedRequest.Builder,
CopyableBuilder<Builder, PresignedSynthesizeSpeechRequest> {
@Override
Builder expiration(Instant expiration);
@Override
Builder isBrowserExecutable(Boolean isBrowserExecutable);
@Override
Builder signedHeaders(Map<String, List<String>> signedHeaders);
@Override
Builder signedPayload(SdkBytes signedPayload);
@Override
Builder httpRequest(SdkHttpRequest httpRequest);
@Override
PresignedSynthesizeSpeechRequest build();
}
private static class BuilderImpl extends PresignedRequest.DefaultBuilder<BuilderImpl> implements Builder {
BuilderImpl() {
}
BuilderImpl(PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest) {
super(presignedSynthesizeSpeechRequest);
}
@Override
public PresignedSynthesizeSpeechRequest build() {
return new PresignedSynthesizeSpeechRequest(this);
}
}
}
| 5,110 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services/rds/DefaultRdsUtilitiesTest.java | package software.amazon.awssdk.services.rds;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import java.time.Clock;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.DefaultRdsUtilities.DefaultBuilder;
import software.amazon.awssdk.services.rds.model.GenerateAuthenticationTokenRequest;
public class DefaultRdsUtilitiesTest {
private final ZoneId utcZone = ZoneId.of("UTC").normalized();
private final Clock fixedClock = Clock.fixed(ZonedDateTime.of(2016, 11, 7, 17, 39, 33, 0, utcZone).toInstant(), utcZone);
@Test
public void testTokenGenerationWithBuilderDefaultsUsingAwsCredentialsProvider() {
AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(
AwsBasicCredentials.create("access_key", "secret_key")
);
DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder()
.credentialsProvider(credentialsProvider)
.region(Region.US_EAST_1);
testTokenGenerationWithBuilderDefaults(utilitiesBuilder);
}
@Test
public void testTokenGenerationWithBuilderDefaultsUsingIdentityProvider() {
IdentityProvider<AwsCredentialsIdentity> credentialsProvider = StaticCredentialsProvider.create(
AwsBasicCredentials.create("access_key", "secret_key")
);
DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder()
.credentialsProvider(credentialsProvider)
.region(Region.US_EAST_1);
testTokenGenerationWithBuilderDefaults(utilitiesBuilder);
}
private void testTokenGenerationWithBuilderDefaults(DefaultBuilder utilitiesBuilder) {
DefaultRdsUtilities rdsUtilities = new DefaultRdsUtilities(utilitiesBuilder, fixedClock);
String authenticationToken = rdsUtilities.generateAuthenticationToken(builder -> {
builder.username("mySQLUser")
.hostname("host.us-east-1.amazonaws.com")
.port(3306);
});
String expectedToken = "host.us-east-1.amazonaws.com:3306/?DBUser=mySQLUser&Action=connect&" +
"X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20161107T173933Z&X-Amz-SignedHeaders=host&" +
"X-Amz-Expires=900&X-Amz-Credential=access_key%2F20161107%2Fus-east-1%2Frds-db%2Faws4_request&" +
"X-Amz-Signature=87ab58107ef49f1c311a412f98b7f976b0b5152ffb559f0d36c6c9a0c5e0e362";
assertThat(authenticationToken).isEqualTo(expectedToken);
}
@Test
public void testTokenGenerationWithOverriddenCredentialsUsingAwsCredentialsProvider() {
AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(
AwsBasicCredentials.create("foo", "bar")
);
DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder()
.credentialsProvider(credentialsProvider)
.region(Region.US_EAST_1);
testTokenGenerationWithOverriddenCredentials(utilitiesBuilder, builder -> {
builder.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("access_key", "secret_key")));
});
}
@Test
public void testTokenGenerationWithOverriddenCredentialsUsingIdentityProvider() {
IdentityProvider<AwsCredentialsIdentity> credentialsProvider = StaticCredentialsProvider.create(
AwsBasicCredentials.create("foo", "bar")
);
DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder()
.credentialsProvider(credentialsProvider)
.region(Region.US_EAST_1);
testTokenGenerationWithOverriddenCredentials(utilitiesBuilder, builder -> {
builder.credentialsProvider((IdentityProvider<AwsCredentialsIdentity>) StaticCredentialsProvider.create(
AwsBasicCredentials.create("access_key", "secret_key")));
});
}
private void testTokenGenerationWithOverriddenCredentials(DefaultBuilder utilitiesBuilder,
Consumer<GenerateAuthenticationTokenRequest.Builder> credsBuilder) {
DefaultRdsUtilities rdsUtilities = new DefaultRdsUtilities(utilitiesBuilder, fixedClock);
String authenticationToken = rdsUtilities.generateAuthenticationToken(builder -> {
builder.username("mySQLUser")
.hostname("host.us-east-1.amazonaws.com")
.port(3306)
.applyMutation(credsBuilder);
});
String expectedToken = "host.us-east-1.amazonaws.com:3306/?DBUser=mySQLUser&Action=connect&" +
"X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20161107T173933Z&X-Amz-SignedHeaders=host&" +
"X-Amz-Expires=900&X-Amz-Credential=access_key%2F20161107%2Fus-east-1%2Frds-db%2Faws4_request&" +
"X-Amz-Signature=87ab58107ef49f1c311a412f98b7f976b0b5152ffb559f0d36c6c9a0c5e0e362";
assertThat(authenticationToken).isEqualTo(expectedToken);
}
@Test
public void testTokenGenerationWithOverriddenRegion() {
IdentityProvider<AwsCredentialsIdentity> credentialsProvider = StaticCredentialsProvider.create(
AwsBasicCredentials.create("access_key", "secret_key")
);
DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder()
.credentialsProvider(credentialsProvider)
.region(Region.US_WEST_2);
DefaultRdsUtilities rdsUtilities = new DefaultRdsUtilities(utilitiesBuilder, fixedClock);
String authenticationToken = rdsUtilities.generateAuthenticationToken(builder -> {
builder.username("mySQLUser")
.hostname("host.us-east-1.amazonaws.com")
.port(3306)
.region(Region.US_EAST_1);
});
String expectedToken = "host.us-east-1.amazonaws.com:3306/?DBUser=mySQLUser&Action=connect&" +
"X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20161107T173933Z&X-Amz-SignedHeaders=host&" +
"X-Amz-Expires=900&X-Amz-Credential=access_key%2F20161107%2Fus-east-1%2Frds-db%2Faws4_request&" +
"X-Amz-Signature=87ab58107ef49f1c311a412f98b7f976b0b5152ffb559f0d36c6c9a0c5e0e362";
assertThat(authenticationToken).isEqualTo(expectedToken);
}
@Test
public void testMissingRegionThrowsException() {
IdentityProvider<AwsCredentialsIdentity> credentialsProvider = StaticCredentialsProvider.create(
AwsBasicCredentials.create("access_key", "secret_key")
);
DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder()
.credentialsProvider(credentialsProvider);
DefaultRdsUtilities rdsUtilities = new DefaultRdsUtilities(utilitiesBuilder, fixedClock);
assertThatThrownBy(() -> rdsUtilities.generateAuthenticationToken(builder -> {
builder.username("mySQLUser")
.hostname("host.us-east-1.amazonaws.com")
.port(3306);
})).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Region should be provided");
}
@Test
public void testMissingCredentialsThrowsException() {
DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder()
.region(Region.US_WEST_2);
DefaultRdsUtilities rdsUtilities = new DefaultRdsUtilities(utilitiesBuilder, fixedClock);
assertThatThrownBy(() -> rdsUtilities.generateAuthenticationToken(builder -> {
builder.username("mySQLUser")
.hostname("host.us-east-1.amazonaws.com")
.port(3306);
})).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("CredentialProvider should be provided");
}
} | 5,111 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services/rds | Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services/rds/internal/PresignRequestWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds.internal;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.findAll;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import java.net.URI;
import java.util.List;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
@RunWith(MockitoJUnitRunner.class)
public class PresignRequestWireMockTest {
@ClassRule
public static final WireMockRule WIRE_MOCK = new WireMockRule(0);
public static RdsClient client;
@BeforeClass
public static void setup() {
client = RdsClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + WIRE_MOCK.port()))
.build();
}
@Before
public void reset() {
WIRE_MOCK.resetAll();
}
@Test
public void copyDbClusterSnapshotWithSourceRegionSendsPresignedUrl() {
verifyMethodCallSendsPresignedUrl(() -> client.copyDBClusterSnapshot(r -> r.sourceRegion("us-west-2")),
"CopyDBClusterSnapshot");
}
@Test
public void copyDBSnapshotWithSourceRegionSendsPresignedUrl() {
verifyMethodCallSendsPresignedUrl(() -> client.copyDBSnapshot(r -> r.sourceRegion("us-west-2")),
"CopyDBSnapshot");
}
@Test
public void createDbClusterWithSourceRegionSendsPresignedUrl() {
verifyMethodCallSendsPresignedUrl(() -> client.createDBCluster(r -> r.sourceRegion("us-west-2")),
"CreateDBCluster");
}
@Test
public void createDBInstanceReadReplicaWithSourceRegionSendsPresignedUrl() {
verifyMethodCallSendsPresignedUrl(() -> client.createDBInstanceReadReplica(r -> r.sourceRegion("us-west-2")),
"CreateDBInstanceReadReplica");
}
public void verifyMethodCallSendsPresignedUrl(Runnable methodCall, String actionName) {
stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody("<body/>")));
methodCall.run();
List<LoggedRequest> requests = findAll(anyRequestedFor(anyUrl()));
assertThat(requests).isNotEmpty();
LoggedRequest lastRequest = requests.get(0);
String lastRequestBody = new String(lastRequest.getBody(), UTF_8);
assertThat(lastRequestBody).contains("PreSignedUrl=https%3A%2F%2Frds.us-west-2.amazonaws.com%3FAction%3D" + actionName
+ "%26Version%3D2014-10-31%26DestinationRegion%3Dus-east-1%26");
}
@Test
public void startDBInstanceAutomatedBackupsReplicationWithSourceRegionSendsPresignedUrl() {
verifyMethodCallSendsPresignedUrl(() -> client.startDBInstanceAutomatedBackupsReplication(r -> r.sourceRegion("us-west-2")),
"StartDBInstanceAutomatedBackupsReplication");
}
}
| 5,112 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services/rds | Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services/rds/internal/PresignRequestHandlerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Clock;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder;
import software.amazon.awssdk.core.Protocol;
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.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.model.CopyDbSnapshotRequest;
import software.amazon.awssdk.services.rds.model.RdsRequest;
import software.amazon.awssdk.services.rds.transform.CopyDbSnapshotRequestMarshaller;
/**
* Unit Tests for {@link RdsPresignInterceptor}
*/
public class PresignRequestHandlerTest {
private static final AwsBasicCredentials CREDENTIALS = AwsBasicCredentials.create("foo", "bar");
private static final Region DESTINATION_REGION = Region.of("us-west-2");
private static RdsPresignInterceptor<CopyDbSnapshotRequest> presignInterceptor = new CopyDbSnapshotPresignInterceptor();
private final CopyDbSnapshotRequestMarshaller marshaller =
new CopyDbSnapshotRequestMarshaller(RdsPresignInterceptor.PROTOCOL_FACTORY);
@Test
public void testSetsPresignedUrl() {
CopyDbSnapshotRequest request = makeTestRequest();
SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request));
assertNotNull(presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0));
}
@Test
public void testComputesPresignedUrlCorrectly() {
// Note: test data was baselined by performing actual calls, with real
// credentials to RDS and checking that they succeeded. Then the
// request was recreated with all the same parameters but with test
// credentials.
final CopyDbSnapshotRequest request = CopyDbSnapshotRequest.builder()
.sourceDBSnapshotIdentifier("arn:aws:rds:us-east-1:123456789012:snapshot:rds:test-instance-ss-2016-12-20-23-19")
.targetDBSnapshotIdentifier("test-instance-ss-copy-2")
.sourceRegion("us-east-1")
.kmsKeyId("arn:aws:kms:us-west-2:123456789012:key/11111111-2222-3333-4444-555555555555")
.build();
Calendar c = new GregorianCalendar();
c.setTimeZone(TimeZone.getTimeZone("UTC"));
// 20161221T180735Z
// Note: month is 0-based
c.set(2016, Calendar.DECEMBER, 21, 18, 7, 35);
Clock signingDateOverride = Mockito.mock(Clock.class);
when(signingDateOverride.millis()).thenReturn(c.getTimeInMillis());
RdsPresignInterceptor<CopyDbSnapshotRequest> interceptor = new CopyDbSnapshotPresignInterceptor(signingDateOverride);
SdkHttpRequest presignedRequest = modifyHttpRequest(interceptor, request, marshallRequest(request));
final String expectedPreSignedUrl = "https://rds.us-east-1.amazonaws.com?" +
"Action=CopyDBSnapshot" +
"&Version=2014-10-31" +
"&SourceDBSnapshotIdentifier=arn%3Aaws%3Ards%3Aus-east-1%3A123456789012%3Asnapshot%3Ards%3Atest-instance-ss-2016-12-20-23-19" +
"&TargetDBSnapshotIdentifier=test-instance-ss-copy-2" +
"&KmsKeyId=arn%3Aaws%3Akms%3Aus-west-2%3A123456789012%3Akey%2F11111111-2222-3333-4444-555555555555" +
"&DestinationRegion=us-west-2" +
"&X-Amz-Algorithm=AWS4-HMAC-SHA256" +
"&X-Amz-Date=20161221T180735Z" +
"&X-Amz-SignedHeaders=host" +
"&X-Amz-Expires=604800" +
"&X-Amz-Credential=foo%2F20161221%2Fus-east-1%2Frds%2Faws4_request" +
"&X-Amz-Signature=f839ca3c728dc96e7c978befeac648296b9f778f6724073de4217173859d13d9";
assertEquals(expectedPreSignedUrl, presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0));
}
@Test
public void testSkipsPresigningIfUrlSet() {
CopyDbSnapshotRequest request = CopyDbSnapshotRequest.builder()
.sourceRegion("us-west-2")
.preSignedUrl("PRESIGNED")
.build();
SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request));
assertEquals("PRESIGNED", presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0));
}
@Test
public void testSkipsPresigningIfSourceRegionNotSet() {
CopyDbSnapshotRequest request = CopyDbSnapshotRequest.builder().build();
SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request));
assertNull(presignedRequest.rawQueryParameters().get("PreSignedUrl"));
}
@Test
public void testParsesDestinationRegionfromRequestEndpoint() throws URISyntaxException {
CopyDbSnapshotRequest request = CopyDbSnapshotRequest.builder()
.sourceRegion("us-east-1")
.build();
Region destination = Region.of("us-west-2");
SdkHttpFullRequest marshalled = marshallRequest(request);
final SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshalled);
final URI presignedUrl = new URI(presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0));
assertTrue(presignedUrl.toString().contains("DestinationRegion=" + destination.id()));
}
@Test
public void testSourceRegionRemovedFromOriginalRequest() {
CopyDbSnapshotRequest request = makeTestRequest();
SdkHttpFullRequest marshalled = marshallRequest(request);
SdkHttpRequest actual = modifyHttpRequest(presignInterceptor, request, marshalled);
assertFalse(actual.rawQueryParameters().containsKey("SourceRegion"));
}
private SdkHttpFullRequest marshallRequest(CopyDbSnapshotRequest request) {
SdkHttpFullRequest.Builder marshalled = marshaller.marshall(request).toBuilder();
URI endpoint = new DefaultServiceEndpointBuilder("rds", Protocol.HTTPS.toString())
.withRegion(DESTINATION_REGION)
.getServiceEndpoint();
return marshalled.uri(endpoint).build();
}
private ExecutionAttributes executionAttributes() {
return new ExecutionAttributes().putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, CREDENTIALS)
.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, DESTINATION_REGION)
.putAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER,
ProfileFile::defaultProfileFile)
.putAttribute(SdkExecutionAttribute.PROFILE_NAME, "default");
}
private CopyDbSnapshotRequest makeTestRequest() {
return CopyDbSnapshotRequest.builder()
.sourceDBSnapshotIdentifier("arn:aws:rds:us-east-1:123456789012:snapshot:rds:test-instance-ss-2016-12-20-23-19")
.targetDBSnapshotIdentifier("test-instance-ss-copy-2")
.sourceRegion("us-east-1")
.kmsKeyId("arn:aws:kms:us-west-2:123456789012:key/11111111-2222-3333-4444-555555555555")
.build();
}
private SdkHttpRequest modifyHttpRequest(ExecutionInterceptor interceptor,
RdsRequest request,
SdkHttpFullRequest httpRequest) {
InterceptorContext context = InterceptorContext.builder().request(request).httpRequest(httpRequest).build();
return interceptor.modifyHttpRequest(context, executionAttributes());
}
}
| 5,113 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/RdsUtilities.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.model.GenerateAuthenticationTokenRequest;
/**
* Utilities for working with RDS. An instance of this class can be created by:
* <p>
* 1) Using the low-level client {@link RdsClient#utilities()} (or {@link RdsAsyncClient#utilities()}} method. This is
* recommended as SDK will use the same configuration from the {@link RdsClient} object to create the {@link RdsUtilities} object.
*
* <pre>
* RdsClient rdsClient = RdsClient.create();
* RdsUtilities utilities = rdsClient.utilities();
* </pre>
* </p>
*
* <p>
* 2) Directly using the {@link #builder()} method.
*
* <pre>
* RdsUtilities utilities = RdsUtilities.builder()
* .credentialsProvider(DefaultCredentialsProvider.create())
* .region(Region.US_WEST_2)
* .build()
* </pre>
* </p>
*
* Note: This class does not make network calls.
*/
@SdkPublicApi
public interface RdsUtilities {
/**
* Create a builder that can be used to configure and create a {@link RdsUtilities}.
*/
static Builder builder() {
return new DefaultRdsUtilities.DefaultBuilder();
}
/**
* Generates an authorization tokens for IAM authentication to an RDS database.
*
* @param request The request used to generate the auth token
* @return String to use as the RDS auth token
* @throws IllegalArgumentException if the required parameters are not valid
*/
default String generateAuthenticationToken(Consumer<GenerateAuthenticationTokenRequest.Builder> request) {
return generateAuthenticationToken(GenerateAuthenticationTokenRequest.builder().applyMutation(request).build());
}
/**
* Generates an authorization tokens for IAM authentication to an RDS database.
*
* @param request The request used to generate the auth token
* @return String to use as the RDS auth token
* @throws IllegalArgumentException if the required parameters are not valid
*/
default String generateAuthenticationToken(GenerateAuthenticationTokenRequest request) {
throw new UnsupportedOperationException();
}
/**
* Builder for creating an instance of {@link RdsUtilities}. It can be configured using {@link RdsUtilities#builder()}.
* Once configured, the {@link RdsUtilities} can created using {@link #build()}.
*/
@SdkPublicApi
interface Builder {
/**
* The default region to use when working with the methods in {@link RdsUtilities} class.
*
* @return This object for method chaining
*/
Builder region(Region region);
/**
* The default credentials provider to use when working with the methods in {@link RdsUtilities} class.
*
* @return This object for method chaining
*/
default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) {
return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider);
}
/**
* The default credentials provider to use when working with the methods in {@link RdsUtilities} class.
*
* @return This object for method chaining
*/
default Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
throw new UnsupportedOperationException();
}
/**
* Create a {@link RdsUtilities}
*/
RdsUtilities build();
}
}
| 5,114 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/DefaultRdsUtilities.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import software.amazon.awssdk.annotations.Immutable;
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.Aws4Signer;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.model.GenerateAuthenticationTokenRequest;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.StringUtils;
@Immutable
@SdkInternalApi
final class DefaultRdsUtilities implements RdsUtilities {
private static final Logger log = Logger.loggerFor(RdsUtilities.class);
// The time the IAM token is good for. https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html
private static final Duration EXPIRATION_DURATION = Duration.ofMinutes(15);
private final Aws4Signer signer = Aws4Signer.create();
private final Region region;
private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider;
private final Clock clock;
DefaultRdsUtilities(DefaultBuilder builder) {
this(builder, Clock.systemUTC());
}
/**
* Test Only
*/
DefaultRdsUtilities(DefaultBuilder builder, Clock clock) {
this.credentialsProvider = builder.credentialsProvider;
this.region = builder.region;
this.clock = clock;
}
/**
* Used by RDS low-level client's utilities() method
*/
@SdkInternalApi
static RdsUtilities create(SdkClientConfiguration clientConfiguration) {
return new DefaultBuilder().clientConfiguration(clientConfiguration).build();
}
@Override
public String generateAuthenticationToken(GenerateAuthenticationTokenRequest request) {
SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host(request.hostname())
.port(request.port())
.encodedPath("/")
.putRawQueryParameter("DBUser", request.username())
.putRawQueryParameter("Action", "connect")
.build();
Instant expirationTime = Instant.now(clock).plus(EXPIRATION_DURATION);
Aws4PresignerParams presignRequest = Aws4PresignerParams.builder()
.signingClockOverride(clock)
.expirationTime(expirationTime)
.awsCredentials(resolveCredentials(request))
.signingName("rds-db")
.signingRegion(resolveRegion(request))
.build();
SdkHttpFullRequest fullRequest = signer.presign(httpRequest, presignRequest);
String signedUrl = fullRequest.getUri().toString();
// Format should be: <hostname>>:<port>>/?Action=connect&DBUser=<username>>&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expi...
// Note: This must be the real RDS hostname, not proxy or tunnels
String result = StringUtils.replacePrefixIgnoreCase(signedUrl, "https://", "");
log.debug(() -> "Generated RDS authentication token with expiration of " + expirationTime);
return result;
}
private Region resolveRegion(GenerateAuthenticationTokenRequest request) {
if (request.region() != null) {
return request.region();
}
if (this.region != null) {
return this.region;
}
throw new IllegalArgumentException("Region should be provided either in GenerateAuthenticationTokenRequest object " +
"or RdsUtilities object");
}
// TODO: update this to use AwsCredentialsIdentity when we migrate Signers to accept the new type.
private AwsCredentials resolveCredentials(GenerateAuthenticationTokenRequest request) {
if (request.credentialsIdentityProvider() != null) {
return CredentialUtils.toCredentials(
CompletableFutureUtils.joinLikeSync(request.credentialsIdentityProvider().resolveIdentity()));
}
if (this.credentialsProvider != null) {
return CredentialUtils.toCredentials(CompletableFutureUtils.joinLikeSync(this.credentialsProvider.resolveIdentity()));
}
throw new IllegalArgumentException("CredentialProvider should be provided either in GenerateAuthenticationTokenRequest " +
"object or RdsUtilities object");
}
@SdkInternalApi
static final class DefaultBuilder implements Builder {
private Region region;
private IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider;
DefaultBuilder() {
}
Builder clientConfiguration(SdkClientConfiguration clientConfiguration) {
this.credentialsProvider = clientConfiguration.option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER);
this.region = clientConfiguration.option(AwsClientOption.AWS_REGION);
return this;
}
@Override
public Builder region(Region region) {
this.region = region;
return this;
}
@Override
public Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
this.credentialsProvider = credentialsProvider;
return this;
}
/**
* Construct a {@link RdsUtilities} object.
*/
@Override
public RdsUtilities build() {
return new DefaultRdsUtilities(this);
}
}
}
| 5,115 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/StartDbInstanceAutomatedBackupsReplicationPresignInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.services.rds.model.StartDbInstanceAutomatedBackupsReplicationRequest;
import software.amazon.awssdk.services.rds.transform.StartDbInstanceAutomatedBackupsReplicationRequestMarshaller;
/**
* Handler for pre-signing {@link StartDbInstanceAutomatedBackupsReplicationRequest}.
*/
@SdkInternalApi
public final class StartDbInstanceAutomatedBackupsReplicationPresignInterceptor extends
RdsPresignInterceptor<StartDbInstanceAutomatedBackupsReplicationRequest> {
public static final StartDbInstanceAutomatedBackupsReplicationRequestMarshaller MARSHALLER =
new StartDbInstanceAutomatedBackupsReplicationRequestMarshaller(PROTOCOL_FACTORY);
public StartDbInstanceAutomatedBackupsReplicationPresignInterceptor() {
super(StartDbInstanceAutomatedBackupsReplicationRequest.class);
}
@Override
protected PresignableRequest adaptRequest(final StartDbInstanceAutomatedBackupsReplicationRequest originalRequest) {
return new PresignableRequest() {
@Override
public String getSourceRegion() {
return originalRequest.sourceRegion();
}
@Override
public SdkHttpFullRequest marshall() {
return MARSHALLER.marshall(originalRequest);
}
};
}
}
| 5,116 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/CopyDbClusterSnapshotPresignInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.services.rds.model.CopyDbClusterSnapshotRequest;
import software.amazon.awssdk.services.rds.transform.CopyDbClusterSnapshotRequestMarshaller;
/**
* Handler for pre-signing {@link CopyDbClusterSnapshotRequest}.
*/
@SdkInternalApi
public final class CopyDbClusterSnapshotPresignInterceptor extends RdsPresignInterceptor<CopyDbClusterSnapshotRequest> {
public static final CopyDbClusterSnapshotRequestMarshaller MARSHALLER =
new CopyDbClusterSnapshotRequestMarshaller(PROTOCOL_FACTORY);
public CopyDbClusterSnapshotPresignInterceptor() {
super(CopyDbClusterSnapshotRequest.class);
}
@Override
protected PresignableRequest adaptRequest(final CopyDbClusterSnapshotRequest originalRequest) {
return new PresignableRequest() {
@Override
public String getSourceRegion() {
return originalRequest.sourceRegion();
}
@Override
public SdkHttpFullRequest marshall() {
return MARSHALLER.marshall(originalRequest);
}
};
}
}
| 5,117 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/CreateDbClusterPresignInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.services.rds.model.CreateDbClusterRequest;
import software.amazon.awssdk.services.rds.transform.CreateDbClusterRequestMarshaller;
/**
* Handler for pre-signing {@link CreateDbClusterRequest}.
*/
@SdkInternalApi
public final class CreateDbClusterPresignInterceptor extends RdsPresignInterceptor<CreateDbClusterRequest> {
public static final CreateDbClusterRequestMarshaller MARSHALLER =
new CreateDbClusterRequestMarshaller(PROTOCOL_FACTORY);
public CreateDbClusterPresignInterceptor() {
super(CreateDbClusterRequest.class);
}
@Override
protected PresignableRequest adaptRequest(final CreateDbClusterRequest originalRequest) {
return new PresignableRequest() {
@Override
public String getSourceRegion() {
return originalRequest.sourceRegion();
}
@Override
public SdkHttpFullRequest marshall() {
return MARSHALLER.marshall(originalRequest);
}
};
}
}
| 5,118 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/CreateDbInstanceReadReplicaPresignInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.services.rds.model.CreateDbInstanceReadReplicaRequest;
import software.amazon.awssdk.services.rds.transform.CreateDbInstanceReadReplicaRequestMarshaller;
/**
* Handler for pre-signing {@link CreateDbInstanceReadReplicaRequest}.
*/
@SdkInternalApi
public final class CreateDbInstanceReadReplicaPresignInterceptor extends
RdsPresignInterceptor<CreateDbInstanceReadReplicaRequest> {
public static final CreateDbInstanceReadReplicaRequestMarshaller MARSHALLER =
new CreateDbInstanceReadReplicaRequestMarshaller(PROTOCOL_FACTORY);
public CreateDbInstanceReadReplicaPresignInterceptor() {
super(CreateDbInstanceReadReplicaRequest.class);
}
@Override
protected PresignableRequest adaptRequest(final CreateDbInstanceReadReplicaRequest originalRequest) {
return new PresignableRequest() {
@Override
public String getSourceRegion() {
return originalRequest.sourceRegion();
}
@Override
public SdkHttpFullRequest marshall() {
return MARSHALLER.marshall(originalRequest);
}
};
}
}
| 5,119 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/RdsPresignInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds.internal;
import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.AWS_CREDENTIALS;
import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME;
import java.net.URI;
import java.time.Clock;
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.Aws4Signer;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.awscore.AwsExecutionAttribute;
import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder;
import software.amazon.awssdk.core.Protocol;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
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.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.protocols.query.AwsQueryProtocolFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.model.RdsRequest;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* Abstract pre-sign handler that follows the pre-signing scheme outlined in the 'RDS Presigned URL for Cross-Region Copying'
* SEP.
*
* @param <T> The request type.
*/
@SdkInternalApi
public abstract class RdsPresignInterceptor<T extends RdsRequest> implements ExecutionInterceptor {
private static final URI CUSTOM_ENDPOINT_LOCALHOST = URI.create("http://localhost");
protected static final AwsQueryProtocolFactory PROTOCOL_FACTORY = AwsQueryProtocolFactory
.builder()
// Need an endpoint to marshall but this will be overwritten in modifyHttpRequest
.clientConfiguration(SdkClientConfiguration.builder()
.option(SdkClientOption.ENDPOINT, CUSTOM_ENDPOINT_LOCALHOST)
.build())
.build();
private static final String SERVICE_NAME = "rds";
private static final String PARAM_SOURCE_REGION = "SourceRegion";
private static final String PARAM_DESTINATION_REGION = "DestinationRegion";
private static final String PARAM_PRESIGNED_URL = "PreSignedUrl";
public interface PresignableRequest {
String getSourceRegion();
SdkHttpFullRequest marshall();
}
private final Class<T> requestClassToPreSign;
private final Clock signingOverrideClock;
public RdsPresignInterceptor(Class<T> requestClassToPreSign) {
this(requestClassToPreSign, null);
}
public RdsPresignInterceptor(Class<T> requestClassToPreSign, Clock signingOverrideClock) {
this.requestClassToPreSign = requestClassToPreSign;
this.signingOverrideClock = signingOverrideClock;
}
@Override
public final SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes) {
SdkHttpRequest request = context.httpRequest();
SdkRequest originalRequest = context.request();
if (!requestClassToPreSign.isInstance(originalRequest)) {
return request;
}
if (request.firstMatchingRawQueryParameter(PARAM_PRESIGNED_URL).isPresent()) {
return request;
}
PresignableRequest presignableRequest = adaptRequest(requestClassToPreSign.cast(originalRequest));
String sourceRegion = presignableRequest.getSourceRegion();
if (sourceRegion == null) {
return request;
}
String destinationRegion = executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION).id();
URI endpoint = createEndpoint(sourceRegion, SERVICE_NAME, executionAttributes);
SdkHttpFullRequest.Builder marshalledRequest = presignableRequest.marshall().toBuilder().uri(endpoint);
SdkHttpFullRequest requestToPresign =
marshalledRequest.method(SdkHttpMethod.GET)
.putRawQueryParameter(PARAM_DESTINATION_REGION, destinationRegion)
.removeQueryParameter(PARAM_SOURCE_REGION)
.build();
requestToPresign = presignRequest(requestToPresign, executionAttributes, sourceRegion);
String presignedUrl = requestToPresign.getUri().toString();
return request.toBuilder()
.putRawQueryParameter(PARAM_PRESIGNED_URL, presignedUrl)
// Remove the unmodeled params to stop them getting onto the wire
.removeQueryParameter(PARAM_SOURCE_REGION)
.build();
}
/**
* Adapts the request to the {@link PresignableRequest}.
*
* @param originalRequest the original request
* @return a PresignableRequest
*/
protected abstract PresignableRequest adaptRequest(T originalRequest);
private SdkHttpFullRequest presignRequest(SdkHttpFullRequest request,
ExecutionAttributes attributes,
String signingRegion) {
Aws4Signer signer = Aws4Signer.create();
Aws4PresignerParams presignerParams = Aws4PresignerParams.builder()
.signingRegion(Region.of(signingRegion))
.signingName(SERVICE_NAME)
.signingClockOverride(signingOverrideClock)
.awsCredentials(resolveCredentials(attributes))
.build();
return signer.presign(request, presignerParams);
}
private AwsCredentials resolveCredentials(ExecutionAttributes attributes) {
return attributes.getOptionalAttribute(SELECTED_AUTH_SCHEME)
.map(selectedAuthScheme -> selectedAuthScheme.identity())
.map(identityFuture -> CompletableFutureUtils.joinLikeSync(identityFuture))
.filter(identity -> identity instanceof AwsCredentialsIdentity)
.map(identity -> {
AwsCredentialsIdentity awsCredentialsIdentity = (AwsCredentialsIdentity) identity;
return CredentialUtils.toCredentials(awsCredentialsIdentity);
}).orElse(attributes.getAttribute(AWS_CREDENTIALS));
}
private URI createEndpoint(String regionName, String serviceName, ExecutionAttributes attributes) {
Region region = Region.of(regionName);
if (region == null) {
throw SdkClientException.builder()
.message("{" + serviceName + ", " + regionName + "} was not "
+ "found in region metadata. Update to latest version of SDK and try again.")
.build();
}
return new DefaultServiceEndpointBuilder(SERVICE_NAME, Protocol.HTTPS.toString())
.withRegion(region)
.withProfileFile(attributes.getAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER))
.withProfileName(attributes.getAttribute(SdkExecutionAttribute.PROFILE_NAME))
.withDualstackEnabled(attributes.getAttribute(AwsExecutionAttribute.DUALSTACK_ENDPOINT_ENABLED))
.withFipsEnabled(attributes.getAttribute(AwsExecutionAttribute.FIPS_ENDPOINT_ENABLED))
.getServiceEndpoint();
}
}
| 5,120 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/CopyDbSnapshotPresignInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds.internal;
import java.time.Clock;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.services.rds.model.CopyDbSnapshotRequest;
import software.amazon.awssdk.services.rds.transform.CopyDbSnapshotRequestMarshaller;
/**
* Handler for pre-signing {@link CopyDbSnapshotRequest}.
*/
@SdkInternalApi
public final class CopyDbSnapshotPresignInterceptor extends RdsPresignInterceptor<CopyDbSnapshotRequest> {
public static final CopyDbSnapshotRequestMarshaller MARSHALLER = new CopyDbSnapshotRequestMarshaller(PROTOCOL_FACTORY);
public CopyDbSnapshotPresignInterceptor() {
super(CopyDbSnapshotRequest.class);
}
@SdkTestInternalApi
CopyDbSnapshotPresignInterceptor(Clock signingDateOverride) {
super(CopyDbSnapshotRequest.class, signingDateOverride);
}
@Override
protected PresignableRequest adaptRequest(final CopyDbSnapshotRequest originalRequest) {
return new PresignableRequest() {
@Override
public String getSourceRegion() {
return originalRequest.sourceRegion();
}
@Override
public SdkHttpFullRequest marshall() {
return MARSHALLER.marshall(originalRequest);
}
};
}
}
| 5,121 |
0 | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds | Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/model/GenerateAuthenticationTokenRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.rds.model;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsUtilities;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Input parameters for generating an auth token for IAM database authentication.
*/
@SdkPublicApi
public final class GenerateAuthenticationTokenRequest implements
ToCopyableBuilder<GenerateAuthenticationTokenRequest.Builder, GenerateAuthenticationTokenRequest> {
private final String hostname;
private final int port;
private final String username;
private final Region region;
private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider;
private GenerateAuthenticationTokenRequest(BuilderImpl builder) {
this.hostname = Validate.notEmpty(builder.hostname, "hostname");
this.port = Validate.isPositive(builder.port, "port");
this.username = Validate.notEmpty(builder.username, "username");
this.region = builder.region;
this.credentialsProvider = builder.credentialsProvider;
}
/**
* @return The hostname of the database to connect to
*/
public String hostname() {
return hostname;
}
/**
* @return The port of the database to connect to
*/
public int port() {
return port;
}
/**
* @return The username to log in as.
*/
public String username() {
return username;
}
/**
* @return The region the database is hosted in. If specified, takes precedence over the value specified in
* {@link RdsUtilities.Builder#region(Region)}
*/
public Region region() {
return region;
}
/**
* @return The credentials provider to sign the IAM auth request with. If specified, takes precedence over the value
* specified in {@link RdsUtilities.Builder#credentialsProvider}}
*/
public AwsCredentialsProvider credentialsProvider() {
return CredentialUtils.toCredentialsProvider(credentialsProvider);
}
/**
* @return The credentials provider to sign the IAM auth request with. If specified, takes precedence over the value
* specified in {@link RdsUtilities.Builder#credentialsProvider(AwsCredentialsProvider)}}
*/
public IdentityProvider<? extends AwsCredentialsIdentity> credentialsIdentityProvider() {
return credentialsProvider;
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
/**
* Creates a builder for {@link RdsUtilities}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* A builder for a {@link GenerateAuthenticationTokenRequest}, created with {@link #builder()}.
*/
@SdkPublicApi
@NotThreadSafe
public interface Builder extends CopyableBuilder<Builder, GenerateAuthenticationTokenRequest> {
/**
* The hostname of the database to connect to
*
* @return This object for method chaining
*/
Builder hostname(String endpoint);
/**
* The port number the database is listening on.
*
* @return This object for method chaining
*/
Builder port(int port);
/**
* The username to log in as.
*
* @return This object for method chaining
*/
Builder username(String userName);
/**
* The region the database is hosted in. If specified, takes precedence over the value specified in
* {@link RdsUtilities.Builder#region(Region)}
*
* @return This object for method chaining
*/
Builder region(Region region);
/**
* The credentials provider to sign the IAM auth request with. If specified, takes precedence over the value
* specified in {@link RdsUtilities.Builder#credentialsProvider)}}
*
* @return This object for method chaining
*/
default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) {
return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider);
}
/**
* The credentials provider to sign the IAM auth request with. If specified, takes precedence over the value
* specified in {@link RdsUtilities.Builder#credentialsProvider}}
*
* @return This object for method chaining
*/
default Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
throw new UnsupportedOperationException();
}
@Override
GenerateAuthenticationTokenRequest build();
}
private static final class BuilderImpl implements Builder {
private String hostname;
private int port;
private String username;
private Region region;
private IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider;
private BuilderImpl() {
}
private BuilderImpl(GenerateAuthenticationTokenRequest request) {
this.hostname = request.hostname;
this.port = request.port;
this.username = request.username;
this.region = request.region;
this.credentialsProvider = request.credentialsProvider;
}
@Override
public Builder hostname(String endpoint) {
this.hostname = endpoint;
return this;
}
@Override
public Builder port(int port) {
this.port = port;
return this;
}
@Override
public Builder username(String userName) {
this.username = userName;
return this;
}
@Override
public Builder region(Region region) {
this.region = region;
return this;
}
@Override
public Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
this.credentialsProvider = credentialsProvider;
return this;
}
@Override
public GenerateAuthenticationTokenRequest build() {
return new GenerateAuthenticationTokenRequest(this);
}
}
} | 5,122 |
0 | Create_ds/aws-sdk-java-v2/services/swf/src/main/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/swf/src/main/java/software/amazon/awssdk/services/swf/package-info.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/**
* <fullname>Amazon Simple Workflow Service</fullname>
* <p>
* The Amazon Simple Workflow Service (Amazon SWF) makes it easy to build applications that use Amazon's cloud to
* coordinate work across distributed components. In Amazon SWF, a <i>task</i> represents a logical unit of work that is
* performed by a component of your workflow. Coordinating tasks in a workflow involves managing intertask dependencies,
* scheduling, and concurrency in accordance with the logical flow of the application.
* </p>
* <p>
* Amazon SWF gives you full control over implementing tasks and coordinating them without worrying about underlying
* complexities such as tracking their progress and maintaining their state.
* </p>
* <p>
* This documentation serves as reference only. For a broader overview of the Amazon SWF programming model, see the <a
* href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/">Amazon SWF Developer Guide</a>.
* </p>
*/
package software.amazon.awssdk.services.swf;
| 5,123 |
0 | Create_ds/aws-sdk-java-v2/services/swf/src/main/java/software/amazon/awssdk/services/swf | Create_ds/aws-sdk-java-v2/services/swf/src/main/java/software/amazon/awssdk/services/swf/internal/SwfHttpConfigurationOptions.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.swf.internal;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.utils.AttributeMap;
@SdkInternalApi
public final class SwfHttpConfigurationOptions {
private static final AttributeMap OPTIONS = AttributeMap
.builder()
.put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofMillis(90_000))
.put(SdkHttpConfigurationOption.MAX_CONNECTIONS, 1000)
.build();
private SwfHttpConfigurationOptions() {
}
public static AttributeMap defaultHttpConfig() {
return OPTIONS;
}
}
| 5,124 |
0 | Create_ds/aws-sdk-java-v2/services/cloudwatchevents/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/cloudwatchevents/src/it/java/software/amazon/awssdk/services/cloudwatchevents/CloudWatchEventsIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.cloudwatchevents;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.services.cloudwatchevents.model.DeleteRuleRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.DescribeRuleRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.DescribeRuleResponse;
import software.amazon.awssdk.services.cloudwatchevents.model.DisableRuleRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.EnableRuleRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.PutRuleRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.RuleState;
import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase;
public class CloudWatchEventsIntegrationTest extends AwsIntegrationTestBase {
private static final String RULE_NAME = "rule";
private static final String RULE_DESCRIPTION = "ruleDescription";
private static final String EVENT_PATTERN = "{ \"source\": [\"aws.ec2\"] }";
private static CloudWatchEventsClient events;
@BeforeClass
public static void setUpClient() throws Exception {
events = CloudWatchEventsClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build();
events.putRule(PutRuleRequest.builder()
.name(RULE_NAME)
.description(RULE_DESCRIPTION)
.eventPattern(EVENT_PATTERN)
.build()
);
// By default, a newly created rule is enabled
Assert.assertEquals(RuleState.ENABLED,
events.describeRule(DescribeRuleRequest.builder().name(RULE_NAME).build())
.state());
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
events.deleteRule(DeleteRuleRequest.builder().name(RULE_NAME).build());
}
@Test
public void basicTest() {
events.enableRule(EnableRuleRequest.builder().name(RULE_NAME).build());
DescribeRuleResponse describeRuleResult = events.describeRule(DescribeRuleRequest.builder()
.name(RULE_NAME).build());
Assert.assertEquals(RULE_NAME, describeRuleResult.name());
Assert.assertEquals(RULE_DESCRIPTION, describeRuleResult.description());
Assert.assertEquals(RuleState.ENABLED,
describeRuleResult.state());
events.disableRule(DisableRuleRequest.builder().name(RULE_NAME).build());
Assert.assertEquals(RuleState.DISABLED,
events.describeRule(DescribeRuleRequest.builder().name(RULE_NAME).build())
.state());
}
}
| 5,125 |
0 | Create_ds/aws-sdk-java-v2/services/datapipeline/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/datapipeline/src/it/java/software/amazon/awssdk/services/datapipeline/IntegrationTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.datapipeline;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.junit.BeforeClass;
import software.amazon.awssdk.testutils.service.AwsTestBase;
/**
* Base class for all STS integration tests. Loads AWS credentials from a
* properties file on disk, provides helper methods for tests, and instantiates
* the STS client object for all tests to use.
*/
public class IntegrationTestBase extends AwsTestBase {
/** The shared DP client for all tests to use. */
protected static DataPipelineClient dataPipeline;
@BeforeClass
public static void setUp() throws FileNotFoundException, IOException {
setUpCredentials();
dataPipeline = DataPipelineClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build();
}
}
| 5,126 |
0 | Create_ds/aws-sdk-java-v2/services/datapipeline/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/datapipeline/src/it/java/software/amazon/awssdk/services/datapipeline/DataPipelineIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.datapipeline;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.AfterClass;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.services.datapipeline.model.ActivatePipelineRequest;
import software.amazon.awssdk.services.datapipeline.model.ActivatePipelineResponse;
import software.amazon.awssdk.services.datapipeline.model.CreatePipelineRequest;
import software.amazon.awssdk.services.datapipeline.model.CreatePipelineResponse;
import software.amazon.awssdk.services.datapipeline.model.DeletePipelineRequest;
import software.amazon.awssdk.services.datapipeline.model.DescribeObjectsRequest;
import software.amazon.awssdk.services.datapipeline.model.DescribeObjectsResponse;
import software.amazon.awssdk.services.datapipeline.model.DescribePipelinesRequest;
import software.amazon.awssdk.services.datapipeline.model.DescribePipelinesResponse;
import software.amazon.awssdk.services.datapipeline.model.Field;
import software.amazon.awssdk.services.datapipeline.model.GetPipelineDefinitionRequest;
import software.amazon.awssdk.services.datapipeline.model.GetPipelineDefinitionResponse;
import software.amazon.awssdk.services.datapipeline.model.ListPipelinesRequest;
import software.amazon.awssdk.services.datapipeline.model.ListPipelinesResponse;
import software.amazon.awssdk.services.datapipeline.model.PipelineObject;
import software.amazon.awssdk.services.datapipeline.model.PutPipelineDefinitionRequest;
import software.amazon.awssdk.services.datapipeline.model.PutPipelineDefinitionResponse;
import software.amazon.awssdk.services.datapipeline.model.ValidatePipelineDefinitionRequest;
import software.amazon.awssdk.services.datapipeline.model.ValidatePipelineDefinitionResponse;
public class DataPipelineIntegrationTest extends IntegrationTestBase {
private static final String PIPELINE_NAME = "my-pipeline";
private static final String PIPELINE_ID = "my-pipeline" + System.currentTimeMillis();
private static final String PIPELINE_DESCRIPTION = "my pipeline";
private static final String OBJECT_ID = "123";
private static final String OBJECT_NAME = "object";
private static final String VALID_KEY = "startDateTime";
private static final String INVALID_KEY = "radom_key";
private static final String FIELD_VALUE = "2012-09-25T17:00:00";
private static String pipelineId;
@AfterClass
public static void tearDown() {
try {
dataPipeline.deletePipeline(DeletePipelineRequest.builder().pipelineId(pipelineId).build());
} catch (Exception e) {
// Do nothing.
}
}
@Test
public void testPipelineOperations() throws InterruptedException {
// Create a pipeline.
CreatePipelineResponse createPipelineResult = dataPipeline.createPipeline(
CreatePipelineRequest.builder()
.name(PIPELINE_NAME)
.uniqueId(PIPELINE_ID)
.description(PIPELINE_DESCRIPTION)
.build());
pipelineId = createPipelineResult.pipelineId();
assertNotNull(pipelineId);
// Invalid field
PipelineObject pipelineObject = PipelineObject.builder()
.id(OBJECT_ID + "1")
.name(OBJECT_NAME)
.fields(Field.builder()
.key(INVALID_KEY)
.stringValue(FIELD_VALUE)
.build())
.build();
ValidatePipelineDefinitionResponse validatePipelineDefinitionResult =
dataPipeline.validatePipelineDefinition(ValidatePipelineDefinitionRequest.builder()
.pipelineId(pipelineId)
.pipelineObjects(pipelineObject)
.build());
assertTrue(validatePipelineDefinitionResult.errored());
assertNotNull(validatePipelineDefinitionResult.validationErrors());
assertTrue(validatePipelineDefinitionResult.validationErrors().size() > 0);
assertNotNull(validatePipelineDefinitionResult.validationErrors().get(0));
assertNotNull(validatePipelineDefinitionResult.validationWarnings());
assertEquals(0, validatePipelineDefinitionResult.validationWarnings().size());
// Valid field
pipelineObject = PipelineObject.builder()
.id(OBJECT_ID)
.name(OBJECT_NAME)
.fields(Field.builder()
.key(VALID_KEY)
.stringValue(FIELD_VALUE)
.build())
.build();
// Validate pipeline definition.
validatePipelineDefinitionResult =
dataPipeline.validatePipelineDefinition(ValidatePipelineDefinitionRequest.builder()
.pipelineId(pipelineId)
.pipelineObjects(pipelineObject)
.build());
assertFalse(validatePipelineDefinitionResult.errored());
assertNotNull(validatePipelineDefinitionResult.validationErrors());
assertEquals(0, validatePipelineDefinitionResult.validationErrors().size());
assertNotNull(validatePipelineDefinitionResult.validationWarnings());
assertEquals(0, validatePipelineDefinitionResult.validationWarnings().size());
// Put pipeline definition.
PutPipelineDefinitionResponse putPipelineDefinitionResult =
dataPipeline.putPipelineDefinition(PutPipelineDefinitionRequest.builder()
.pipelineId(pipelineId)
.pipelineObjects(pipelineObject)
.build());
assertFalse(putPipelineDefinitionResult.errored());
assertNotNull(putPipelineDefinitionResult.validationErrors());
assertEquals(0, putPipelineDefinitionResult.validationErrors().size());
assertNotNull(putPipelineDefinitionResult.validationWarnings());
assertEquals(0, putPipelineDefinitionResult.validationWarnings().size());
// Get pipeline definition.
GetPipelineDefinitionResponse pipelineDefinitionResult =
dataPipeline.getPipelineDefinition(GetPipelineDefinitionRequest.builder().pipelineId(pipelineId).build());
assertEquals(1, pipelineDefinitionResult.pipelineObjects().size());
assertEquals(OBJECT_ID, pipelineDefinitionResult.pipelineObjects().get(0).id());
assertEquals(OBJECT_NAME, pipelineDefinitionResult.pipelineObjects().get(0).name());
assertEquals(1, pipelineDefinitionResult.pipelineObjects().get(0).fields().size());
assertTrue(pipelineDefinitionResult.pipelineObjects().get(0).fields()
.contains(Field.builder().key(VALID_KEY).stringValue(FIELD_VALUE).build()));
// Activate a pipeline.
ActivatePipelineResponse activatePipelineResult =
dataPipeline.activatePipeline(ActivatePipelineRequest.builder().pipelineId(pipelineId).build());
assertNotNull(activatePipelineResult);
// List pipeline.
ListPipelinesResponse listPipelinesResult = dataPipeline.listPipelines(ListPipelinesRequest.builder().build());
assertTrue(listPipelinesResult.pipelineIdList().size() > 0);
assertNotNull(pipelineId, listPipelinesResult.pipelineIdList().get(0).id());
assertNotNull(PIPELINE_NAME, listPipelinesResult.pipelineIdList().get(0).name());
Thread.sleep(1000 * 5);
// Describe objects.
DescribeObjectsResponse describeObjectsResult =
dataPipeline.describeObjects(DescribeObjectsRequest.builder().pipelineId(pipelineId).objectIds(OBJECT_ID).build());
assertEquals(1, describeObjectsResult.pipelineObjects().size());
assertEquals(OBJECT_ID, describeObjectsResult.pipelineObjects().get(0).id());
assertEquals(OBJECT_NAME, describeObjectsResult.pipelineObjects().get(0).name());
assertTrue(describeObjectsResult.pipelineObjects().get(0).fields()
.contains(Field.builder().key(VALID_KEY).stringValue(FIELD_VALUE).build()));
assertTrue(describeObjectsResult.pipelineObjects().get(0).fields()
.contains(Field.builder().key("@pipelineId").stringValue(pipelineId).build()));
// Describe a pipeline.
DescribePipelinesResponse describepipelinesResult =
dataPipeline.describePipelines(DescribePipelinesRequest.builder().pipelineIds(pipelineId).build());
assertEquals(1, describepipelinesResult.pipelineDescriptionList().size());
assertEquals(PIPELINE_NAME, describepipelinesResult.pipelineDescriptionList().get(0).name());
assertEquals(pipelineId, describepipelinesResult.pipelineDescriptionList().get(0).pipelineId());
assertEquals(PIPELINE_DESCRIPTION, describepipelinesResult.pipelineDescriptionList().get(0).description());
assertTrue(describepipelinesResult.pipelineDescriptionList().get(0).fields().size() > 0);
assertTrue(describepipelinesResult.pipelineDescriptionList().get(0).fields()
.contains(Field.builder().key("name").stringValue(PIPELINE_NAME).build()));
assertTrue(describepipelinesResult.pipelineDescriptionList().get(0).fields()
.contains(Field.builder().key("@id").stringValue(pipelineId).build()));
assertTrue(describepipelinesResult.pipelineDescriptionList().get(0).fields()
.contains(Field.builder().key("uniqueId").stringValue(PIPELINE_ID).build()));
// Delete a pipeline.
dataPipeline.deletePipeline(DeletePipelineRequest.builder().pipelineId(pipelineId).build());
Thread.sleep(1000 * 5);
try {
describepipelinesResult = dataPipeline.describePipelines(DescribePipelinesRequest.builder().pipelineIds(pipelineId).build());
if (describepipelinesResult.pipelineDescriptionList().size() > 0) {
fail();
}
} catch (SdkServiceException e) {
// Ignored or expected.
}
}
}
| 5,127 |
0 | Create_ds/aws-sdk-java-v2/services/elasticsearch/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/elasticsearch/src/it/java/software/amazon/awssdk/services/elasticsearch/ServiceIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.elasticsearch;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.services.elasticsearch.model.AddTagsRequest;
import software.amazon.awssdk.services.elasticsearch.model.CreateElasticsearchDomainRequest;
import software.amazon.awssdk.services.elasticsearch.model.DeleteElasticsearchDomainRequest;
import software.amazon.awssdk.services.elasticsearch.model.DescribeElasticsearchDomainConfigRequest;
import software.amazon.awssdk.services.elasticsearch.model.DescribeElasticsearchDomainRequest;
import software.amazon.awssdk.services.elasticsearch.model.DescribeElasticsearchDomainsRequest;
import software.amazon.awssdk.services.elasticsearch.model.DomainInfo;
import software.amazon.awssdk.services.elasticsearch.model.EBSOptions;
import software.amazon.awssdk.services.elasticsearch.model.ElasticsearchDomainConfig;
import software.amazon.awssdk.services.elasticsearch.model.ElasticsearchDomainStatus;
import software.amazon.awssdk.services.elasticsearch.model.ListDomainNamesRequest;
import software.amazon.awssdk.services.elasticsearch.model.ListTagsRequest;
import software.amazon.awssdk.services.elasticsearch.model.Tag;
import software.amazon.awssdk.services.elasticsearch.model.VolumeType;
import software.amazon.awssdk.testutils.service.AwsTestBase;
public class ServiceIntegrationTest extends AwsTestBase {
private static ElasticsearchClient es;
private static final String DOMAIN_NAME = "java-es-test-" + System.currentTimeMillis();
@BeforeClass
public static void setup() throws IOException {
setUpCredentials();
es = ElasticsearchClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build();
}
@AfterClass
public static void tearDown() {
es.deleteElasticsearchDomain(DeleteElasticsearchDomainRequest.builder().domainName(DOMAIN_NAME).build());
}
@Test
public void testOperations() {
String domainArn = testCreateDomain();
testListDomainNames();
testDescribeDomain();
testDescribeDomains();
testDescribeDomainConfig();
testAddAndListTags(domainArn);
}
private String testCreateDomain() {
ElasticsearchDomainStatus status = es.createElasticsearchDomain(
CreateElasticsearchDomainRequest
.builder()
.ebsOptions(EBSOptions.builder()
.ebsEnabled(true)
.volumeSize(10)
.volumeType(VolumeType.STANDARD)
.build())
.domainName(DOMAIN_NAME)
.build()).domainStatus();
assertEquals(DOMAIN_NAME, status.domainName());
assertValidDomainStatus(status);
return status.arn();
}
private void testDescribeDomain() {
ElasticsearchDomainStatus status = es.describeElasticsearchDomain(
DescribeElasticsearchDomainRequest.builder()
.domainName(DOMAIN_NAME).build()).domainStatus();
assertEquals(DOMAIN_NAME, status.domainName());
assertValidDomainStatus(status);
}
private void testDescribeDomains() {
ElasticsearchDomainStatus status = es
.describeElasticsearchDomains(
DescribeElasticsearchDomainsRequest.builder()
.domainNames(DOMAIN_NAME).build())
.domainStatusList().get(0);
assertEquals(DOMAIN_NAME, status.domainName());
assertValidDomainStatus(status);
}
private void testListDomainNames() {
List<String> domainNames = toDomainNameList(es.listDomainNames(
ListDomainNamesRequest.builder().build()).domainNames());
assertThat(domainNames, hasItem(DOMAIN_NAME));
}
private List<String> toDomainNameList(Collection<DomainInfo> domainInfos) {
List<String> names = new LinkedList<String>();
for (DomainInfo info : domainInfos) {
names.add(info.domainName());
}
return names;
}
private void testDescribeDomainConfig() {
ElasticsearchDomainConfig config = es
.describeElasticsearchDomainConfig(
DescribeElasticsearchDomainConfigRequest.builder()
.domainName(DOMAIN_NAME).build()).domainConfig();
assertValidDomainConfig(config);
}
private void testAddAndListTags(String arn) {
Tag tag = Tag.builder().key("name").value("foo").build();
es.addTags(AddTagsRequest.builder().arn(arn).tagList(tag).build());
List<Tag> tags = es.listTags(ListTagsRequest.builder().arn(arn).build()).tagList();
assertThat(tags, hasItem(tag));
}
private void assertValidDomainStatus(ElasticsearchDomainStatus status) {
assertTrue(status.created());
assertNotNull(status.arn());
assertNotNull(status.accessPolicies());
assertNotNull(status.advancedOptions());
assertNotNull(status.domainId());
assertNotNull(status.ebsOptions());
assertNotNull(status.elasticsearchClusterConfig());
assertNotNull(status.snapshotOptions());
}
private void assertValidDomainConfig(ElasticsearchDomainConfig config) {
assertNotNull(config.accessPolicies());
assertNotNull(config.advancedOptions());
assertNotNull(config.ebsOptions());
assertNotNull(config.elasticsearchClusterConfig());
assertNotNull(config.snapshotOptions());
}
}
| 5,128 |
0 | Create_ds/aws-sdk-java-v2/services/codecommit/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/codecommit/src/it/java/software/amazon/awssdk/services/codecommit/AwsCodeCommitServiceIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.codecommit;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.services.codecommit.model.CreateRepositoryRequest;
import software.amazon.awssdk.services.codecommit.model.DeleteRepositoryRequest;
import software.amazon.awssdk.services.codecommit.model.GetRepositoryRequest;
import software.amazon.awssdk.services.codecommit.model.RepositoryDoesNotExistException;
import software.amazon.awssdk.services.codecommit.model.RepositoryMetadata;
import software.amazon.awssdk.testutils.service.AwsTestBase;
/**
* Smoke test for {@link CodeCommitClient}.
*/
public class AwsCodeCommitServiceIntegrationTest extends AwsTestBase {
private static final String REPO_NAME = "java-sdk-test-repo-" + System.currentTimeMillis();
private static CodeCommitClient client;
@BeforeClass
public static void setup() throws FileNotFoundException, IOException {
setUpCredentials();
client = CodeCommitClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build();
}
@AfterClass
public static void cleanup() {
try {
client.deleteRepository(DeleteRepositoryRequest.builder()
.repositoryName(REPO_NAME)
.build());
} catch (Exception ignored) {
System.err.println("Failed to delete repository " + ignored);
}
}
@Test
public void testOperations() {
// CreateRepository
client.createRepository(CreateRepositoryRequest.builder()
.repositoryName(REPO_NAME)
.repositoryDescription("My test repo")
.build());
// GetRepository
RepositoryMetadata repoMd = client.getRepository(GetRepositoryRequest.builder()
.repositoryName(REPO_NAME)
.build()
).repositoryMetadata();
Assert.assertEquals(REPO_NAME, repoMd.repositoryName());
assertValid_RepositoryMetadata(repoMd);
// Can't perform any branch-related operations since we need to create
// the first branch by pushing a commit via git.
// DeleteRepository
client.deleteRepository(DeleteRepositoryRequest.builder()
.repositoryName(REPO_NAME)
.build());
}
@Test(expected = RepositoryDoesNotExistException.class)
public void testExceptionHandling() {
String nonExistentRepoName = UUID.randomUUID().toString();
client.getRepository(GetRepositoryRequest.builder()
.repositoryName(nonExistentRepoName)
.build());
}
private void assertValid_RepositoryMetadata(RepositoryMetadata md) {
Assert.assertNotNull(md.accountId());
Assert.assertNotNull(md.arn());
Assert.assertNotNull(md.cloneUrlHttp());
Assert.assertNotNull(md.cloneUrlSsh());
Assert.assertNotNull(md.repositoryDescription());
Assert.assertNotNull(md.repositoryId());
Assert.assertNotNull(md.repositoryName());
Assert.assertNotNull(md.creationDate());
Assert.assertNotNull(md.lastModifiedDate());
}
}
| 5,129 |
0 | Create_ds/aws-sdk-java-v2/services/apigateway/src/test/java/software/amazon/awssdk/services/apigateway | Create_ds/aws-sdk-java-v2/services/apigateway/src/test/java/software/amazon/awssdk/services/apigateway/internal/AcceptJsonInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.apigateway.internal;
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.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import java.net.URI;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link AcceptJsonInterceptor}.
*/
@RunWith(MockitoJUnitRunner.class)
public class AcceptJsonInterceptorTest {
private static final AcceptJsonInterceptor interceptor = new AcceptJsonInterceptor();
@Mock
private Context.ModifyHttpRequest ctx;
@Test
public void doesNotClobberExistingValue() {
SdkHttpRequest request = newRequest("some-value");
Mockito.when(ctx.httpRequest()).thenReturn(request);
request = interceptor.modifyHttpRequest(ctx, new ExecutionAttributes());
assertThat(request.headers().get("Accept")).containsOnly("some-value");
}
@Test
public void addsStandardAcceptHeaderIfMissing() {
SdkHttpRequest request = newRequest(null);
Mockito.when(ctx.httpRequest()).thenReturn(request);
request = interceptor.modifyHttpRequest(ctx, new ExecutionAttributes());
assertThat(request.headers().get("Accept")).containsOnly("application/json");
}
private SdkHttpFullRequest newRequest(String accept) {
SdkHttpFullRequest.Builder builder = SdkHttpFullRequest.builder()
.uri(URI.create("https://amazonaws.com"))
.method(SdkHttpMethod.GET);
if (accept != null) {
builder.appendHeader("Accept", accept);
}
return builder.build();
}
}
| 5,130 |
0 | Create_ds/aws-sdk-java-v2/services/apigateway/src/test/java/software/amazon/awssdk/services/apigateway | Create_ds/aws-sdk-java-v2/services/apigateway/src/test/java/software/amazon/awssdk/services/apigateway/model/GetUsageRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.apigateway.model;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import java.net.URI;
import java.util.concurrent.CompletionException;
import org.assertj.core.api.ThrowableAssert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.apigateway.ApiGatewayAsyncClient;
import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
@WireMockTest
class GetUsageRequestTest {
private int wireMockPort;
private ApiGatewayClient client;
private ApiGatewayAsyncClient asyncClient;
@BeforeEach
void setUp(WireMockRuntimeInfo wmRuntimeInfo) {
wireMockPort = wmRuntimeInfo.getHttpPort();
client = ApiGatewayClient.builder()
.credentialsProvider(StaticCredentialsProvider
.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_WEST_2)
.endpointOverride(URI.create("http://localhost:" + wireMockPort))
.build();
asyncClient = ApiGatewayAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider
.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_WEST_2)
.endpointOverride(URI.create("http://localhost:" + wireMockPort))
.build();
}
@Test
void marshall_syncMissingUploadIdButValidationDisabled_ThrowsException() {
stubAndRespondWith(200, "");
GetUsageRequest request = getUsageRequestWithDates(null, "20221115");
assertThatNoException().isThrownBy(() -> client.getUsage(request));
}
@Test
void marshall_syncEmptyStartDate_encodesAsEmptyValue() {
stubAndRespondWith(200, "");
GetUsageRequest request = getUsageRequestWithDates("", "20221115");
client.getUsage(request);
verify(anyRequestedFor(anyUrl()).withQueryParam("startDate", equalTo("")));
}
@Test
void marshall_syncNonEmptyStartDate_encodesValue() {
stubAndRespondWith(200, "");
GetUsageRequest request = getUsageRequestWithDates("20221101", "20221115");
client.getUsage(request);
verify(anyRequestedFor(anyUrl()).withQueryParam("startDate", equalTo("20221101")));
}
@Test
void marshall_asyncMissingStartDateButValidationDisabled_ThrowsException() {
stubAndRespondWith(200, "");
GetUsageRequest request = getUsageRequestWithDates(null, "20221115");
assertThatNoException().isThrownBy(() -> asyncClient.getUsage(request).join());
}
@Test
void marshall_asyncEmptyStartDate_encodesAsEmptyValue() {
stubAndRespondWith(200, "");
GetUsageRequest request = getUsageRequestWithDates("", "20221115");
asyncClient.getUsage(request).join();
verify(anyRequestedFor(anyUrl()).withQueryParam("startDate", equalTo("")));
}
@Test
void marshall_asyncNonEmptyStartDate_encodesValue() {
stubAndRespondWith(200, "");
GetUsageRequest request = getUsageRequestWithDates("20221101", "20221115");
asyncClient.getUsage(request).join();
verify(anyRequestedFor(anyUrl()).withQueryParam("startDate", equalTo("20221101")));
}
private static GetUsageRequest getUsageRequestWithDates(String startDate, String endDate) {
return GetUsageRequest.builder()
.usagePlanId("myUsagePlanId")
.startDate(startDate)
.endDate(endDate)
.build();
}
private static void stubAndRespondWith(int status, String body) {
stubFor(any(urlMatching(".*"))
.willReturn(aResponse().withStatus(status).withBody(body)));
}
}
| 5,131 |
0 | Create_ds/aws-sdk-java-v2/services/apigateway/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/apigateway/src/it/java/software/amazon/awssdk/services/apigateway/IntegrationTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.apigateway;
import java.io.IOException;
import org.junit.BeforeClass;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.testutils.service.AwsTestBase;
public class IntegrationTestBase extends AwsTestBase {
protected static ApiGatewayClient apiGateway;
@BeforeClass
public static void setUp() throws IOException {
apiGateway = ApiGatewayClient.builder().region(Region.US_EAST_1).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build();
}
}
| 5,132 |
0 | Create_ds/aws-sdk-java-v2/services/apigateway/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/apigateway/src/it/java/software/amazon/awssdk/services/apigateway/ServiceIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.apigateway;
import com.google.common.util.concurrent.RateLimiter;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.Assert;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.services.apigateway.model.CreateApiKeyRequest;
import software.amazon.awssdk.services.apigateway.model.CreateApiKeyResponse;
import software.amazon.awssdk.services.apigateway.model.CreateResourceRequest;
import software.amazon.awssdk.services.apigateway.model.CreateResourceResponse;
import software.amazon.awssdk.services.apigateway.model.CreateRestApiRequest;
import software.amazon.awssdk.services.apigateway.model.CreateRestApiResponse;
import software.amazon.awssdk.services.apigateway.model.DeleteRestApiRequest;
import software.amazon.awssdk.services.apigateway.model.GetApiKeyRequest;
import software.amazon.awssdk.services.apigateway.model.GetApiKeyResponse;
import software.amazon.awssdk.services.apigateway.model.GetResourceRequest;
import software.amazon.awssdk.services.apigateway.model.GetResourceResponse;
import software.amazon.awssdk.services.apigateway.model.GetResourcesRequest;
import software.amazon.awssdk.services.apigateway.model.GetResourcesResponse;
import software.amazon.awssdk.services.apigateway.model.GetRestApiRequest;
import software.amazon.awssdk.services.apigateway.model.GetRestApiResponse;
import software.amazon.awssdk.services.apigateway.model.IntegrationType;
import software.amazon.awssdk.services.apigateway.model.NotFoundException;
import software.amazon.awssdk.services.apigateway.model.Op;
import software.amazon.awssdk.services.apigateway.model.PatchOperation;
import software.amazon.awssdk.services.apigateway.model.PutIntegrationRequest;
import software.amazon.awssdk.services.apigateway.model.PutIntegrationResponse;
import software.amazon.awssdk.services.apigateway.model.PutMethodRequest;
import software.amazon.awssdk.services.apigateway.model.PutMethodResponse;
import software.amazon.awssdk.services.apigateway.model.Resource;
import software.amazon.awssdk.services.apigateway.model.RestApi;
import software.amazon.awssdk.services.apigateway.model.TooManyRequestsException;
import software.amazon.awssdk.services.apigateway.model.UpdateApiKeyRequest;
import software.amazon.awssdk.services.apigateway.model.UpdateResourceRequest;
import software.amazon.awssdk.services.apigateway.model.UpdateRestApiRequest;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.Logger;
public class ServiceIntegrationTest extends IntegrationTestBase {
private static final Logger log = Logger.loggerFor(ServiceIntegrationTest.class);
private static final String NAME_PREFIX = "java-sdk-integration-";
private static final String NAME = NAME_PREFIX + System.currentTimeMillis();
private static final String DESCRIPTION = "fooDesc";
// Limit deletes to once every 31 seconds
// https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#api-gateway-control-service-limits-table
private static final Lazy<RateLimiter> DELETE_RATE_LIMITER = new Lazy<>(() -> RateLimiter.create(1.0 / 31));
private static String restApiId = null;
@BeforeClass
public static void createRestApi() {
deleteStaleRestApis();
CreateRestApiResponse createRestApiResult = apiGateway.createRestApi(
CreateRestApiRequest.builder().name(NAME)
.description(DESCRIPTION).build());
Assert.assertNotNull(createRestApiResult);
Assert.assertNotNull(createRestApiResult.description());
Assert.assertNotNull(createRestApiResult.id());
Assert.assertNotNull(createRestApiResult.name());
Assert.assertNotNull(createRestApiResult.createdDate());
Assert.assertEquals(createRestApiResult.name(), NAME);
Assert.assertEquals(createRestApiResult.description(), DESCRIPTION);
restApiId = createRestApiResult.id();
}
@AfterClass
public static void deleteRestApiKey() {
if (restApiId != null) {
DELETE_RATE_LIMITER.getValue().acquire();
try {
apiGateway.deleteRestApi(DeleteRestApiRequest.builder().restApiId(restApiId).build());
} catch (TooManyRequestsException e) {
log.warn(() -> String.format("Failed to delete REST API %s (%s). This API should be deleted automatically in a "
+ "future 'deleteStaleRestApis' execution.",
NAME, restApiId), e);
}
}
}
private static void deleteStaleRestApis() {
Instant startTime = Instant.now();
Duration maxRunTime = Duration.ofMinutes(5);
Duration maxApiAge = Duration.ofDays(7);
AtomicInteger success = new AtomicInteger();
AtomicInteger failure = new AtomicInteger();
log.info(() -> String.format("Searching for stale REST APIs older than %s days...", maxApiAge.toDays()));
for (RestApi api : apiGateway.getRestApisPaginator().items()) {
if (Instant.now().isAfter(startTime.plus(maxRunTime))) {
log.info(() -> String.format("More than %s has elapsed trying to delete stale REST APIs, giving up for this run. "
+ "Successfully deleted: %s. Failed to delete: %s.",
maxRunTime, success.get(), failure.get()));
return;
}
Duration apiAge = Duration.between(api.createdDate(), Instant.now());
if (api.name().startsWith(NAME_PREFIX) && apiAge.compareTo(maxApiAge) > 0) {
DELETE_RATE_LIMITER.getValue().acquire();
try {
apiGateway.deleteRestApi(r -> r.restApiId(api.id()));
log.info(() -> String.format("Successfully deleted REST API %s (%s) which was %s days old.",
api.name(), api.id(), apiAge.toDays()));
success.incrementAndGet();
} catch (Exception e) {
log.error(() -> String.format("Failed to delete REST API %s (%s) which is %s days old.",
api.name(), api.id(), apiAge.toDays()), e);
failure.incrementAndGet();
}
}
}
log.info(() -> String.format("Finished searching for stale REST APIs. Successfully deleted: %s. Failed to delete: %s.",
success.get(), failure.get()));
}
@Test
public void testUpdateRetrieveRestApi() {
PatchOperation patch = PatchOperation.builder().op(Op.REPLACE)
.path("/description").value("updatedDesc").build();
apiGateway.updateRestApi(UpdateRestApiRequest.builder().restApiId(restApiId)
.patchOperations(patch).build());
GetRestApiResponse getRestApiResult = apiGateway
.getRestApi(GetRestApiRequest.builder().restApiId(restApiId).build());
Assert.assertNotNull(getRestApiResult);
Assert.assertNotNull(getRestApiResult.description());
Assert.assertNotNull(getRestApiResult.id());
Assert.assertNotNull(getRestApiResult.name());
Assert.assertNotNull(getRestApiResult.createdDate());
Assert.assertEquals(getRestApiResult.name(), NAME);
Assert.assertEquals(getRestApiResult.description(), "updatedDesc");
}
@Test
public void testCreateUpdateRetrieveApiKey() {
CreateApiKeyResponse createApiKeyResult = apiGateway
.createApiKey(CreateApiKeyRequest.builder().name(NAME)
.description(DESCRIPTION).build());
Assert.assertNotNull(createApiKeyResult);
Assert.assertNotNull(createApiKeyResult.description());
Assert.assertNotNull(createApiKeyResult.id());
Assert.assertNotNull(createApiKeyResult.name());
Assert.assertNotNull(createApiKeyResult.createdDate());
Assert.assertNotNull(createApiKeyResult.enabled());
Assert.assertNotNull(createApiKeyResult.lastUpdatedDate());
Assert.assertNotNull(createApiKeyResult.stageKeys());
String apiKeyId = createApiKeyResult.id();
Assert.assertEquals(createApiKeyResult.name(), NAME);
Assert.assertEquals(createApiKeyResult.description(), DESCRIPTION);
PatchOperation patch = PatchOperation.builder().op(Op.REPLACE)
.path("/description").value("updatedDesc").build();
apiGateway.updateApiKey(UpdateApiKeyRequest.builder().apiKey(apiKeyId)
.patchOperations(patch).build());
GetApiKeyResponse getApiKeyResult = apiGateway
.getApiKey(GetApiKeyRequest.builder().apiKey(apiKeyId).build());
Assert.assertNotNull(getApiKeyResult);
Assert.assertNotNull(getApiKeyResult.description());
Assert.assertNotNull(getApiKeyResult.id());
Assert.assertNotNull(getApiKeyResult.name());
Assert.assertNotNull(getApiKeyResult.createdDate());
Assert.assertNotNull(getApiKeyResult.enabled());
Assert.assertNotNull(getApiKeyResult.lastUpdatedDate());
Assert.assertNotNull(getApiKeyResult.stageKeys());
Assert.assertEquals(getApiKeyResult.id(), apiKeyId);
Assert.assertEquals(getApiKeyResult.name(), NAME);
Assert.assertEquals(getApiKeyResult.description(), "updatedDesc");
}
@Test
public void testResourceOperations() {
GetResourcesResponse resourcesResult = apiGateway
.getResources(GetResourcesRequest.builder()
.restApiId(restApiId).build());
List<Resource> resources = resourcesResult.items();
Assert.assertEquals(resources.size(), 1);
Resource rootResource = resources.get(0);
Assert.assertNotNull(rootResource);
Assert.assertEquals(rootResource.path(), "/");
String rootResourceId = rootResource.id();
CreateResourceResponse createResourceResult = apiGateway
.createResource(CreateResourceRequest.builder()
.restApiId(restApiId)
.pathPart("fooPath")
.parentId(rootResourceId).build());
Assert.assertNotNull(createResourceResult);
Assert.assertNotNull(createResourceResult.id());
Assert.assertNotNull(createResourceResult.parentId());
Assert.assertNotNull(createResourceResult.path());
Assert.assertNotNull(createResourceResult.pathPart());
Assert.assertEquals(createResourceResult.pathPart(), "fooPath");
Assert.assertEquals(createResourceResult.parentId(), rootResourceId);
PatchOperation patch = PatchOperation.builder().op(Op.REPLACE)
.path("/pathPart").value("updatedPath").build();
apiGateway.updateResource(UpdateResourceRequest.builder()
.restApiId(restApiId)
.resourceId(createResourceResult.id())
.patchOperations(patch).build());
GetResourceResponse getResourceResult = apiGateway
.getResource(GetResourceRequest.builder()
.restApiId(restApiId)
.resourceId(createResourceResult.id()).build());
Assert.assertNotNull(getResourceResult);
Assert.assertNotNull(getResourceResult.id());
Assert.assertNotNull(getResourceResult.parentId());
Assert.assertNotNull(getResourceResult.path());
Assert.assertNotNull(getResourceResult.pathPart());
Assert.assertEquals(getResourceResult.pathPart(), "updatedPath");
Assert.assertEquals(getResourceResult.parentId(), rootResourceId);
PutMethodResponse putMethodResult = apiGateway
.putMethod(PutMethodRequest.builder().restApiId(restApiId)
.resourceId(createResourceResult.id())
.authorizationType("AWS_IAM").httpMethod("PUT").build());
Assert.assertNotNull(putMethodResult);
Assert.assertNotNull(putMethodResult.authorizationType());
Assert.assertNotNull(putMethodResult.apiKeyRequired());
Assert.assertNotNull(putMethodResult.httpMethod());
Assert.assertEquals(putMethodResult.authorizationType(), "AWS_IAM");
Assert.assertEquals(putMethodResult.httpMethod(), "PUT");
PutIntegrationResponse putIntegrationResult = apiGateway
.putIntegration(PutIntegrationRequest.builder()
.restApiId(restApiId)
.resourceId(createResourceResult.id())
.httpMethod("PUT").type(IntegrationType.MOCK)
.uri("http://foo.bar")
.integrationHttpMethod("GET").build());
Assert.assertNotNull(putIntegrationResult);
Assert.assertNotNull(putIntegrationResult.cacheNamespace());
Assert.assertNotNull(putIntegrationResult.type());
Assert.assertEquals(putIntegrationResult.type(),
IntegrationType.MOCK);
}
@Test(expected = NotFoundException.class)
public void resourceWithDotSignedCorrectly() {
apiGateway.createResource(r -> r.restApiId(restApiId).pathPart("fooPath").parentId("."));
}
@Test(expected = NotFoundException.class)
public void resourceWithDoubleDotSignedCorrectly() {
apiGateway.createResource(r -> r.restApiId(restApiId).pathPart("fooPath").parentId(".."));
}
@Test(expected = NotFoundException.class)
public void resourceWithEncodedCharactersSignedCorrectly() {
apiGateway.createResource(r -> r.restApiId(restApiId).pathPart("fooPath").parentId("foo/../bar"));
}
}
| 5,133 |
0 | Create_ds/aws-sdk-java-v2/services/apigateway/src/main/java/software/amazon/awssdk/services/apigateway | Create_ds/aws-sdk-java-v2/services/apigateway/src/main/java/software/amazon/awssdk/services/apigateway/internal/AcceptJsonInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.apigateway.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.http.SdkHttpRequest;
@SdkInternalApi
public final class AcceptJsonInterceptor implements ExecutionInterceptor {
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes) {
// Some APIG operations marshall to the 'Accept' header to specify the
// format of the document returned by the service, such as GetExport
// https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-export-api.html.
// See the same fix in V1:
// https://github.com/aws/aws-sdk-java/blob/cd2275c07df8656033bfa9baa665354bfb17a6bf/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/internal/AcceptJsonRequestHandler.java#L29
SdkHttpRequest httpRequest = context.httpRequest();
if (!httpRequest.firstMatchingHeader("Accept").isPresent()) {
return httpRequest
.toBuilder()
.putHeader("Accept", "application/json")
.build();
}
return httpRequest;
}
}
| 5,134 |
0 | Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services/transcribestreaming/TestSubscription.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.transcribestreaming;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent;
import software.amazon.awssdk.services.transcribestreaming.model.AudioStream;
public class TestSubscription implements Subscription {
private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1;
private ExecutorService executor = Executors.newFixedThreadPool(1);
private AtomicLong demand = new AtomicLong(0);
private final Subscriber<? super AudioStream> subscriber;
private final InputStream inputStream;
public TestSubscription(Subscriber<? super AudioStream> s, InputStream inputStream) {
this.subscriber = s;
this.inputStream = inputStream;
}
@Override
public void request(long n) {
if (n <= 0) {
subscriber.onError(new IllegalArgumentException("Demand must be positive"));
}
demand.getAndAdd(n);
executor.submit(() -> {
try {
do {
ByteBuffer audioBuffer = getNextEvent();
if (audioBuffer.remaining() > 0) {
AudioEvent audioEvent = audioEventFromBuffer(audioBuffer);
subscriber.onNext(audioEvent);
} else {
subscriber.onComplete();
break;
}
} while (demand.decrementAndGet() > 0);
} catch (Exception e) {
subscriber.onError(e);
}
});
}
@Override
public void cancel() {
}
private ByteBuffer getNextEvent() {
ByteBuffer audioBuffer = null;
byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];
int len = 0;
try {
len = inputStream.read(audioBytes);
if (len <= 0) {
audioBuffer = ByteBuffer.allocate(0);
} else {
audioBuffer = ByteBuffer.wrap(audioBytes, 0, len);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return audioBuffer;
}
private AudioEvent audioEventFromBuffer(ByteBuffer bb) {
return AudioEvent.builder()
.audioChunk(SdkBytes.fromByteBuffer(bb))
.build();
}
} | 5,135 |
0 | Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services/transcribestreaming/TestResponseHandlers.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.transcribestreaming;
import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZN_REQUEST_ID_HEADER;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponse;
import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler;
import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent;
import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream;
public class TestResponseHandlers {
private static final Logger log = LoggerFactory.getLogger(TestResponseHandlers.class);
/**
* A simple consumer of events to subscribe
*/
public static StartStreamTranscriptionResponseHandler responseHandlerBuilder_Consumer() {
return StartStreamTranscriptionResponseHandler.builder()
.onResponse(r -> {
String idFromHeader = r.sdkHttpResponse()
.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADER)
.orElse(null);
log.debug("Received Initial response: " + idFromHeader);
})
.onError(e -> {
log.error("Error message: " + e.getMessage(), e);
})
.onComplete(() -> {
log.debug("All records stream successfully");
})
.subscriber(event -> {
// Do nothing
})
.build();
}
/**
* A classic way by implementing the interface and using helper method in {@link SdkPublisher}.
*/
public static StartStreamTranscriptionResponseHandler responseHandlerBuilder_Classic() {
return new StartStreamTranscriptionResponseHandler() {
@Override
public void responseReceived(StartStreamTranscriptionResponse response) {
String idFromHeader = response.sdkHttpResponse()
.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADER)
.orElse(null);
log.debug("Received Initial response: " + idFromHeader);
}
@Override
public void onEventStream(SdkPublisher<TranscriptResultStream> publisher) {
publisher
// Filter to only SubscribeToShardEvents
.filter(TranscriptEvent.class)
// Flat map into a publisher of just records
// Using
.flatMapIterable(event -> event.transcript().results())
// TODO limit is broken. After limit is reached, app fails with SdkCancellationException
// instead of gracefully exiting. Limit to 1000 total records
//.limit(5)
// Batch records into lists of 25
.buffer(25)
// Print out each record batch
// You won't see any data printed as the audio files we use have no voice
.subscribe(batch -> {
log.debug("Record Batch - " + batch);
});
}
@Override
public void exceptionOccurred(Throwable throwable) {
log.error("Error message: " + throwable.getMessage(), throwable);
}
@Override
public void complete() {
log.debug("All records stream successfully");
}
};
}
}
| 5,136 |
0 | Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services/transcribestreaming/TranscribeStreamingIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.transcribestreaming;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static software.amazon.awssdk.http.Header.CONTENT_TYPE;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.internal.util.Mimetype;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.transcribestreaming.model.AudioStream;
import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode;
import software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding;
import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest;
import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler;
import software.amazon.awssdk.utils.Logger;
/**
* An example test class to show the usage of
* {@link TranscribeStreamingAsyncClient#startStreamTranscription(StartStreamTranscriptionRequest, Publisher,
* StartStreamTranscriptionResponseHandler)} API.
*
* The audio files used in this class don't have voice, so there won't be any transcripted text would be empty
*/
public class TranscribeStreamingIntegrationTest {
private static final Logger log = Logger.loggerFor(TranscribeStreamingIntegrationTest.class);
private static TranscribeStreamingAsyncClient client;
private static MetricPublisher mockPublisher;
@BeforeClass
public static void setup() {
mockPublisher = mock(MetricPublisher.class);
client = TranscribeStreamingAsyncClient.builder()
.region(Region.US_EAST_1)
.overrideConfiguration(b -> b.addExecutionInterceptor(new VerifyHeaderInterceptor())
.addMetricPublisher(mockPublisher))
.credentialsProvider(getCredentials())
.build();
}
@Test
public void testFileWith16kRate() throws InterruptedException {
CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000),
new AudioStreamPublisher(
getInputStream("silence_16kHz_s16le.wav")),
TestResponseHandlers.responseHandlerBuilder_Classic());
result.join();
verifyMetrics();
}
@Test
public void testFileWith8kRate() throws ExecutionException, InterruptedException {
CompletableFuture<Void> result = client.startStreamTranscription(getRequest(8_000),
new AudioStreamPublisher(
getInputStream("silence_8kHz_s16le.wav")),
TestResponseHandlers.responseHandlerBuilder_Consumer());
result.get();
}
private static AwsCredentialsProvider getCredentials() {
return DefaultCredentialsProvider.create();
}
private StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) {
return StartStreamTranscriptionRequest.builder()
.languageCode(LanguageCode.EN_US.toString())
.mediaEncoding(MediaEncoding.PCM)
.mediaSampleRateHertz(mediaSampleRateHertz)
.build();
}
private InputStream getInputStream(String audioFileName) {
try {
File inputFile = new File(getClass().getClassLoader().getResource(audioFileName).getFile());
assertTrue(inputFile.exists());
InputStream audioStream = new FileInputStream(inputFile);
return audioStream;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
private class AudioStreamPublisher implements Publisher<AudioStream> {
private final InputStream inputStream;
private AudioStreamPublisher(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void subscribe(Subscriber<? super AudioStream> s) {
s.onSubscribe(new TestSubscription(s, inputStream));
}
}
private static class VerifyHeaderInterceptor implements ExecutionInterceptor {
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
List<String> contentTypeHeader = context.httpRequest().headers().get(CONTENT_TYPE);
assertThat(contentTypeHeader.size()).isEqualTo(1);
assertThat(contentTypeHeader.get(0)).isEqualTo(Mimetype.MIMETYPE_EVENT_STREAM);
}
}
private void verifyMetrics() throws InterruptedException {
// wait for 100ms for metrics to be delivered to mockPublisher
Thread.sleep(100);
ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class);
verify(mockPublisher).publish(collectionCaptor.capture());
MetricCollection capturedCollection = collectionCaptor.getValue();
assertThat(capturedCollection.name()).isEqualTo("ApiCall");
log.info(() -> "captured collection: " + capturedCollection);
assertThat(capturedCollection.metricValues(CoreMetric.CREDENTIALS_FETCH_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(capturedCollection.metricValues(CoreMetric.MARSHALLING_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_DURATION).get(0))
.isGreaterThan(Duration.ZERO);
MetricCollection attemptCollection = capturedCollection.children().get(0);
assertThat(attemptCollection.name()).isEqualTo("ApiCallAttempt");
assertThat(attemptCollection.metricValues(HttpMetric.HTTP_STATUS_CODE))
.containsExactly(200);
assertThat(attemptCollection.metricValues(CoreMetric.SIGNING_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(attemptCollection.metricValues(CoreMetric.AWS_REQUEST_ID).get(0)).isNotEmpty();
assertThat(attemptCollection.metricValues(CoreMetric.SERVICE_CALL_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ofMillis(100));
}
}
| 5,137 |
0 | Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/main/java/software/amazon/awssdk/services/transcribestreaming | Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/main/java/software/amazon/awssdk/services/transcribestreaming/internal/DefaultHttpConfigurationOptions.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.transcribestreaming.internal;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.utils.AttributeMap;
@SdkInternalApi
public final class DefaultHttpConfigurationOptions {
private static final AttributeMap OPTIONS = AttributeMap
.builder()
.put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(100))
.put(SdkHttpConfigurationOption.WRITE_TIMEOUT, Duration.ofSeconds(30))
.build();
private DefaultHttpConfigurationOptions() {
}
public static AttributeMap defaultHttpConfig() {
return OPTIONS;
}
}
| 5,138 |
0 | Create_ds/aws-sdk-java-v2/services/efs/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/efs/src/it/java/software/amazon/awssdk/services/efs/ElasticFileSystemIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.efs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.UUID;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.efs.model.CreateFileSystemRequest;
import software.amazon.awssdk.services.efs.model.DeleteFileSystemRequest;
import software.amazon.awssdk.services.efs.model.DescribeFileSystemsRequest;
import software.amazon.awssdk.services.efs.model.FileSystemAlreadyExistsException;
import software.amazon.awssdk.services.efs.model.FileSystemNotFoundException;
import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase;
import software.amazon.awssdk.utils.StringUtils;
public class ElasticFileSystemIntegrationTest extends AwsIntegrationTestBase {
private static EfsClient client;
private String fileSystemId;
@BeforeClass
public static void setupFixture() throws Exception {
client = EfsClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).region(Region.US_WEST_2).build();
}
@After
public void tearDown() {
if (!StringUtils.isEmpty(fileSystemId)) {
client.deleteFileSystem(DeleteFileSystemRequest.builder().fileSystemId(fileSystemId).build());
}
}
@Test
public void describeFileSystems_ReturnsNonNull() {
assertNotNull(client.describeFileSystems(DescribeFileSystemsRequest.builder().build()));
}
@Test
public void describeFileSystem_NonExistentFileSystem_ThrowsException() {
try {
client.describeFileSystems(DescribeFileSystemsRequest.builder().fileSystemId("fs-00000000").build());
} catch (FileSystemNotFoundException e) {
assertEquals("FileSystemNotFound", e.errorCode());
}
}
/**
* Tests that an exception with a member in it is serialized properly. See TT0064111680
*/
@Test
public void createFileSystem_WithDuplicateCreationToken_ThrowsExceptionWithFileSystemIdPresent() {
String creationToken = UUID.randomUUID().toString();
this.fileSystemId = client.createFileSystem(CreateFileSystemRequest.builder().creationToken(creationToken).build())
.fileSystemId();
try {
client.createFileSystem(CreateFileSystemRequest.builder().creationToken(creationToken).build()).fileSystemId();
} catch (FileSystemAlreadyExistsException e) {
assertEquals(fileSystemId, e.fileSystemId());
}
}
}
| 5,139 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsWebIdentityTokenCredentialProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import org.junit.Assert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityResponse;
import software.amazon.awssdk.services.sts.model.Credentials;
import java.nio.file.Paths;
import java.time.Instant;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class StsWebIdentityTokenCredentialProviderTest {
@Mock
StsClient stsClient;
private EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
@BeforeEach
public void setUp() {
String webIdentityTokenPath = Paths.get("src/test/resources/token.jwt").toAbsolutePath().toString();
ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_ROLE_ARN.environmentVariable(), "someRole");
ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_WEB_IDENTITY_TOKEN_FILE.environmentVariable(), webIdentityTokenPath);
ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_ROLE_SESSION_NAME.environmentVariable(), "tempRoleSession");
}
@AfterEach
public void cleanUp(){
ENVIRONMENT_VARIABLE_HELPER.reset();
}
@Test
void createAssumeRoleWithWebIdentityTokenCredentialsProviderWithoutStsClient_throws_Exception() {
Assert.assertThrows(NullPointerException.class,
() -> StsWebIdentityTokenFileCredentialsProvider.builder().refreshRequest(r -> r.build()).build());
}
@Test
void createAssumeRoleWithWebIdentityTokenCredentialsProviderCreateStsClient() {
StsWebIdentityTokenFileCredentialsProvider provider =
StsWebIdentityTokenFileCredentialsProvider.builder().stsClient(stsClient).refreshRequest(r -> r.build())
.build();
when(stsClient.assumeRoleWithWebIdentity(Mockito.any(AssumeRoleWithWebIdentityRequest.class)))
.thenReturn(AssumeRoleWithWebIdentityResponse.builder()
.credentials(Credentials.builder().accessKeyId("key")
.expiration(Instant.now())
.sessionToken("session").secretAccessKey("secret").build()).build());
provider.resolveCredentials();
Mockito.verify(stsClient, Mockito.times(1)).assumeRoleWithWebIdentity(Mockito.any(AssumeRoleWithWebIdentityRequest.class));
}
@Test
void createAssumeRoleWithWebIdentityTokenCredentialsProviderStsClientBuilder() {
String webIdentityTokenPath = Paths.get("src/test/resources/token.jwt").toAbsolutePath().toString();
StsWebIdentityTokenFileCredentialsProvider provider =
StsWebIdentityTokenFileCredentialsProvider.builder().stsClient(stsClient)
.refreshRequest(r -> r.build())
.roleArn("someRole")
.webIdentityTokenFile(Paths.get(webIdentityTokenPath))
.roleSessionName("tempRoleSession")
.build();
when(stsClient.assumeRoleWithWebIdentity(Mockito.any(AssumeRoleWithWebIdentityRequest.class)))
.thenReturn(AssumeRoleWithWebIdentityResponse.builder()
.credentials(Credentials.builder().accessKeyId("key")
.expiration(Instant.now())
.sessionToken("session").secretAccessKey("secret").build()).build());
provider.resolveCredentials();
Mockito.verify(stsClient, Mockito.times(1)).assumeRoleWithWebIdentity(Mockito.any(AssumeRoleWithWebIdentityRequest.class));
}
} | 5,140 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
import software.amazon.awssdk.services.sts.model.Credentials;
/**
* Validate the functionality of {@link StsAssumeRoleCredentialsProvider}.
* Inherits tests from {@link StsCredentialsProviderTestBase}.
*/
public class StsAssumeRoleCredentialsProviderTest extends StsCredentialsProviderTestBase<AssumeRoleRequest, AssumeRoleResponse> {
@Override
protected AssumeRoleRequest getRequest() {
return AssumeRoleRequest.builder().build();
}
@Override
protected AssumeRoleResponse getResponse(Credentials credentials) {
return AssumeRoleResponse.builder().credentials(credentials).build();
}
@Override
protected StsAssumeRoleCredentialsProvider.Builder createCredentialsProviderBuilder(AssumeRoleRequest request) {
return StsAssumeRoleCredentialsProvider.builder().refreshRequest(request);
}
@Override
protected AssumeRoleResponse callClient(StsClient client, AssumeRoleRequest request) {
return client.assumeRole(request);
}
}
| 5,141 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsWebIdentityTokenCredentialsProviderBaseTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.auth.StsWebIdentityTokenFileCredentialsProvider.Builder;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityResponse;
import software.amazon.awssdk.services.sts.model.Credentials;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import software.amazon.awssdk.utils.IoUtils;
/**
* Validate the functionality of {@link StsWebIdentityTokenFileCredentialsProvider}. Inherits tests from {@link
* StsCredentialsProviderTestBase}.
*/
public class StsWebIdentityTokenCredentialsProviderBaseTest
extends StsCredentialsProviderTestBase<AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse> {
private EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
@BeforeEach
public void setUp() {
String webIdentityTokenPath = Paths.get("src/test/resources/token.jwt").toAbsolutePath().toString();
ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_ROLE_ARN.environmentVariable(), "someRole");
ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_WEB_IDENTITY_TOKEN_FILE.environmentVariable(), webIdentityTokenPath);
ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_ROLE_SESSION_NAME.environmentVariable(), "tempRoleSession");
}
@AfterEach
public void cleanUp(){
ENVIRONMENT_VARIABLE_HELPER.reset();
}
@Override
protected AssumeRoleWithWebIdentityRequest getRequest() {
return AssumeRoleWithWebIdentityRequest.builder().webIdentityToken(getToken(Paths.get("src/test/resources"
+ "/token.jwt").toAbsolutePath())).build();
}
@Override
protected AssumeRoleWithWebIdentityResponse getResponse(Credentials credentials) {
return AssumeRoleWithWebIdentityResponse.builder().credentials(credentials).build();
}
@Override
protected Builder createCredentialsProviderBuilder(AssumeRoleWithWebIdentityRequest request) {
return StsWebIdentityTokenFileCredentialsProvider.builder().stsClient(stsClient).refreshRequest(request);
}
@Override
protected AssumeRoleWithWebIdentityResponse callClient(StsClient client, AssumeRoleWithWebIdentityRequest request) {
return client.assumeRoleWithWebIdentity(request);
}
private String getToken(Path file) {
try (InputStream webIdentityTokenStream = Files.newInputStream(file)) {
return IoUtils.toUtf8String(webIdentityTokenStream);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
| 5,142 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleWithSamlCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.auth.StsAssumeRoleWithSamlCredentialsProvider.Builder;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithSamlRequest;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithSamlResponse;
import software.amazon.awssdk.services.sts.model.Credentials;
/**
* Validate the functionality of {@link StsAssumeRoleWithSamlCredentialsProvider}.
* Inherits tests from {@link StsCredentialsProviderTestBase}.
*/
public class StsAssumeRoleWithSamlCredentialsProviderTest
extends StsCredentialsProviderTestBase<AssumeRoleWithSamlRequest, AssumeRoleWithSamlResponse> {
@Override
protected AssumeRoleWithSamlRequest getRequest() {
return AssumeRoleWithSamlRequest.builder().build();
}
@Override
protected AssumeRoleWithSamlResponse getResponse(Credentials credentials) {
return AssumeRoleWithSamlResponse.builder().credentials(credentials).build();
}
@Override
protected Builder createCredentialsProviderBuilder(AssumeRoleWithSamlRequest request) {
return StsAssumeRoleWithSamlCredentialsProvider.builder().refreshRequest(request);
}
@Override
protected AssumeRoleWithSamlResponse callClient(StsClient client, AssumeRoleWithSamlRequest request) {
return client.assumeRoleWithSAML(request);
}
}
| 5,143 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsGetFederationTokenCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.auth.StsGetFederationTokenCredentialsProvider.Builder;
import software.amazon.awssdk.services.sts.model.Credentials;
import software.amazon.awssdk.services.sts.model.GetFederationTokenRequest;
import software.amazon.awssdk.services.sts.model.GetFederationTokenResponse;
/**
* Validate the functionality of {@link StsGetFederationTokenCredentialsProvider}.
* Inherits tests from {@link StsCredentialsProviderTestBase}.
*/
public class StsGetFederationTokenCredentialsProviderTest
extends StsCredentialsProviderTestBase<GetFederationTokenRequest, GetFederationTokenResponse> {
@Override
protected GetFederationTokenRequest getRequest() {
return GetFederationTokenRequest.builder().build();
}
@Override
protected GetFederationTokenResponse getResponse(Credentials credentials) {
return GetFederationTokenResponse.builder().credentials(credentials).build();
}
@Override
protected Builder createCredentialsProviderBuilder(GetFederationTokenRequest request) {
return StsGetFederationTokenCredentialsProvider.builder().refreshRequest(request);
}
@Override
protected GetFederationTokenResponse callClient(StsClient client, GetFederationTokenRequest request) {
return client.getFederationToken(request);
}
}
| 5,144 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsGetSessionTokenCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.auth.StsGetSessionTokenCredentialsProvider.Builder;
import software.amazon.awssdk.services.sts.model.Credentials;
import software.amazon.awssdk.services.sts.model.GetSessionTokenRequest;
import software.amazon.awssdk.services.sts.model.GetSessionTokenResponse;
/**
* Validate the functionality of {@link StsGetSessionTokenCredentialsProvider}.
* Inherits tests from {@link StsCredentialsProviderTestBase}.
*/
public class StsGetSessionTokenCredentialsProviderTest
extends StsCredentialsProviderTestBase<GetSessionTokenRequest, GetSessionTokenResponse> {
@Override
protected GetSessionTokenRequest getRequest() {
return GetSessionTokenRequest.builder().build();
}
@Override
protected GetSessionTokenResponse getResponse(Credentials credentials) {
return GetSessionTokenResponse.builder().credentials(credentials).build();
}
@Override
protected Builder createCredentialsProviderBuilder(GetSessionTokenRequest request) {
return StsGetSessionTokenCredentialsProvider.builder().refreshRequest(request);
}
@Override
protected GetSessionTokenResponse callClient(StsClient client, GetSessionTokenRequest request) {
return client.getSessionToken(request);
}
}
| 5,145 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsCredentialsProviderTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.Credentials;
/**
* Validates the functionality of {@link StsCredentialsProvider} and its subclasses.
*/
@ExtendWith(MockitoExtension.class)
public abstract class StsCredentialsProviderTestBase<RequestT, ResponseT> {
@Mock
protected StsClient stsClient;
@Test
public void cachingDoesNotApplyToExpiredSession() {
callClientWithCredentialsProvider(Instant.now().minus(Duration.ofSeconds(5)), 2, false);
callClient(verify(stsClient, times(2)), Mockito.any());
}
@Test
public void cachingDoesNotApplyToExpiredSession_OverridePrefetchAndStaleTimes() {
callClientWithCredentialsProvider(Instant.now().minus(Duration.ofSeconds(5)), 2, true);
callClient(verify(stsClient, times(2)), Mockito.any());
}
@Test
public void cachingAppliesToNonExpiredSession() {
callClientWithCredentialsProvider(Instant.now().plus(Duration.ofHours(5)), 2, false);
callClient(verify(stsClient, times(1)), Mockito.any());
}
@Test
public void cachingAppliesToNonExpiredSession_OverridePrefetchAndStaleTimes() {
callClientWithCredentialsProvider(Instant.now().plus(Duration.ofHours(5)), 2, true);
callClient(verify(stsClient, times(1)), Mockito.any());
}
@Test
public void distantExpiringCredentialsUpdatedInBackground() throws InterruptedException {
callClientWithCredentialsProvider(Instant.now().plusSeconds(90), 2, false);
Instant endCheckTime = Instant.now().plus(Duration.ofSeconds(5));
while (Mockito.mockingDetails(stsClient).getInvocations().size() < 2 && endCheckTime.isAfter(Instant.now())) {
Thread.sleep(100);
}
callClient(verify(stsClient, times(2)), Mockito.any());
}
@Test
public void distantExpiringCredentialsUpdatedInBackground_OverridePrefetchAndStaleTimes() throws InterruptedException {
callClientWithCredentialsProvider(Instant.now().plusSeconds(90), 2, true);
Instant endCheckTime = Instant.now().plus(Duration.ofSeconds(5));
while (Mockito.mockingDetails(stsClient).getInvocations().size() < 2 && endCheckTime.isAfter(Instant.now())) {
Thread.sleep(100);
}
callClient(verify(stsClient, times(2)), Mockito.any());
}
protected abstract RequestT getRequest();
protected abstract ResponseT getResponse(Credentials credentials);
protected abstract StsCredentialsProvider.BaseBuilder<?, ? extends StsCredentialsProvider>
createCredentialsProviderBuilder(RequestT request);
protected abstract ResponseT callClient(StsClient client, RequestT request);
public void callClientWithCredentialsProvider(Instant credentialsExpirationDate, int numTimesInvokeCredentialsProvider, boolean overrideStaleAndPrefetchTimes) {
Credentials credentials = Credentials.builder().accessKeyId("a").secretAccessKey("b").sessionToken("c").expiration(credentialsExpirationDate).build();
RequestT request = getRequest();
ResponseT response = getResponse(credentials);
when(callClient(stsClient, request)).thenReturn(response);
StsCredentialsProvider.BaseBuilder<?, ? extends StsCredentialsProvider> credentialsProviderBuilder = createCredentialsProviderBuilder(request);
if(overrideStaleAndPrefetchTimes) {
//do the same values as we would do without overriding the stale and prefetch times
credentialsProviderBuilder.staleTime(Duration.ofMinutes(2));
credentialsProviderBuilder.prefetchTime(Duration.ofMinutes(4));
}
try (StsCredentialsProvider credentialsProvider = credentialsProviderBuilder.stsClient(stsClient).build()) {
if(overrideStaleAndPrefetchTimes) {
//validate that we actually stored the override values in the build provider
assertThat(credentialsProvider.staleTime()).as("stale time").isEqualTo(Duration.ofMinutes(2));
assertThat(credentialsProvider.prefetchTime()).as("prefetch time").isEqualTo(Duration.ofMinutes(4));
} else {
//validate that the default values are used
assertThat(credentialsProvider.staleTime()).as("stale time").isEqualTo(Duration.ofMinutes(1));
assertThat(credentialsProvider.prefetchTime()).as("prefetch time").isEqualTo(Duration.ofMinutes(5));
}
for (int i = 0; i < numTimesInvokeCredentialsProvider; ++i) {
AwsSessionCredentials providedCredentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials();
assertThat(providedCredentials.accessKeyId()).isEqualTo("a");
assertThat(providedCredentials.secretAccessKey()).isEqualTo("b");
assertThat(providedCredentials.sessionToken()).isEqualTo("c");
}
}
}
}
| 5,146 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleWithWebIdentityCredentialsProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.auth.StsAssumeRoleWithWebIdentityCredentialsProvider.Builder;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityResponse;
import software.amazon.awssdk.services.sts.model.Credentials;
/**
* Validate the functionality of {@link StsAssumeRoleWithWebIdentityCredentialsProvider}.
* Inherits tests from {@link StsCredentialsProviderTestBase}.
*/
public class StsAssumeRoleWithWebIdentityCredentialsProviderTest
extends StsCredentialsProviderTestBase<AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse> {
@Override
protected AssumeRoleWithWebIdentityRequest getRequest() {
return AssumeRoleWithWebIdentityRequest.builder().build();
}
@Override
protected AssumeRoleWithWebIdentityResponse getResponse(Credentials credentials) {
return AssumeRoleWithWebIdentityResponse.builder().credentials(credentials).build();
}
@Override
protected Builder createCredentialsProviderBuilder(AssumeRoleWithWebIdentityRequest request) {
return StsAssumeRoleWithWebIdentityCredentialsProvider.builder().refreshRequest(request);
}
@Override
protected AssumeRoleWithWebIdentityResponse callClient(StsClient client, AssumeRoleWithWebIdentityRequest request) {
return client.assumeRoleWithWebIdentity(request);
}
}
| 5,147 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/internal/StsWebIdentityCredentialsProviderFactoryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.internal;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.nio.file.Paths;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.WebIdentityTokenCredentialsProviderFactory;
import software.amazon.awssdk.auth.credentials.internal.WebIdentityCredentialsUtils;
import software.amazon.awssdk.auth.credentials.internal.WebIdentityTokenCredentialProperties;
class StsWebIdentityCredentialsProviderFactoryTest {
@Test
void stsWebIdentityCredentialsProviderFactory_with_webIdentityCredentialsUtils() {
WebIdentityTokenCredentialsProviderFactory factory = WebIdentityCredentialsUtils.factory();
assertNotNull(factory);
}
@Test
void stsWebIdentityCredentialsProviderFactory_withWebIdentityTokenCredentialProperties() {
WebIdentityTokenCredentialsProviderFactory factory = new StsWebIdentityCredentialsProviderFactory();
AwsCredentialsProvider provider = factory.create(
WebIdentityTokenCredentialProperties.builder()
.asyncCredentialUpdateEnabled(true)
.prefetchTime(Duration.ofMinutes(5))
.staleTime(Duration.ofMinutes(15))
.roleArn("role-arn")
.webIdentityTokenFile(Paths.get("/path/to/file"))
.roleSessionName("session-name")
.roleSessionDuration(Duration.ofMinutes(60))
.build());
assertNotNull(provider);
}
}
| 5,148 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/internal/AssumeRoleProfileTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.internal;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.internal.ProfileCredentialsUtils;
import software.amazon.awssdk.utils.StringInputStream;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.services.sts.AssumeRoleIntegrationTest;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* Verify some basic functionality of {@link StsProfileCredentialsProviderFactory} via the way customers will encounter it:
* the {@link ProfileFile}. The full functionality is verified via
* {@link AssumeRoleIntegrationTest#profileCredentialsProviderCanAssumeRoles()}.
*/
public class AssumeRoleProfileTest {
@Test
public void createAssumeRoleCredentialsProviderViaProfileSucceeds() {
String profileContent =
"[profile source]\n"
+ "aws_access_key_id=defaultAccessKey\n"
+ "aws_secret_access_key=defaultSecretAccessKey\n"
+ "\n"
+ "[profile test]\n"
+ "source_profile=source\n"
+ "role_arn=arn:aws:iam::123456789012:role/testRole";
ProfileFile profiles = ProfileFile.builder()
.content(new StringInputStream(profileContent))
.type(ProfileFile.Type.CONFIGURATION)
.build();
assertThat(profiles.profile("test")).hasValueSatisfying(profile -> {
assertThat(new ProfileCredentialsUtils(profiles, profile, profiles::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> {
assertThat(credentialsProvider).isInstanceOf(SdkAutoCloseable.class);
((SdkAutoCloseable) credentialsProvider).close();
});
});
}
@Test
public void assumeRoleOutOfOrderDefinitionSucceeds() {
String profileContent =
"[profile child]\n"
+ "source_profile=parent\n"
+ "role_arn=arn:aws:iam::123456789012:role/testRole\n"
+ "[profile source]\n"
+ "aws_access_key_id=defaultAccessKey\n"
+ "aws_secret_access_key=defaultSecretAccessKey\n"
+ "[profile parent]\n"
+ "source_profile=source\n"
+ "role_arn=arn:aws:iam::123456789012:role/testRole";
ProfileFile profiles = ProfileFile.builder()
.content(new StringInputStream(profileContent))
.type(ProfileFile.Type.CONFIGURATION)
.build();
assertThat(profiles.profile("child")).isPresent();
}
}
| 5,149 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/internal/WebIdentityTokenCredentialProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.internal.ProfileCredentialsUtils;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.StringInputStream;
public class WebIdentityTokenCredentialProviderTest {
@Test
public void createAssumeRoleWithWebIdentityTokenCredentialsProviderViaProfileSucceeds() {
String webIdentityTokenPath = Paths.get("/src/test/token.jwt").toAbsolutePath().toString();
String profileContent =
"[profile test]\n"
+ "web_identity_token_file="+ webIdentityTokenPath +"\n"
+ "role_arn=arn:aws:iam::123456789012:role/testRole";
ProfileFile profiles = ProfileFile.builder()
.content(new StringInputStream(profileContent))
.type(ProfileFile.Type.CONFIGURATION)
.build();
assertThat(profiles.profile("test")).hasValueSatisfying(profile -> {
assertThat(new ProfileCredentialsUtils(profiles, profile, profiles::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> {
assertThat(credentialsProvider).isInstanceOf(SdkAutoCloseable.class);
assertThat(credentialsProvider).hasFieldOrProperty("stsClient");
((SdkAutoCloseable) credentialsProvider).close();
});
});
}
}
| 5,150 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services/sts/IntegrationTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.junit.BeforeClass;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.testutils.service.AwsTestBase;
/**
* Base class for all STS integration tests. Loads AWS credentials from a
* properties file on disk, provides helper methods for tests, and instantiates
* the STS client object for all tests to use.
*/
public abstract class IntegrationTestBase extends AwsTestBase {
/** The shared STS client for all tests to use. */
protected static StsClient sts;
@BeforeClass
public static void setUp() throws FileNotFoundException, IOException {
setUpCredentials();
sts = StsClient.builder()
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.region(Region.US_EAST_1)
.build();
}
}
| 5,151 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services/sts/SecurityTokenServiceIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.core.SdkGlobalTime;
import software.amazon.awssdk.services.sts.model.GetFederationTokenRequest;
import software.amazon.awssdk.services.sts.model.GetFederationTokenResponse;
import software.amazon.awssdk.services.sts.model.GetSessionTokenRequest;
import software.amazon.awssdk.services.sts.model.GetSessionTokenResponse;
import software.amazon.awssdk.utils.Logger;
public class SecurityTokenServiceIntegrationTest extends IntegrationTestBase {
private static final Logger log = Logger.loggerFor(SecurityTokenServiceIntegrationTest.class);
private static final int SESSION_DURATION = 60 * 60;
/** Tests that we can call GetSession to start a session. */
@Test
public void testGetSessionToken() throws Exception {
if (CREDENTIALS_PROVIDER_CHAIN.resolveCredentials() instanceof AwsSessionCredentials) {
log.warn(() -> "testGetSessionToken() skipped due to the current credentials being session credentials. " +
"Session credentials cannot be used to get other session tokens.");
return;
}
GetSessionTokenRequest request = GetSessionTokenRequest.builder().durationSeconds(SESSION_DURATION).build();
GetSessionTokenResponse result = sts.getSessionToken(request);
assertNotNull(result.credentials().accessKeyId());
assertNotNull(result.credentials().expiration());
assertNotNull(result.credentials().secretAccessKey());
assertNotNull(result.credentials().sessionToken());
}
/** Tests that we can call GetFederatedSession to start a federated session. */
@Test
public void testGetFederatedSessionToken() throws Exception {
if (CREDENTIALS_PROVIDER_CHAIN.resolveCredentials() instanceof AwsSessionCredentials) {
log.warn(() -> "testGetFederatedSessionToken() skipped due to the current credentials being session credentials. " +
"Session credentials cannot be used to get federation tokens.");
return;
}
GetFederationTokenRequest request = GetFederationTokenRequest.builder()
.durationSeconds(SESSION_DURATION)
.name("Name").build();
GetFederationTokenResponse result = sts.getFederationToken(request);
assertNotNull(result.credentials().accessKeyId());
assertNotNull(result.credentials().expiration());
assertNotNull(result.credentials().secretAccessKey());
assertNotNull(result.credentials().sessionToken());
assertNotNull(result.federatedUser().arn());
assertNotNull(result.federatedUser().federatedUserId());
}
}
| 5,152 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services/sts/AssumeRoleIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import java.time.Duration;
import java.util.Comparator;
import java.util.Optional;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.auth.credentials.internal.ProfileCredentialsUtils;
import software.amazon.awssdk.core.auth.policy.Action;
import software.amazon.awssdk.core.auth.policy.Policy;
import software.amazon.awssdk.core.auth.policy.Principal;
import software.amazon.awssdk.core.auth.policy.Resource;
import software.amazon.awssdk.core.auth.policy.Statement;
import software.amazon.awssdk.core.auth.policy.Statement.Effect;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.services.iam.model.AccessKeyMetadata;
import software.amazon.awssdk.services.iam.model.CreateAccessKeyResponse;
import software.amazon.awssdk.services.iam.model.EntityAlreadyExistsException;
import software.amazon.awssdk.services.iam.model.MalformedPolicyDocumentException;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
import software.amazon.awssdk.services.sts.model.StsException;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import software.amazon.awssdk.testutils.Waiter;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.StringInputStream;
//TODO This could be useful to cleanup and present as a customer sample
public class AssumeRoleIntegrationTest extends IntegrationTestBaseWithIAM {
private static final int SESSION_DURATION = 60 * 60;
private static final String USER_NAME = "assume-role-integration-test-user";
private static final String USER_ARN_FORMAT = "arn:aws:iam::%s:user/" + USER_NAME;
private static String USER_ARN;
private static final String POLICY_NAME = "AssumeRoleIntegrationTestPolicy";
private static final String POLICY_ARN_FORMAT = "arn:aws:iam::%s:policy/" + POLICY_NAME;
private static final String ROLE_NAME = "assume-role-integration-test-role";
private static final String ROLE_ARN_FORMAT = "arn:aws:iam::%s:role/" + ROLE_NAME;
private static String ROLE_ARN;
private static final String ASSUME_ROLE = "sts:AssumeRole";
private static AwsCredentials userCredentials;
@BeforeClass
public static void setup() {
String accountId = sts.getCallerIdentity().account();
USER_ARN = String.format(USER_ARN_FORMAT, accountId);
ROLE_ARN = String.format(ROLE_ARN_FORMAT, accountId);
// Create a user
try {
iam.createUser(r -> r.userName(USER_NAME));
} catch (EntityAlreadyExistsException e) {
// Test user already exists - awesome.
}
// Create a managed policy that allows the user to assume a role
try {
iam.createPolicy(r -> r.policyName("AssumeRoleIntegrationTestPolicy")
.policyDocument(new Policy().withStatements(new Statement(Effect.Allow)
.withActions(new Action(ASSUME_ROLE))
.withResources(new Resource("*")))
.toJson()));
} catch (EntityAlreadyExistsException e) {
// Policy already exists - awesome.
}
// Attach the policy to the user (if it isn't already attached)
iam.attachUserPolicy(r -> r.userName(USER_NAME).policyArn(String.format(POLICY_ARN_FORMAT, accountId)));
// Try to create a role that can be assumed by the user, until the eventual consistency catches up.
try {
String rolePolicyDoc = new Policy()
.withStatements(new Statement(Effect.Allow)
.withPrincipals(new Principal("AWS", USER_ARN, false))
.withActions(new Action(ASSUME_ROLE)))
.toJson();
Waiter.run(() -> iam.createRole(r -> r.roleName(ROLE_NAME)
.assumeRolePolicyDocument(rolePolicyDoc)))
.ignoringException(MalformedPolicyDocumentException.class)
.orFailAfter(Duration.ofMinutes(2));
} catch (EntityAlreadyExistsException e) {
// Role already exists - awesome.
}
// Delete the oldest credentials for the user. We don't want to hit our limit.
iam.listAccessKeysPaginator(r -> r.userName(USER_NAME))
.accessKeyMetadata().stream()
.min(Comparator.comparing(AccessKeyMetadata::createDate))
.ifPresent(key -> iam.deleteAccessKey(r -> r.userName(USER_NAME).accessKeyId(key.accessKeyId())));
// Create new credentials for the user
CreateAccessKeyResponse createAccessKeyResult = iam.createAccessKey(r -> r.userName(USER_NAME));
userCredentials = AwsBasicCredentials.create(createAccessKeyResult.accessKey().accessKeyId(),
createAccessKeyResult.accessKey().secretAccessKey());
// Try to assume the role to make sure we won't hit issues during testing.
StsClient userCredentialSts = StsClient.builder()
.credentialsProvider(() -> userCredentials)
.build();
Waiter.run(() -> userCredentialSts.assumeRole(r -> r.durationSeconds(SESSION_DURATION)
.roleArn(ROLE_ARN)
.roleSessionName("Test")))
.ignoringException(StsException.class)
.orFailAfter(Duration.ofMinutes(5));
}
/** Tests that we can call assumeRole successfully. */
@Test
public void testAssumeRole() throws InterruptedException {
AssumeRoleRequest assumeRoleRequest = AssumeRoleRequest.builder()
.durationSeconds(SESSION_DURATION)
.roleArn(ROLE_ARN)
.roleSessionName("Name")
.build();
StsClient sts = StsClient.builder().credentialsProvider(StaticCredentialsProvider.create(userCredentials)).build();
AssumeRoleResponse assumeRoleResult = sts.assumeRole(assumeRoleRequest);
assertNotNull(assumeRoleResult.assumedRoleUser());
assertNotNull(assumeRoleResult.assumedRoleUser().arn());
assertNotNull(assumeRoleResult.assumedRoleUser().assumedRoleId());
assertNotNull(assumeRoleResult.credentials());
}
@Test
public void profileCredentialsProviderCanAssumeRoles() throws InterruptedException {
String ASSUME_ROLE_PROFILE =
"[source]\n"
+ "aws_access_key_id = " + userCredentials.accessKeyId() + "\n"
+ "aws_secret_access_key = " + userCredentials.secretAccessKey() + "\n"
+ "\n"
+ "[test]\n"
+ "region = us-west-1\n"
+ "source_profile = source\n"
+ "role_arn = " + ROLE_ARN;
ProfileFile profiles = ProfileFile.builder()
.content(new StringInputStream(ASSUME_ROLE_PROFILE))
.type(ProfileFile.Type.CREDENTIALS)
.build();
Optional<Profile> profile = profiles.profile("test");
AwsCredentialsProvider awsCredentialsProvider =
new ProfileCredentialsUtils(profiles, profile.get(), profiles::profile).credentialsProvider().get();
// Try to assume the role until the eventual consistency catches up.
AwsCredentials awsCredentials = Waiter.run(awsCredentialsProvider::resolveCredentials)
.ignoringException(StsException.class)
.orFail();
assertThat(awsCredentials.accessKeyId()).isNotBlank();
assertThat(awsCredentials.secretAccessKey()).isNotBlank();
((SdkAutoCloseable) awsCredentialsProvider).close();
}
@Test
public void profileCredentialProviderCanAssumeRolesWithEnvironmentCredentialSource() throws InterruptedException {
EnvironmentVariableHelper.run(helper -> {
helper.set("AWS_ACCESS_KEY_ID", userCredentials.accessKeyId());
helper.set("AWS_SECRET_ACCESS_KEY", userCredentials.secretAccessKey());
helper.remove("AWS_SESSION_TOKEN");
String ASSUME_ROLE_PROFILE =
"[test]\n"
+ "region = us-west-1\n"
+ "credential_source = Environment\n"
+ "role_arn = " + ROLE_ARN;
ProfileFile profiles = ProfileFile.builder()
.content(new StringInputStream(ASSUME_ROLE_PROFILE))
.type(ProfileFile.Type.CREDENTIALS)
.build();
Optional<Profile> profile = profiles.profile("test");
AwsCredentialsProvider awsCredentialsProvider =
new ProfileCredentialsUtils(profiles, profile.get(), profiles::profile).credentialsProvider().get();
// Try to assume the role until the eventual consistency catches up.
AwsCredentials awsCredentials = Waiter.run(awsCredentialsProvider::resolveCredentials)
.ignoringException(StsException.class)
.orFail();
assertThat(awsCredentials.accessKeyId()).isNotBlank();
assertThat(awsCredentials.secretAccessKey()).isNotBlank();
((SdkAutoCloseable) awsCredentialsProvider).close();
});
}
@Test
public void profileCredentialProviderWithEnvironmentCredentialSourceAndSystemProperties() throws InterruptedException {
System.setProperty("aws.accessKeyId", userCredentials.accessKeyId());
System.setProperty("aws.secretAccessKey", userCredentials.secretAccessKey());
try {
EnvironmentVariableHelper.run(helper -> {
helper.remove("AWS_ACCESS_KEY_ID");
helper.remove("AWS_SECRET_ACCESS_KEY");
helper.remove("AWS_SESSION_TOKEN");
String ASSUME_ROLE_PROFILE =
"[test]\n"
+ "region = us-west-1\n"
+ "credential_source = Environment\n"
+ "role_arn = " + ROLE_ARN;
ProfileFile profiles = ProfileFile.builder()
.content(new StringInputStream(ASSUME_ROLE_PROFILE))
.type(ProfileFile.Type.CREDENTIALS)
.build();
Optional<Profile> profile = profiles.profile("test");
AwsCredentialsProvider awsCredentialsProvider =
new ProfileCredentialsUtils(profiles, profile.get(), profiles::profile).credentialsProvider().get();
// Try to assume the role until the eventual consistency catches up.
AwsCredentials awsCredentials = Waiter.run(awsCredentialsProvider::resolveCredentials)
.ignoringException(StsException.class)
.orFail();
assertThat(awsCredentials.accessKeyId()).isNotBlank();
assertThat(awsCredentials.secretAccessKey()).isNotBlank();
((SdkAutoCloseable) awsCredentialsProvider).close();
});
} finally {
System.clearProperty("aws.accessKeyId");
System.clearProperty("aws.secretAccessKey");
}
}
}
| 5,153 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services/sts/IntegrationTestBaseWithIAM.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.junit.BeforeClass;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
/**
* Base class for all STS integration tests that also need IAM
*/
public abstract class IntegrationTestBaseWithIAM extends IntegrationTestBase {
/** The shared IAM client for all tests to use. */
protected static IamClient iam;
@BeforeClass
public static void setUp() throws FileNotFoundException, IOException {
IntegrationTestBase.setUp();
iam = IamClient.builder()
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.region(Region.AWS_GLOBAL)
.build();
}
}
| 5,154 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsWebIdentityTokenFileCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials;
import static software.amazon.awssdk.utils.StringUtils.trim;
import static software.amazon.awssdk.utils.Validate.notNull;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.internal.WebIdentityTokenCredentialProperties;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.internal.AssumeRoleWithWebIdentityRequestSupplier;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An implementation of {@link AwsCredentialsProvider} that periodically sends an {@link AssumeRoleWithWebIdentityRequest} to the
* AWS Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a
* single calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set).
*
* Unlike {@link StsAssumeRoleWithWebIdentityCredentialsProvider}, this reads the web identity information, including AWS role
* ARN, AWS session name and the location of a web identity token file from system properties and environment variables. The
* web identity token file is expected to contain the web identity token to use with each request.
*
* If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until
* they are updated successfully.
*
* Users of this provider must {@link #close()} it when they are finished using it.
*
* This is created using {@link #builder()}.
*/
@SdkPublicApi
public final class StsWebIdentityTokenFileCredentialsProvider
extends StsCredentialsProvider
implements ToCopyableBuilder<StsWebIdentityTokenFileCredentialsProvider.Builder, StsWebIdentityTokenFileCredentialsProvider> {
private final AwsCredentialsProvider credentialsProvider;
private final RuntimeException loadException;
private final Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequest;
private final Path webIdentityTokenFile;
private final String roleArn;
private final String roleSessionName;
private final Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequestFromBuilder;
private StsWebIdentityTokenFileCredentialsProvider(Builder builder) {
super(builder, "sts-assume-role-with-web-identity-credentials-provider");
Path webIdentityTokenFile =
builder.webIdentityTokenFile != null ? builder.webIdentityTokenFile
: Paths.get(trim(SdkSystemSetting.AWS_WEB_IDENTITY_TOKEN_FILE
.getStringValueOrThrow()));
String roleArn = builder.roleArn != null ? builder.roleArn
: trim(SdkSystemSetting.AWS_ROLE_ARN.getStringValueOrThrow());
String sessionName = builder.roleSessionName != null ? builder.roleSessionName :
SdkSystemSetting.AWS_ROLE_SESSION_NAME.getStringValue()
.orElse("aws-sdk-java-" + System.currentTimeMillis());
WebIdentityTokenCredentialProperties credentialProperties =
WebIdentityTokenCredentialProperties.builder()
.roleArn(roleArn)
.roleSessionName(builder.roleSessionName)
.webIdentityTokenFile(webIdentityTokenFile)
.build();
this.assumeRoleWithWebIdentityRequest = builder.assumeRoleWithWebIdentityRequestSupplier != null
? builder.assumeRoleWithWebIdentityRequestSupplier
: () -> AssumeRoleWithWebIdentityRequest.builder()
.roleArn(credentialProperties.roleArn())
.roleSessionName(sessionName)
.build();
AwsCredentialsProvider credentialsProviderLocal = null;
RuntimeException loadExceptionLocal = null;
try {
AssumeRoleWithWebIdentityRequestSupplier supplier =
AssumeRoleWithWebIdentityRequestSupplier.builder()
.assumeRoleWithWebIdentityRequest(assumeRoleWithWebIdentityRequest.get())
.webIdentityTokenFile(credentialProperties.webIdentityTokenFile())
.build();
credentialsProviderLocal =
StsAssumeRoleWithWebIdentityCredentialsProvider.builder()
.stsClient(builder.stsClient)
.refreshRequest(supplier)
.build();
} catch (RuntimeException e) {
// If we couldn't load the credentials provider for some reason, save an exception describing why. This exception
// will only be raised on calls to getCredentials. We don't want to raise an exception here because it may be
// expected (eg. in the default credential chain).
loadExceptionLocal = e;
}
this.loadException = loadExceptionLocal;
this.credentialsProvider = credentialsProviderLocal;
this.webIdentityTokenFile = builder.webIdentityTokenFile;
this.roleArn = builder.roleArn;
this.roleSessionName = builder.roleSessionName;
this.assumeRoleWithWebIdentityRequestFromBuilder = builder.assumeRoleWithWebIdentityRequestSupplier;
}
public static Builder builder() {
return new Builder();
}
@Override
public AwsCredentials resolveCredentials() {
if (loadException != null) {
throw loadException;
}
return credentialsProvider.resolveCredentials();
}
@Override
public String toString() {
return ToString.create("StsWebIdentityTokenFileCredentialsProvider");
}
@Override
protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) {
AssumeRoleWithWebIdentityRequest request = assumeRoleWithWebIdentityRequest.get();
notNull(request, "AssumeRoleWithWebIdentityRequest can't be null");
return toAwsSessionCredentials(stsClient.assumeRoleWithWebIdentity(request).credentials());
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
public static final class Builder extends BaseBuilder<Builder, StsWebIdentityTokenFileCredentialsProvider> {
private String roleArn;
private String roleSessionName;
private Path webIdentityTokenFile;
private Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequestSupplier;
private StsClient stsClient;
private Builder() {
super(StsWebIdentityTokenFileCredentialsProvider::new);
}
private Builder(StsWebIdentityTokenFileCredentialsProvider provider) {
super(StsWebIdentityTokenFileCredentialsProvider::new);
this.roleArn = provider.roleArn;
this.roleSessionName = provider.roleSessionName;
this.webIdentityTokenFile = provider.webIdentityTokenFile;
this.assumeRoleWithWebIdentityRequestSupplier = provider.assumeRoleWithWebIdentityRequestFromBuilder;
this.stsClient = provider.stsClient;
}
/**
* The Custom {@link StsClient} that will be used to fetch AWS service credentials.
* <ul>
* <li>This SDK client must be closed by the caller when it is ready to be disposed.</li>
* <li>This SDK client's retry policy should handle IdpCommunicationErrorException </li>
* </ul>
* @param stsClient The STS client to use for communication with STS.
* Make sure IdpCommunicationErrorException is retried in the retry policy for this client.
* Make sure the custom STS client is closed when it is ready to be disposed.
* @return Returns a reference to this object so that method calls can be chained together.
*/
@Override
public Builder stsClient(StsClient stsClient) {
this.stsClient = stsClient;
return super.stsClient(stsClient);
}
/**
* <p>
* The Amazon Resource Name (ARN) of the IAM role that is associated with the Sts.
* If not provided this will be read from SdkSystemSetting.AWS_ROLE_ARN.
* </p>
*
* @param roleArn The Amazon Resource Name (ARN) of the IAM role that is associated with the Sts cluster.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder roleArn(String roleArn) {
this.roleArn = roleArn;
return this;
}
/**
* <p>
* Sets Amazon Resource Name (ARN) of the IAM role that is associated with the Sts.
* By default this will be read from SdkSystemSetting.AWS_ROLE_ARN.
* </p>
*
* @param roleArn The Amazon Resource Name (ARN) of the IAM role that is associated with the Sts cluster.
*/
public void setRoleArn(String roleArn) {
roleArn(roleArn);
}
/**
* <p>
* Sets the role session name that should be used by this credentials provider.
* By default this is read from SdkSystemSetting.AWS_ROLE_SESSION_NAME
* </p>
*
* @param roleSessionName role session name that should be used by this credentials provider
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder roleSessionName(String roleSessionName) {
this.roleSessionName = roleSessionName;
return this;
}
/**
* <p>
* Sets the role session name that should be used by this credentials provider.
* By default this is read from SdkSystemSetting.AWS_ROLE_SESSION_NAME
* </p>
*
* @param roleSessionName role session name that should be used by this credentials provider.
*/
public void setRoleSessionName(String roleSessionName) {
roleSessionName(roleSessionName);
}
/**
* <p>
* Sets the absolute path to the web identity token file that should be used by this credentials provider.
* By default this will be read from SdkSystemSetting.AWS_WEB_IDENTITY_TOKEN_FILE.
* </p>
*
* @param webIdentityTokenFile absolute path to the web identity token file that should be used by this credentials
* provider.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder webIdentityTokenFile(Path webIdentityTokenFile) {
this.webIdentityTokenFile = webIdentityTokenFile;
return this;
}
public void setWebIdentityTokenFile(Path webIdentityTokenFile) {
webIdentityTokenFile(webIdentityTokenFile);
}
/**
* Configure the {@link AssumeRoleWithWebIdentityRequest} that should be periodically sent to the STS service to update
* the session token when it gets close to expiring.
*
* @param assumeRoleWithWebIdentityRequest The request to send to STS whenever the assumed session expires.
* @return This object for chained calls.
*/
public Builder refreshRequest(AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest) {
return refreshRequest(() -> assumeRoleWithWebIdentityRequest);
}
/**
* Similar to {@link #refreshRequest(AssumeRoleWithWebIdentityRequest)}, but takes a {@link Supplier} to supply the
* request to STS.
*
* @param assumeRoleWithWebIdentityRequestSupplier A supplier
* @return This object for chained calls.
*/
public Builder refreshRequest(Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequestSupplier) {
this.assumeRoleWithWebIdentityRequestSupplier = assumeRoleWithWebIdentityRequestSupplier;
return this;
}
/**
* Similar to {@link #refreshRequest(AssumeRoleWithWebIdentityRequest)}, but takes a lambda to configure a new {@link
* AssumeRoleWithWebIdentityRequest.Builder}. This removes the need to call {@link
* AssumeRoleWithWebIdentityRequest#builder()} and {@link AssumeRoleWithWebIdentityRequest.Builder#build()}.
*/
public Builder refreshRequest(Consumer<AssumeRoleWithWebIdentityRequest.Builder> assumeRoleWithWebIdentityRequest) {
return refreshRequest(AssumeRoleWithWebIdentityRequest.builder().applyMutation(assumeRoleWithWebIdentityRequest)
.build());
}
@Override
public StsWebIdentityTokenFileCredentialsProvider build() {
return new StsWebIdentityTokenFileCredentialsProvider(this);
}
}
} | 5,155 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleWithWebIdentityCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials;
import static software.amazon.awssdk.utils.Validate.notNull;
import java.util.function.Consumer;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An implementation of {@link AwsCredentialsProvider} that periodically sends an {@link AssumeRoleWithWebIdentityRequest} to the
* AWS Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a
* single calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set).
*
* If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until
* they are updated successfully.
*
* Users of this provider must {@link #close()} it when they are finished using it.
*
* This is created using {@link #builder()}.
*/
@SdkPublicApi
@ThreadSafe
public final class StsAssumeRoleWithWebIdentityCredentialsProvider
extends StsCredentialsProvider
implements ToCopyableBuilder<StsAssumeRoleWithWebIdentityCredentialsProvider.Builder,
StsAssumeRoleWithWebIdentityCredentialsProvider> {
private final Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequest;
/**
* @see #builder()
*/
private StsAssumeRoleWithWebIdentityCredentialsProvider(Builder builder) {
super(builder, "sts-assume-role-with-web-identity-credentials-provider");
notNull(builder.assumeRoleWithWebIdentityRequestSupplier, "Assume role with web identity request must not be null.");
this.assumeRoleWithWebIdentityRequest = builder.assumeRoleWithWebIdentityRequestSupplier;
}
/**
* Create a builder for an {@link StsAssumeRoleWithWebIdentityCredentialsProvider}.
*/
public static Builder builder() {
return new Builder();
}
@Override
protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) {
AssumeRoleWithWebIdentityRequest request = assumeRoleWithWebIdentityRequest.get();
notNull(request, "AssumeRoleWithWebIdentityRequest can't be null");
return toAwsSessionCredentials(stsClient.assumeRoleWithWebIdentity(request).credentials());
}
@Override
public String toString() {
return ToString.create("StsAssumeRoleWithWebIdentityCredentialsProvider");
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
/**
* A builder (created by {@link StsAssumeRoleWithWebIdentityCredentialsProvider#builder()}) for creating a
* {@link StsAssumeRoleWithWebIdentityCredentialsProvider}.
*/
@NotThreadSafe
public static final class Builder extends BaseBuilder<Builder, StsAssumeRoleWithWebIdentityCredentialsProvider> {
private Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequestSupplier;
private Builder() {
super(StsAssumeRoleWithWebIdentityCredentialsProvider::new);
}
public Builder(StsAssumeRoleWithWebIdentityCredentialsProvider provider) {
super(StsAssumeRoleWithWebIdentityCredentialsProvider::new, provider);
this.assumeRoleWithWebIdentityRequestSupplier = provider.assumeRoleWithWebIdentityRequest;
}
/**
* Configure the {@link AssumeRoleWithWebIdentityRequest} that should be periodically sent to the STS service to update
* the session token when it gets close to expiring.
*
* @param assumeRoleWithWebIdentityRequest The request to send to STS whenever the assumed session expires.
* @return This object for chained calls.
*/
public Builder refreshRequest(AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest) {
return refreshRequest(() -> assumeRoleWithWebIdentityRequest);
}
/**
* Similar to {@link #refreshRequest(AssumeRoleWithWebIdentityRequest)}, but takes a {@link Supplier} to supply the
* request to STS.
*
* @param assumeRoleWithWebIdentityRequest A supplier
* @return This object for chained calls.
*/
public Builder refreshRequest(Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequest) {
this.assumeRoleWithWebIdentityRequestSupplier = assumeRoleWithWebIdentityRequest;
return this;
}
/**
* Similar to {@link #refreshRequest(AssumeRoleWithWebIdentityRequest)}, but takes a lambda to configure a new
* {@link AssumeRoleWithWebIdentityRequest.Builder}. This removes the need to called
* {@link AssumeRoleWithWebIdentityRequest#builder()} and {@link AssumeRoleWithWebIdentityRequest.Builder#build()}.
*/
public Builder refreshRequest(Consumer<AssumeRoleWithWebIdentityRequest.Builder> assumeRoleWithWebIdentityRequest) {
return refreshRequest(AssumeRoleWithWebIdentityRequest.builder().applyMutation(assumeRoleWithWebIdentityRequest)
.build());
}
@Override
public StsAssumeRoleWithWebIdentityCredentialsProvider build() {
return super.build();
}
}
}
| 5,156 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsGetSessionTokenCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.GetSessionTokenRequest;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An implementation of {@link AwsCredentialsProvider} that periodically sends a {@link GetSessionTokenRequest} to the AWS
* Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a single
* calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set).
*
* If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until
* they are updated successfully.
*
* Users of this provider must {@link #close()} it when they are finished using it.
*
* This is created using {@link #builder()}.
*/
@SdkPublicApi
@ThreadSafe
public class StsGetSessionTokenCredentialsProvider
extends StsCredentialsProvider
implements ToCopyableBuilder<StsGetSessionTokenCredentialsProvider.Builder, StsGetSessionTokenCredentialsProvider> {
private final GetSessionTokenRequest getSessionTokenRequest;
/**
* @see #builder()
*/
private StsGetSessionTokenCredentialsProvider(Builder builder) {
super(builder, "sts-get-token-credentials-provider");
Validate.notNull(builder.getSessionTokenRequest, "Get session token request must not be null.");
this.getSessionTokenRequest = builder.getSessionTokenRequest;
}
/**
* Create a builder for an {@link StsGetSessionTokenCredentialsProvider}.
*/
public static Builder builder() {
return new Builder();
}
@Override
protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) {
return toAwsSessionCredentials(stsClient.getSessionToken(getSessionTokenRequest).credentials());
}
@Override
public String toString() {
return ToString.create("StsGetSessionTokenCredentialsProvider");
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
/**
* A builder (created by {@link StsGetSessionTokenCredentialsProvider#builder()}) for creating a
* {@link StsGetSessionTokenCredentialsProvider}.
*/
@NotThreadSafe
public static final class Builder extends BaseBuilder<Builder, StsGetSessionTokenCredentialsProvider> {
private GetSessionTokenRequest getSessionTokenRequest = GetSessionTokenRequest.builder().build();
private Builder() {
super(StsGetSessionTokenCredentialsProvider::new);
}
public Builder(StsGetSessionTokenCredentialsProvider provider) {
super(StsGetSessionTokenCredentialsProvider::new, provider);
this.getSessionTokenRequest = provider.getSessionTokenRequest;
}
/**
* Configure the {@link GetSessionTokenRequest} that should be periodically sent to the STS service to update the session
* token when it gets close to expiring.
*
* If this is not specified, default values are used.
*
* @param getSessionTokenRequest The request to send to STS whenever the assumed session expires.
* @return This object for chained calls.
*/
public Builder refreshRequest(GetSessionTokenRequest getSessionTokenRequest) {
this.getSessionTokenRequest = getSessionTokenRequest;
return this;
}
/**
* Similar to {@link #refreshRequest(GetSessionTokenRequest)}, but takes a lambda to configure a new
* {@link GetSessionTokenRequest.Builder}. This removes the need to called
* {@link GetSessionTokenRequest#builder()} and {@link GetSessionTokenRequest.Builder#build()}.
*/
public Builder refreshRequest(Consumer<GetSessionTokenRequest.Builder> getFederationTokenRequest) {
return refreshRequest(GetSessionTokenRequest.builder().applyMutation(getFederationTokenRequest).build());
}
@Override
public StsGetSessionTokenCredentialsProvider build() {
return super.build();
}
}
}
| 5,157 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsGetFederationTokenCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.GetFederationTokenRequest;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An implementation of {@link AwsCredentialsProvider} that periodically sends a {@link GetFederationTokenRequest} to the AWS
* Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a single
* calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set).
*
* If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until
* they are updated successfully.
*
* Users of this provider must {@link #close()} it when they are finished using it.
*
* This is created using {@link #builder()}.
*/
@SdkPublicApi
@ThreadSafe
public class StsGetFederationTokenCredentialsProvider
extends StsCredentialsProvider
implements ToCopyableBuilder<StsGetFederationTokenCredentialsProvider.Builder, StsGetFederationTokenCredentialsProvider> {
private final GetFederationTokenRequest getFederationTokenRequest;
/**
* @see #builder()
*/
private StsGetFederationTokenCredentialsProvider(Builder builder) {
super(builder, "sts-get-federation-token-credentials-provider");
Validate.notNull(builder.getFederationTokenRequest, "Get session token request must not be null.");
this.getFederationTokenRequest = builder.getFederationTokenRequest;
}
/**
* Create a builder for an {@link StsGetFederationTokenCredentialsProvider}.
*/
public static Builder builder() {
return new Builder();
}
@Override
protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) {
return toAwsSessionCredentials(stsClient.getFederationToken(getFederationTokenRequest).credentials());
}
@Override
public String toString() {
return ToString.create("StsGetFederationTokenCredentialsProvider");
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
/**
* A builder (created by {@link StsGetFederationTokenCredentialsProvider#builder()}) for creating a
* {@link StsGetFederationTokenCredentialsProvider}.
*/
@NotThreadSafe
public static final class Builder extends BaseBuilder<Builder, StsGetFederationTokenCredentialsProvider> {
private GetFederationTokenRequest getFederationTokenRequest;
private Builder() {
super(StsGetFederationTokenCredentialsProvider::new);
}
public Builder(StsGetFederationTokenCredentialsProvider provider) {
super(StsGetFederationTokenCredentialsProvider::new, provider);
this.getFederationTokenRequest = provider.getFederationTokenRequest;
}
/**
* Configure the {@link GetFederationTokenRequest} that should be periodically sent to the STS service to update the
* session token when it gets close to expiring.
*
* @param getFederationTokenRequest The request to send to STS whenever the assumed session expires.
* @return This object for chained calls.
*/
public Builder refreshRequest(GetFederationTokenRequest getFederationTokenRequest) {
this.getFederationTokenRequest = getFederationTokenRequest;
return this;
}
/**
* Similar to {@link #refreshRequest(GetFederationTokenRequest)}, but takes a lambda to configure a new
* {@link GetFederationTokenRequest.Builder}. This removes the need to called
* {@link GetFederationTokenRequest#builder()} and {@link GetFederationTokenRequest.Builder#build()}.
*/
public Builder refreshRequest(Consumer<GetFederationTokenRequest.Builder> getFederationTokenRequest) {
return refreshRequest(GetFederationTokenRequest.builder().applyMutation(getFederationTokenRequest).build());
}
@Override
public StsGetFederationTokenCredentialsProvider build() {
return super.build();
}
}
}
| 5,158 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials;
import java.util.function.Consumer;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An implementation of {@link AwsCredentialsProvider} that periodically sends an {@link AssumeRoleRequest} to the AWS
* Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a single
* calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set).
*
* If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until
* they are updated successfully.
*
* Users of this provider must {@link #close()} it when they are finished using it.
*
* This is created using {@link StsAssumeRoleCredentialsProvider#builder()}.
*/
@SdkPublicApi
@ThreadSafe
public final class StsAssumeRoleCredentialsProvider
extends StsCredentialsProvider
implements ToCopyableBuilder<StsAssumeRoleCredentialsProvider.Builder, StsAssumeRoleCredentialsProvider> {
private Supplier<AssumeRoleRequest> assumeRoleRequestSupplier;
/**
* @see #builder()
*/
private StsAssumeRoleCredentialsProvider(Builder builder) {
super(builder, "sts-assume-role-credentials-provider");
Validate.notNull(builder.assumeRoleRequestSupplier, "Assume role request must not be null.");
this.assumeRoleRequestSupplier = builder.assumeRoleRequestSupplier;
}
/**
* Create a builder for an {@link StsAssumeRoleCredentialsProvider}.
*/
public static Builder builder() {
return new Builder();
}
@Override
protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) {
AssumeRoleRequest assumeRoleRequest = assumeRoleRequestSupplier.get();
Validate.notNull(assumeRoleRequest, "Assume role request must not be null.");
return toAwsSessionCredentials(stsClient.assumeRole(assumeRoleRequest).credentials());
}
@Override
public String toString() {
return ToString.create("StsAssumeRoleCredentialsProvider");
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
/**
* A builder (created by {@link StsAssumeRoleCredentialsProvider#builder()}) for creating a
* {@link StsAssumeRoleCredentialsProvider}.
*/
@NotThreadSafe
public static final class Builder extends BaseBuilder<Builder, StsAssumeRoleCredentialsProvider> {
private Supplier<AssumeRoleRequest> assumeRoleRequestSupplier;
private Builder() {
super(StsAssumeRoleCredentialsProvider::new);
}
private Builder(StsAssumeRoleCredentialsProvider provider) {
super(StsAssumeRoleCredentialsProvider::new, provider);
this.assumeRoleRequestSupplier = provider.assumeRoleRequestSupplier;
}
/**
* Configure the {@link AssumeRoleRequest} that should be periodically sent to the STS service to update the assumed
* credentials.
*
* @param assumeRoleRequest The request to send to STS whenever the assumed session expires.
* @return This object for chained calls.
*/
public Builder refreshRequest(AssumeRoleRequest assumeRoleRequest) {
return refreshRequest(() -> assumeRoleRequest);
}
/**
* Similar to {@link #refreshRequest(AssumeRoleRequest)}, but takes a {@link Supplier} to supply the request to
* STS.
*
* @param assumeRoleRequestSupplier A supplier
* @return This object for chained calls.
*/
public Builder refreshRequest(Supplier<AssumeRoleRequest> assumeRoleRequestSupplier) {
this.assumeRoleRequestSupplier = assumeRoleRequestSupplier;
return this;
}
/**
* Similar to {@link #refreshRequest(AssumeRoleRequest)}, but takes a lambda to configure a new
* {@link AssumeRoleRequest.Builder}. This removes the need to called {@link AssumeRoleRequest#builder()} and
* {@link AssumeRoleRequest.Builder#build()}.
*/
public Builder refreshRequest(Consumer<AssumeRoleRequest.Builder> assumeRoleRequest) {
return refreshRequest(AssumeRoleRequest.builder().applyMutation(assumeRoleRequest).build());
}
@Override
public StsAssumeRoleCredentialsProvider build() {
return super.build();
}
}
}
| 5,159 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.function.Function;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.NonBlocking;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* An implementation of {@link AwsCredentialsProvider} that is extended within this package to provide support for periodically-
* updating session credentials.
*
* When credentials get close to expiration, this class will attempt to update them automatically either with a single calling
* thread (by default) or asynchronously (if {@link #asyncCredentialUpdateEnabled} is true). If the credentials expire, this
* class will block all calls to {@link #resolveCredentials()} until the credentials are updated.
*
* Users of this provider must {@link #close()} it when they are finished using it.
*/
@ThreadSafe
@SdkPublicApi
public abstract class StsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable {
private static final Logger log = Logger.loggerFor(StsCredentialsProvider.class);
private static final Duration DEFAULT_STALE_TIME = Duration.ofMinutes(1);
private static final Duration DEFAULT_PREFETCH_TIME = Duration.ofMinutes(5);
/**
* The STS client that should be used for periodically updating the session credentials.
*/
final StsClient stsClient;
/**
* The session cache that handles automatically updating the credentials when they get close to expiring.
*/
private final CachedSupplier<AwsSessionCredentials> sessionCache;
private final Duration staleTime;
private final Duration prefetchTime;
private final Boolean asyncCredentialUpdateEnabled;
StsCredentialsProvider(BaseBuilder<?, ?> builder, String asyncThreadName) {
this.stsClient = Validate.notNull(builder.stsClient, "STS client must not be null.");
this.staleTime = Optional.ofNullable(builder.staleTime).orElse(DEFAULT_STALE_TIME);
this.prefetchTime = Optional.ofNullable(builder.prefetchTime).orElse(DEFAULT_PREFETCH_TIME);
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
CachedSupplier.Builder<AwsSessionCredentials> cacheBuilder =
CachedSupplier.builder(this::updateSessionCredentials)
.cachedValueName(toString());
if (builder.asyncCredentialUpdateEnabled) {
cacheBuilder.prefetchStrategy(new NonBlocking(asyncThreadName));
}
this.sessionCache = cacheBuilder.build();
}
/**
* Update the expiring session credentials by calling STS. Invoked by {@link CachedSupplier} when the credentials
* are close to expiring.
*/
private RefreshResult<AwsSessionCredentials> updateSessionCredentials() {
AwsSessionCredentials credentials = getUpdatedCredentials(stsClient);
Instant actualTokenExpiration =
credentials.expirationTime()
.orElseThrow(() -> new IllegalStateException("Sourced credentials have no expiration value"));
return RefreshResult.builder(credentials)
.staleTime(actualTokenExpiration.minus(staleTime))
.prefetchTime(actualTokenExpiration.minus(prefetchTime))
.build();
}
@Override
public AwsCredentials resolveCredentials() {
AwsSessionCredentials credentials = sessionCache.get();
credentials.expirationTime().ifPresent(t -> {
log.debug(() -> "Using STS credentials with expiration time of " + t);
});
return credentials;
}
@Override
public void close() {
sessionCache.close();
}
/**
* The amount of time, relative to STS token expiration, that the cached credentials are considered stale and
* should no longer be used. All threads will block until the value is updated.
*/
public Duration staleTime() {
return staleTime;
}
/**
* The amount of time, relative to STS token expiration, that the cached credentials are considered close to stale
* and should be updated.
*/
public Duration prefetchTime() {
return prefetchTime;
}
/**
* Implemented by a child class to call STS and get a new set of credentials to be used by this provider.
*/
abstract AwsSessionCredentials getUpdatedCredentials(StsClient stsClient);
/**
* Extended by child class's builders to share configuration across credential providers.
*/
@NotThreadSafe
@SdkPublicApi
public abstract static class BaseBuilder<B extends BaseBuilder<B, T>, T extends ToCopyableBuilder<B, T>>
implements CopyableBuilder<B, T> {
private final Function<B, T> providerConstructor;
private Boolean asyncCredentialUpdateEnabled = false;
private StsClient stsClient;
private Duration staleTime;
private Duration prefetchTime;
BaseBuilder(Function<B, T> providerConstructor) {
this.providerConstructor = providerConstructor;
}
BaseBuilder(Function<B, T> providerConstructor, StsCredentialsProvider provider) {
this.providerConstructor = providerConstructor;
this.asyncCredentialUpdateEnabled = provider.asyncCredentialUpdateEnabled;
this.stsClient = provider.stsClient;
this.staleTime = provider.staleTime;
this.prefetchTime = provider.prefetchTime;
}
/**
* Configure the {@link StsClient} to use when calling STS to update the session. This client should not be shut
* down as long as this credentials provider is in use.
*
* @param stsClient The STS client to use for communication with STS.
* @return This object for chained calls.
*/
@SuppressWarnings("unchecked")
public B stsClient(StsClient stsClient) {
this.stsClient = stsClient;
return (B) this;
}
/**
* Configure whether the provider should fetch credentials asynchronously in the background. If this is true,
* threads are less likely to block when credentials are loaded, but additional resources are used to maintain
* the provider.
*
* <p>By default, this is disabled.</p>
*/
@SuppressWarnings("unchecked")
public B asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return (B) this;
}
/**
* Configure the amount of time, relative to STS token expiration, that the cached credentials are considered
* stale and must be updated. All threads will block until the value is updated.
*
* <p>By default, this is 1 minute.</p>
*/
@SuppressWarnings("unchecked")
public B staleTime(Duration staleTime) {
this.staleTime = staleTime;
return (B) this;
}
/**
* Configure the amount of time, relative to STS token expiration, that the cached credentials are considered
* close to stale and should be updated.
*
* Prefetch updates will occur between the specified time and the stale time of the provider. Prefetch updates may be
* asynchronous. See {@link #asyncCredentialUpdateEnabled}.
*
* <p>By default, this is 5 minutes.</p>
*/
@SuppressWarnings("unchecked")
public B prefetchTime(Duration prefetchTime) {
this.prefetchTime = prefetchTime;
return (B) this;
}
/**
* Build the credentials provider using the configuration applied to this builder.
*/
@SuppressWarnings("unchecked")
public T build() {
return providerConstructor.apply((B) this);
}
}
}
| 5,160 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleWithSamlCredentialsProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.auth;
import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials;
import java.util.function.Consumer;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithSamlRequest;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An implementation of {@link AwsCredentialsProvider} that periodically sends an {@link AssumeRoleWithSamlRequest} to the AWS
* Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a single
* calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set).
*
* If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until
* they are updated successfully.
*
* Users of this provider must {@link #close()} it when they are finished using it.
*
* This is created using {@link StsAssumeRoleWithSamlCredentialsProvider#builder()}.
*/
@SdkPublicApi
@ThreadSafe
public final class StsAssumeRoleWithSamlCredentialsProvider
extends StsCredentialsProvider
implements ToCopyableBuilder<StsAssumeRoleWithSamlCredentialsProvider.Builder, StsAssumeRoleWithSamlCredentialsProvider> {
private final Supplier<AssumeRoleWithSamlRequest> assumeRoleWithSamlRequestSupplier;
/**
* @see #builder()
*/
private StsAssumeRoleWithSamlCredentialsProvider(Builder builder) {
super(builder, "sts-assume-role-with-saml-credentials-provider");
Validate.notNull(builder.assumeRoleWithSamlRequestSupplier, "Assume role with SAML request must not be null.");
this.assumeRoleWithSamlRequestSupplier = builder.assumeRoleWithSamlRequestSupplier;
}
/**
* Create a builder for an {@link StsAssumeRoleWithSamlCredentialsProvider}.
*/
public static Builder builder() {
return new Builder();
}
@Override
protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) {
AssumeRoleWithSamlRequest assumeRoleWithSamlRequest = assumeRoleWithSamlRequestSupplier.get();
Validate.notNull(assumeRoleWithSamlRequest, "Assume role with saml request must not be null.");
return toAwsSessionCredentials(stsClient.assumeRoleWithSAML(assumeRoleWithSamlRequest).credentials());
}
@Override
public String toString() {
return ToString.create("StsAssumeRoleWithSamlCredentialsProvider");
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
/**
* A builder (created by {@link StsAssumeRoleWithSamlCredentialsProvider#builder()}) for creating a
* {@link StsAssumeRoleWithSamlCredentialsProvider}.
*/
@NotThreadSafe
public static final class Builder extends BaseBuilder<Builder, StsAssumeRoleWithSamlCredentialsProvider> {
private Supplier<AssumeRoleWithSamlRequest> assumeRoleWithSamlRequestSupplier;
private Builder() {
super(StsAssumeRoleWithSamlCredentialsProvider::new);
}
public Builder(StsAssumeRoleWithSamlCredentialsProvider provider) {
super(StsAssumeRoleWithSamlCredentialsProvider::new, provider);
this.assumeRoleWithSamlRequestSupplier = provider.assumeRoleWithSamlRequestSupplier;
}
/**
* Configure the {@link AssumeRoleWithSamlRequest} that should be periodically sent to the STS service to update
* the session token when it gets close to expiring.
*
* @param assumeRoleWithSamlRequest The request to send to STS whenever the assumed session expires.
* @return This object for chained calls.
*/
public Builder refreshRequest(AssumeRoleWithSamlRequest assumeRoleWithSamlRequest) {
return refreshRequest(() -> assumeRoleWithSamlRequest);
}
/**
* Similar to {@link #refreshRequest(AssumeRoleWithSamlRequest)}, but takes a {@link Supplier} to supply the request to
* STS.
*
* @param assumeRoleWithSamlRequestSupplier A supplier
* @return This object for chained calls.
*/
public Builder refreshRequest(Supplier<AssumeRoleWithSamlRequest> assumeRoleWithSamlRequestSupplier) {
this.assumeRoleWithSamlRequestSupplier = assumeRoleWithSamlRequestSupplier;
return this;
}
/**
* Similar to {@link #refreshRequest(AssumeRoleWithSamlRequest)}, but takes a lambda to configure a new
* {@link AssumeRoleWithSamlRequest.Builder}. This removes the need to called {@link AssumeRoleWithSamlRequest#builder()}
* and {@link AssumeRoleWithSamlRequest.Builder#build()}.
*/
public Builder refreshRequest(Consumer<AssumeRoleWithSamlRequest.Builder> assumeRoleWithSamlRequest) {
return refreshRequest(AssumeRoleWithSamlRequest.builder().applyMutation(assumeRoleWithSamlRequest).build());
}
@Override
public StsAssumeRoleWithSamlCredentialsProvider build() {
return super.build();
}
}
}
| 5,161 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/internal/StsAuthUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.services.sts.model.Credentials;
@SdkInternalApi
public final class StsAuthUtils {
private StsAuthUtils() {
}
public static AwsSessionCredentials toAwsSessionCredentials(Credentials credentials) {
return AwsSessionCredentials.builder()
.accessKeyId(credentials.accessKeyId())
.secretAccessKey(credentials.secretAccessKey())
.sessionToken(credentials.sessionToken())
.expirationTime(credentials.expiration())
.build();
}
}
| 5,162 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/internal/StsWebIdentityCredentialsProviderFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.internal;
import java.net.URI;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.WebIdentityTokenCredentialsProviderFactory;
import software.amazon.awssdk.auth.credentials.internal.WebIdentityTokenCredentialProperties;
import software.amazon.awssdk.core.retry.conditions.OrRetryCondition;
import software.amazon.awssdk.core.retry.conditions.RetryCondition;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.StsClientBuilder;
import software.amazon.awssdk.services.sts.auth.StsAssumeRoleWithWebIdentityCredentialsProvider;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest;
import software.amazon.awssdk.services.sts.model.IdpCommunicationErrorException;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.NumericUtils;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* An implementation of {@link WebIdentityTokenCredentialsProviderFactory} that allows users to assume a role using a web identity
* token file specified in either a {@link Profile} or environment variables.
*/
@SdkProtectedApi
public final class StsWebIdentityCredentialsProviderFactory implements WebIdentityTokenCredentialsProviderFactory {
@Override
public AwsCredentialsProvider create(WebIdentityTokenCredentialProperties credentialProperties) {
return new StsWebIdentityCredentialsProvider(credentialProperties);
}
/**
* A wrapper for a {@link StsAssumeRoleWithWebIdentityCredentialsProvider} that is returned by this factory when
* {@link #create(WebIdentityTokenCredentialProperties)} is invoked. This wrapper is important because it ensures the parent
* credentials provider is closed when the assume-role credentials provider is no longer needed.
*/
private static final class StsWebIdentityCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable {
private final StsClient stsClient;
private final StsAssumeRoleWithWebIdentityCredentialsProvider credentialsProvider;
private StsWebIdentityCredentialsProvider(WebIdentityTokenCredentialProperties credentialProperties) {
String roleSessionName = credentialProperties.roleSessionName();
String sessionName = roleSessionName != null ? roleSessionName : "aws-sdk-java-" + System.currentTimeMillis();
Boolean asyncCredentialUpdateEnabled = credentialProperties.asyncCredentialUpdateEnabled() != null ?
credentialProperties.asyncCredentialUpdateEnabled() : false;
OrRetryCondition retryCondition =
OrRetryCondition.create(context -> context.exception() instanceof IdpCommunicationErrorException,
RetryCondition.defaultRetryCondition());
this.stsClient = StsClient.builder()
.applyMutation(this::configureEndpoint)
.credentialsProvider(AnonymousCredentialsProvider.create())
.overrideConfiguration(o -> o.retryPolicy(r -> r.retryCondition(retryCondition)))
.build();
AssumeRoleWithWebIdentityRequest.Builder requestBuilder = AssumeRoleWithWebIdentityRequest
.builder()
.roleArn(credentialProperties.roleArn())
.roleSessionName(sessionName);
if (credentialProperties.roleSessionDuration() != null) {
requestBuilder.durationSeconds(NumericUtils.saturatedCast(
credentialProperties.roleSessionDuration().getSeconds()));
}
AssumeRoleWithWebIdentityRequestSupplier supplier =
AssumeRoleWithWebIdentityRequestSupplier.builder()
.assumeRoleWithWebIdentityRequest(requestBuilder.build())
.webIdentityTokenFile(credentialProperties.webIdentityTokenFile())
.build();
StsAssumeRoleWithWebIdentityCredentialsProvider.Builder builder =
StsAssumeRoleWithWebIdentityCredentialsProvider.builder()
.asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled)
.stsClient(stsClient)
.refreshRequest(supplier);
if (credentialProperties.prefetchTime() != null) {
builder.prefetchTime(credentialProperties.prefetchTime());
}
if (credentialProperties.staleTime() != null) {
builder.staleTime(credentialProperties.staleTime());
}
this.credentialsProvider = builder.build();
}
@Override
public AwsCredentials resolveCredentials() {
return this.credentialsProvider.resolveCredentials();
}
@Override
public void close() {
IoUtils.closeQuietly(credentialsProvider, null);
IoUtils.closeQuietly(stsClient, null);
}
private void configureEndpoint(StsClientBuilder stsClientBuilder) {
Region stsRegion;
try {
stsRegion = new DefaultAwsRegionProviderChain().getRegion();
} catch (RuntimeException e) {
stsRegion = null;
}
if (stsRegion != null) {
stsClientBuilder.region(stsRegion);
} else {
stsClientBuilder.region(Region.US_EAST_1);
stsClientBuilder.endpointOverride(URI.create("https://sts.amazonaws.com"));
}
}
}
}
| 5,163 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/internal/StsProfileCredentialsProviderFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.internal;
import java.net.URI;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ChildProfileCredentialsProviderFactory;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.StsClientBuilder;
import software.amazon.awssdk.services.sts.auth.StsAssumeRoleCredentialsProvider;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* An implementation of {@link ChildProfileCredentialsProviderFactory} that uses configuration in a profile to create a
* {@link StsAssumeRoleCredentialsProvider}.
*/
@SdkInternalApi
public final class StsProfileCredentialsProviderFactory implements ChildProfileCredentialsProviderFactory {
private static final String MISSING_PROPERTY_ERROR_FORMAT = "'%s' must be set to use role-based credential loading in the "
+ "'%s' profile.";
@Override
public AwsCredentialsProvider create(AwsCredentialsProvider sourceCredentialsProvider, Profile profile) {
return new StsProfileCredentialsProvider(sourceCredentialsProvider, profile);
}
/**
* A wrapper for a {@link StsAssumeRoleCredentialsProvider} that is returned by this factory when
* {@link #create(AwsCredentialsProvider, Profile)} is invoked. This wrapper is important because it ensures the parent
* credentials provider is closed when the assume-role credentials provider is no longer needed.
*/
private static final class StsProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable {
private final StsClient stsClient;
private final AwsCredentialsProvider parentCredentialsProvider;
private final StsAssumeRoleCredentialsProvider credentialsProvider;
private StsProfileCredentialsProvider(AwsCredentialsProvider parentCredentialsProvider, Profile profile) {
String roleArn = requireProperty(profile, ProfileProperty.ROLE_ARN);
String roleSessionName = profile.property(ProfileProperty.ROLE_SESSION_NAME)
.orElseGet(() -> "aws-sdk-java-" + System.currentTimeMillis());
String externalId = profile.property(ProfileProperty.EXTERNAL_ID).orElse(null);
AssumeRoleRequest assumeRoleRequest = AssumeRoleRequest.builder()
.roleArn(roleArn)
.roleSessionName(roleSessionName)
.externalId(externalId)
.build();
this.stsClient = StsClient.builder()
.applyMutation(client -> configureEndpoint(client, profile))
.credentialsProvider(parentCredentialsProvider)
.build();
this.parentCredentialsProvider = parentCredentialsProvider;
this.credentialsProvider = StsAssumeRoleCredentialsProvider.builder()
.stsClient(stsClient)
.refreshRequest(assumeRoleRequest)
.build();
}
private void configureEndpoint(StsClientBuilder stsClientBuilder, Profile profile) {
Region stsRegion = profile.property(ProfileProperty.REGION)
.map(Region::of)
.orElseGet(() -> {
try {
return new DefaultAwsRegionProviderChain().getRegion();
} catch (RuntimeException e) {
return null;
}
});
if (stsRegion != null) {
stsClientBuilder.region(stsRegion);
} else {
stsClientBuilder.region(Region.US_EAST_1);
stsClientBuilder.endpointOverride(URI.create("https://sts.amazonaws.com"));
}
}
private String requireProperty(Profile profile, String requiredProperty) {
return profile.property(requiredProperty)
.orElseThrow(() -> new IllegalArgumentException(String.format(MISSING_PROPERTY_ERROR_FORMAT,
requiredProperty, profile.name())));
}
@Override
public AwsCredentials resolveCredentials() {
return this.credentialsProvider.resolveCredentials();
}
@Override
public void close() {
IoUtils.closeIfCloseable(parentCredentialsProvider, null);
IoUtils.closeQuietly(credentialsProvider, null);
IoUtils.closeQuietly(stsClient, null);
}
}
}
| 5,164 |
0 | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts | Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/internal/AssumeRoleWithWebIdentityRequestSupplier.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.sts.internal;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest;
import software.amazon.awssdk.utils.IoUtils;
@SdkInternalApi
public class AssumeRoleWithWebIdentityRequestSupplier implements Supplier<AssumeRoleWithWebIdentityRequest> {
private final AssumeRoleWithWebIdentityRequest request;
private final Path webIdentityTokenFile;
public AssumeRoleWithWebIdentityRequestSupplier(Builder builder) {
this.request = builder.request;
this.webIdentityTokenFile = builder.webIdentityTokenFile;
}
public static Builder builder() {
return new Builder();
}
@Override
public AssumeRoleWithWebIdentityRequest get() {
return request.toBuilder().webIdentityToken(getToken(webIdentityTokenFile)).build();
}
//file extraction
private String getToken(Path file) {
try (InputStream webIdentityTokenStream = Files.newInputStream(file)) {
return IoUtils.toUtf8String(webIdentityTokenStream);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class Builder {
private AssumeRoleWithWebIdentityRequest request;
private Path webIdentityTokenFile;
public Builder assumeRoleWithWebIdentityRequest(AssumeRoleWithWebIdentityRequest request) {
this.request = request;
return this;
}
public Builder webIdentityTokenFile(Path webIdentityTokenFile) {
this.webIdentityTokenFile = webIdentityTokenFile;
return this;
}
public AssumeRoleWithWebIdentityRequestSupplier build() {
return new AssumeRoleWithWebIdentityRequestSupplier(this);
}
}
} | 5,165 |
0 | Create_ds/aws-sdk-java-v2/services/acm/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/acm/src/it/java/software/amazon/awssdk/services/acm/AwsCertficateManagerIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.acm;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.services.acm.model.AcmException;
import software.amazon.awssdk.services.acm.model.GetCertificateRequest;
import software.amazon.awssdk.services.acm.model.ListCertificatesRequest;
import software.amazon.awssdk.services.acm.model.ListCertificatesResponse;
import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase;
public class AwsCertficateManagerIntegrationTest extends AwsIntegrationTestBase {
private static AcmClient client;
@BeforeClass
public static void setUp() {
client = AcmClient.builder().credentialsProvider(StaticCredentialsProvider.create(getCredentials())).build();
}
@Test
public void list_certificates() {
ListCertificatesResponse result = client.listCertificates(ListCertificatesRequest.builder().build());
Assert.assertTrue(result.certificateSummaryList().size() >= 0);
}
@Test
public void list_certificates_using_oldSigv4aSigner() {
AcmClient client = AcmClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(getCredentials()))
.overrideConfiguration(c -> c.putAdvancedOption(SdkAdvancedClientOption.SIGNER,
AwsCrtV4aSigner.create()))
.build();
ListCertificatesResponse result = client.listCertificates(ListCertificatesRequest.builder().build());
Assert.assertTrue(result.certificateSummaryList().size() >= 0);
}
/**
* Ideally the service must be throwing a Invalid Arn exception
* instead of SdkServiceException. Have reported this to service to
* fix it.
* TODO Change the expected when service fix this.
*/
@Test(expected = AcmException.class)
public void get_certificate_fake_arn_throws_exception() {
client.getCertificate(GetCertificateRequest.builder().certificateArn("arn:aws:acm:us-east-1:123456789:fakecert").build());
}
}
| 5,166 |
0 | Create_ds/aws-sdk-java-v2/services/route53/src/test/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/route53/src/test/java/software/amazon/awssdk/services/route53/Route53InterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.route53;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkResponse;
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.services.route53.internal.Route53IdInterceptor;
import software.amazon.awssdk.services.route53.model.ActivateKeySigningKeyResponse;
import software.amazon.awssdk.services.route53.model.ChangeInfo;
import software.amazon.awssdk.services.route53.model.CreateHostedZoneRequest;
import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse;
import software.amazon.awssdk.services.route53.model.CreateKeySigningKeyResponse;
import software.amazon.awssdk.services.route53.model.CreateReusableDelegationSetResponse;
import software.amazon.awssdk.services.route53.model.DeactivateKeySigningKeyResponse;
import software.amazon.awssdk.services.route53.model.DelegationSet;
import software.amazon.awssdk.services.route53.model.DeleteKeySigningKeyResponse;
import software.amazon.awssdk.services.route53.model.DisableHostedZoneDnssecResponse;
import software.amazon.awssdk.services.route53.model.EnableHostedZoneDnssecResponse;
import software.amazon.awssdk.services.route53.model.GetHostedZoneResponse;
import software.amazon.awssdk.services.route53.model.GetReusableDelegationSetResponse;
import software.amazon.awssdk.services.route53.model.ListReusableDelegationSetsResponse;
/**
* Unit test for request handler customization of delegation set id's
*/
//TODO: fix test, see comment on line 80")
public class Route53InterceptorTest {
private static final String delegationPrefix = "delegationset";
private static final String changeInfoPrefix = "change";
private static final String id = "delegationSetId";
private static final String changeInfoId = "changeInfoId";
private static final String delegationSetId = "/" + delegationPrefix + "/" + id;
private static final String changeInfoIdWithPrefix = "/" + changeInfoPrefix + "/" + changeInfoId;
/**
* Tests if the request handler strips the delegation set prefixes. Asserts
* that the result object has prefix removed.
*/
@Test
public void testDelegationSetPrefixRemoval() {
Route53IdInterceptor interceptor = new Route53IdInterceptor();
DelegationSet delegationSet = DelegationSet.builder().id(delegationSetId).build();
CreateHostedZoneResponse createResult = CreateHostedZoneResponse.builder()
.delegationSet(delegationSet)
.build();
createResult = (CreateHostedZoneResponse) modifyResponse(interceptor, createResult);
assertEquals(createResult.delegationSet().id(), id);
CreateReusableDelegationSetResponse createResuableResult = CreateReusableDelegationSetResponse.builder()
.delegationSet(delegationSet)
.build();
createResuableResult = (CreateReusableDelegationSetResponse) modifyResponse(interceptor, createResuableResult);
assertEquals(createResuableResult.delegationSet().id(), id);
GetHostedZoneResponse getZoneResult = GetHostedZoneResponse.builder()
.delegationSet(delegationSet)
.build();
getZoneResult = (GetHostedZoneResponse) modifyResponse(interceptor, getZoneResult);
// This assert works, but only because of the other operations the are sequenced before this, that modify the id.
assertEquals(getZoneResult.delegationSet().id(), id);
GetReusableDelegationSetResponse getResuableResult = GetReusableDelegationSetResponse.builder()
.delegationSet(delegationSet)
.build();
getResuableResult = (GetReusableDelegationSetResponse) modifyResponse(interceptor, getResuableResult);
assertEquals(getResuableResult.delegationSet().id(), id);
ListReusableDelegationSetsResponse listResult = ListReusableDelegationSetsResponse.builder()
.delegationSets(delegationSet)
.build();
listResult = (ListReusableDelegationSetsResponse) modifyResponse(interceptor, listResult);
assertEquals(listResult.delegationSets().get(0).id(), id);
delegationSet = delegationSet.toBuilder().id(id).build();
createResult = CreateHostedZoneResponse.builder()
.delegationSet(delegationSet)
.build();
createResult = (CreateHostedZoneResponse) modifyResponse(interceptor, createResult);
assertEquals(createResult.delegationSet().id(), id);
}
private SdkResponse modifyResponse(ExecutionInterceptor interceptor, SdkResponse responseObject) {
return interceptor.modifyResponse(InterceptorContext.builder()
.request(CreateHostedZoneRequest.builder().build())
.response(responseObject)
.build(),
new ExecutionAttributes());
}
@Test
public void testChangeInfoPrefixRemoval() {
Route53IdInterceptor interceptor = new Route53IdInterceptor();
ChangeInfo changeInfo = ChangeInfo.builder().id(changeInfoIdWithPrefix).build();
CreateKeySigningKeyResponse createKeySigningKeyResponse = CreateKeySigningKeyResponse.builder()
.changeInfo(changeInfo).build();
createKeySigningKeyResponse = (CreateKeySigningKeyResponse) modifyResponse(interceptor, createKeySigningKeyResponse);
assertEquals(createKeySigningKeyResponse.changeInfo().id(), changeInfoId);
DeleteKeySigningKeyResponse deleteKeySigningKeyResponse = DeleteKeySigningKeyResponse.builder()
.changeInfo(changeInfo).build();
deleteKeySigningKeyResponse = (DeleteKeySigningKeyResponse) modifyResponse(interceptor, deleteKeySigningKeyResponse);
assertEquals(deleteKeySigningKeyResponse.changeInfo().id(), changeInfoId);
ActivateKeySigningKeyResponse activateKeySigningKeyResponse = ActivateKeySigningKeyResponse.builder()
.changeInfo(changeInfo).build();
activateKeySigningKeyResponse = (ActivateKeySigningKeyResponse) modifyResponse(interceptor, activateKeySigningKeyResponse);
assertEquals(activateKeySigningKeyResponse.changeInfo().id(), changeInfoId);
DeactivateKeySigningKeyResponse deactivateKeySigningKeyResponse = DeactivateKeySigningKeyResponse.builder()
.changeInfo(changeInfo).build();
deactivateKeySigningKeyResponse = (DeactivateKeySigningKeyResponse) modifyResponse(interceptor, deactivateKeySigningKeyResponse);
assertEquals(deactivateKeySigningKeyResponse.changeInfo().id(), changeInfoId);
EnableHostedZoneDnssecResponse enableHostedZoneDnssecResponse = EnableHostedZoneDnssecResponse.builder()
.changeInfo(changeInfo).build();
enableHostedZoneDnssecResponse = (EnableHostedZoneDnssecResponse) modifyResponse(interceptor, enableHostedZoneDnssecResponse);
assertEquals(enableHostedZoneDnssecResponse.changeInfo().id(), changeInfoId);
DisableHostedZoneDnssecResponse disableHostedZoneDnssecResponse = DisableHostedZoneDnssecResponse.builder()
.changeInfo(changeInfo).build();
disableHostedZoneDnssecResponse = (DisableHostedZoneDnssecResponse) modifyResponse(interceptor, disableHostedZoneDnssecResponse);
assertEquals(disableHostedZoneDnssecResponse.changeInfo().id(), changeInfoId);
}
}
| 5,167 |
0 | Create_ds/aws-sdk-java-v2/services/route53/src/test/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/route53/src/test/java/software/amazon/awssdk/services/route53/QueryParamBindingTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.route53;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.net.URI;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.protocols.xml.AwsXmlProtocolFactory;
import software.amazon.awssdk.services.route53.model.GetHealthCheckLastFailureReasonRequest;
import software.amazon.awssdk.services.route53.model.ListHealthChecksRequest;
import software.amazon.awssdk.services.route53.transform.GetHealthCheckLastFailureReasonRequestMarshaller;
import software.amazon.awssdk.services.route53.transform.ListHealthChecksRequestMarshaller;
public class QueryParamBindingTest {
protected static final AwsXmlProtocolFactory PROTOCOL_FACTORY = AwsXmlProtocolFactory
.builder()
.clientConfiguration(SdkClientConfiguration.builder()
.option(SdkClientOption.ENDPOINT, URI.create("http://localhost"))
.build())
.build();
/**
* Make sure the marshaller is able to handle @UriLabel parameter values
* containing special characters.
*/
@Test
public void testReservedCharInParamValue() {
final String VALUE_WITH_SEMICOLON = ";foo";
final String VALUE_WITH_AMPERSAND = "&bar";
final String VALUE_WITH_QUESTION_MARK = "?charlie";
ListHealthChecksRequest listReq = ListHealthChecksRequest.builder()
.marker(VALUE_WITH_SEMICOLON)
.maxItems(VALUE_WITH_AMPERSAND)
.build();
SdkHttpFullRequest httpReq_List = new ListHealthChecksRequestMarshaller(PROTOCOL_FACTORY).marshall(listReq);
assertEquals("/2013-04-01/healthcheck", httpReq_List.encodedPath());
Map<String, List<String>> queryParams = httpReq_List.rawQueryParameters();
assertEquals(2, queryParams.size());
assertEquals(VALUE_WITH_SEMICOLON, queryParams.get("marker").get(0));
assertEquals(VALUE_WITH_AMPERSAND, queryParams.get("maxitems").get(0));
GetHealthCheckLastFailureReasonRequest getFailureReq = GetHealthCheckLastFailureReasonRequest.builder()
.healthCheckId(VALUE_WITH_QUESTION_MARK)
.build();
SdkHttpFullRequest httpReq_GetFailure =
new GetHealthCheckLastFailureReasonRequestMarshaller(PROTOCOL_FACTORY).marshall(getFailureReq);
System.out.println(httpReq_GetFailure);
// parameter value should be URL encoded
assertEquals(
"/2013-04-01/healthcheck/%3Fcharlie/lastfailurereason",
httpReq_GetFailure.encodedPath());
queryParams = httpReq_GetFailure.rawQueryParameters();
assertEquals(0, queryParams.size());
}
}
| 5,168 |
0 | Create_ds/aws-sdk-java-v2/services/route53/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/route53/src/it/java/software/amazon/awssdk/services/route53/Route53IntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.route53;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import java.util.UUID;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkGlobalTime;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.route53.model.Change;
import software.amazon.awssdk.services.route53.model.ChangeAction;
import software.amazon.awssdk.services.route53.model.ChangeBatch;
import software.amazon.awssdk.services.route53.model.ChangeInfo;
import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsRequest;
import software.amazon.awssdk.services.route53.model.CreateHealthCheckRequest;
import software.amazon.awssdk.services.route53.model.CreateHealthCheckResponse;
import software.amazon.awssdk.services.route53.model.CreateHostedZoneRequest;
import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse;
import software.amazon.awssdk.services.route53.model.DelegationSet;
import software.amazon.awssdk.services.route53.model.DeleteHealthCheckRequest;
import software.amazon.awssdk.services.route53.model.DeleteHostedZoneRequest;
import software.amazon.awssdk.services.route53.model.DeleteHostedZoneResponse;
import software.amazon.awssdk.services.route53.model.GetChangeRequest;
import software.amazon.awssdk.services.route53.model.GetHealthCheckRequest;
import software.amazon.awssdk.services.route53.model.GetHealthCheckResponse;
import software.amazon.awssdk.services.route53.model.GetHostedZoneRequest;
import software.amazon.awssdk.services.route53.model.GetHostedZoneResponse;
import software.amazon.awssdk.services.route53.model.HealthCheck;
import software.amazon.awssdk.services.route53.model.HealthCheckConfig;
import software.amazon.awssdk.services.route53.model.HostedZone;
import software.amazon.awssdk.services.route53.model.HostedZoneConfig;
import software.amazon.awssdk.services.route53.model.ListHostedZonesRequest;
import software.amazon.awssdk.services.route53.model.ListResourceRecordSetsRequest;
import software.amazon.awssdk.services.route53.model.RRType;
import software.amazon.awssdk.services.route53.model.ResourceRecord;
import software.amazon.awssdk.services.route53.model.ResourceRecordSet;
import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase;
/**
* Integration tests that run through the various operations available in the
* Route 53 API.
*/
public class Route53IntegrationTest extends AwsIntegrationTestBase {
private static final String COMMENT = "comment";
private static final String ZONE_NAME = "java.sdk.com.";
private static final String CALLER_REFERENCE = UUID.randomUUID().toString();
private static final int PORT_NUM = 22;
private static final String TYPE = "TCP";
private static final String IP_ADDRESS = "12.12.12.12";
private static Route53Client route53;
/**
* The ID of the zone we created in this test.
*/
private static String createdZoneId;
/**
* The ID of the change that created our test zone.
*/
private static String createdZoneChangeId;
/**
* the ID of the health check.
*/
private String healthCheckId;
@BeforeClass
public static void setup() {
route53 = Route53Client.builder()
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.region(Region.AWS_GLOBAL)
.build();
// Create Hosted Zone
CreateHostedZoneResponse result = route53.createHostedZone(CreateHostedZoneRequest.builder()
.name(ZONE_NAME)
.callerReference(CALLER_REFERENCE)
.hostedZoneConfig(HostedZoneConfig.builder()
.comment(COMMENT).build()).build()
);
createdZoneId = result.hostedZone().id();
createdZoneChangeId = result.changeInfo().id();
}
/**
* Ensures the HostedZone we create during this test is correctly released.
*/
@AfterClass
public static void tearDown() {
try {
route53.deleteHostedZone(DeleteHostedZoneRequest.builder().id(createdZoneId).build());
} catch (Exception e) {
// Ignored or expected.
}
}
/**
* Runs through each of the APIs in the Route 53 client to make sure we can
* correct send requests and unmarshall responses.
*/
@Test
public void testRoute53() throws Exception {
// Get Hosted Zone
GetHostedZoneRequest hostedZoneRequest = GetHostedZoneRequest.builder().id(createdZoneId).build();
GetHostedZoneResponse hostedZoneResult = route53.getHostedZone(hostedZoneRequest);
assertValidDelegationSet(hostedZoneResult.delegationSet());
assertValidCreatedHostedZone(hostedZoneResult.hostedZone());
// Create a health check
HealthCheckConfig config = HealthCheckConfig.builder().type("TCP").port(PORT_NUM).ipAddress(IP_ADDRESS).build();
CreateHealthCheckResponse createHealthCheckResult = route53.createHealthCheck(
CreateHealthCheckRequest.builder().healthCheckConfig(config).callerReference(CALLER_REFERENCE).build());
healthCheckId = createHealthCheckResult.healthCheck().id();
assertNotNull(createHealthCheckResult.location());
assertValidHealthCheck(createHealthCheckResult.healthCheck());
// Get the health check back
GetHealthCheckResponse gealthCheckResult = route53
.getHealthCheck(GetHealthCheckRequest.builder().healthCheckId(healthCheckId).build());
assertValidHealthCheck(gealthCheckResult.healthCheck());
// Delete the health check
route53.deleteHealthCheck(DeleteHealthCheckRequest.builder().healthCheckId(healthCheckId).build());
// Get the health check back
try {
gealthCheckResult = route53.getHealthCheck(GetHealthCheckRequest.builder().healthCheckId(healthCheckId).build());
fail();
} catch (AwsServiceException e) {
assertNotNull(e.getMessage());
assertNotNull(e.awsErrorDetails().errorCode());
}
// List Hosted Zones
List<HostedZone> hostedZones = route53.listHostedZones(ListHostedZonesRequest.builder().build()).hostedZones();
assertTrue(hostedZones.size() > 0);
for (HostedZone hostedZone : hostedZones) {
assertNotNull(hostedZone.callerReference());
assertNotNull(hostedZone.id());
assertNotNull(hostedZone.name());
}
// List Resource Record Sets
List<ResourceRecordSet> resourceRecordSets = route53.listResourceRecordSets(
ListResourceRecordSetsRequest.builder().hostedZoneId(createdZoneId).build()).resourceRecordSets();
assertTrue(resourceRecordSets.size() > 0);
ResourceRecordSet existingResourceRecordSet = resourceRecordSets.get(0);
for (ResourceRecordSet rrset : resourceRecordSets) {
assertNotNull(rrset.name());
assertNotNull(rrset.type());
assertNotNull(rrset.ttl());
assertTrue(rrset.resourceRecords().size() > 0);
}
// Get Change
ChangeInfo changeInfo = route53.getChange(GetChangeRequest.builder().id(createdZoneChangeId).build()).changeInfo();
assertTrue(changeInfo.id().endsWith(createdZoneChangeId));
assertValidChangeInfo(changeInfo);
// Change Resource Record Sets
ResourceRecordSet newResourceRecordSet = ResourceRecordSet.builder()
.name(ZONE_NAME)
.resourceRecords(existingResourceRecordSet.resourceRecords())
.ttl(existingResourceRecordSet.ttl() + 100)
.type(existingResourceRecordSet.type())
.build();
changeInfo = route53.changeResourceRecordSets(ChangeResourceRecordSetsRequest.builder()
.hostedZoneId(createdZoneId)
.changeBatch(ChangeBatch.builder().comment(COMMENT)
.changes(Change.builder().action(
ChangeAction.DELETE)
.resourceRecordSet(
existingResourceRecordSet).build(),
Change.builder().action(
ChangeAction.CREATE)
.resourceRecordSet(
newResourceRecordSet).build()).build()
).build()).changeInfo();
assertValidChangeInfo(changeInfo);
// Add a weighted Resource Record Set so we can reproduce the bug reported by customers
// when they provide SetIdentifier containing special characters.
String specialChars = "&<>'\"";
newResourceRecordSet =ResourceRecordSet.builder()
.name("weighted." + ZONE_NAME)
.type(RRType.CNAME)
.setIdentifier(specialChars)
.weight(0L)
.ttl(1000L)
.resourceRecords(ResourceRecord.builder().value("www.example.com").build())
.build();
changeInfo = route53.changeResourceRecordSets(ChangeResourceRecordSetsRequest.builder()
.hostedZoneId(createdZoneId)
.changeBatch(
ChangeBatch.builder().comment(COMMENT).changes(
Change.builder().action(ChangeAction.CREATE)
.resourceRecordSet(
newResourceRecordSet).build()).build()).build()
).changeInfo();
assertValidChangeInfo(changeInfo);
// Clear up the RR Set
changeInfo = route53.changeResourceRecordSets(ChangeResourceRecordSetsRequest.builder()
.hostedZoneId(createdZoneId)
.changeBatch(
ChangeBatch.builder().comment(COMMENT).changes(
Change.builder().action(ChangeAction.DELETE)
.resourceRecordSet(
newResourceRecordSet).build()).build()).build()
).changeInfo();
// Delete Hosted Zone
DeleteHostedZoneResponse deleteHostedZoneResult = route53.deleteHostedZone(DeleteHostedZoneRequest.builder().id(createdZoneId).build());
assertValidChangeInfo(deleteHostedZoneResult.changeInfo());
}
/**
* Asserts that the specified HostedZone is valid and represents the same
* HostedZone that we initially created at the very start of this test.
*
* @param hostedZone The hosted zone to test.
*/
private void assertValidCreatedHostedZone(HostedZone hostedZone) {
assertEquals(CALLER_REFERENCE, hostedZone.callerReference());
assertEquals(ZONE_NAME, hostedZone.name());
assertNotNull(hostedZone.id());
assertEquals(COMMENT, hostedZone.config().comment());
}
/**
* Asserts that the specified DelegationSet is valid.
*
* @param delegationSet The delegation set to test.
*/
private void assertValidDelegationSet(DelegationSet delegationSet) {
assertTrue(delegationSet.nameServers().size() > 0);
for (String server : delegationSet.nameServers()) {
assertNotNull(server);
}
}
/**
* Asserts that the specified ChangeInfo is valid.
*
* @param change The ChangeInfo object to test.
*/
private void assertValidChangeInfo(ChangeInfo change) {
assertNotNull(change.id());
assertNotNull(change.status());
assertNotNull(change.submittedAt());
}
private void assertValidHealthCheck(HealthCheck healthCheck) {
assertNotNull(CALLER_REFERENCE, healthCheck.callerReference());
assertNotNull(healthCheck.id());
assertEquals(PORT_NUM, healthCheck.healthCheckConfig().port().intValue());
assertEquals(TYPE, healthCheck.healthCheckConfig().typeAsString());
assertEquals(IP_ADDRESS, healthCheck.healthCheckConfig().ipAddress());
}
/**
* In the following test, we purposely setting the time offset to trigger a clock skew error.
* The time offset must be fixed and then we validate the global value for time offset has been
* update.
*/
@Test
public void testClockSkew() throws SdkServiceException {
SdkGlobalTime.setGlobalTimeOffset(3600);
Route53Client clockSkewClient = Route53Client.builder()
.region(Region.AWS_GLOBAL)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.build();
clockSkewClient.listHostedZones(ListHostedZonesRequest.builder().build());
assertTrue("Clockskew is fixed!", SdkGlobalTime.getGlobalTimeOffset() < 60);
}
}
| 5,169 |
0 | Create_ds/aws-sdk-java-v2/services/route53/src/main/java/software/amazon/awssdk/services/route53 | Create_ds/aws-sdk-java-v2/services/route53/src/main/java/software/amazon/awssdk/services/route53/internal/Route53IdInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.route53.internal;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.services.route53.model.ActivateKeySigningKeyResponse;
import software.amazon.awssdk.services.route53.model.AliasTarget;
import software.amazon.awssdk.services.route53.model.ChangeInfo;
import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsResponse;
import software.amazon.awssdk.services.route53.model.CreateHealthCheckResponse;
import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse;
import software.amazon.awssdk.services.route53.model.CreateKeySigningKeyResponse;
import software.amazon.awssdk.services.route53.model.CreateReusableDelegationSetResponse;
import software.amazon.awssdk.services.route53.model.DeactivateKeySigningKeyResponse;
import software.amazon.awssdk.services.route53.model.DelegationSet;
import software.amazon.awssdk.services.route53.model.DeleteHostedZoneResponse;
import software.amazon.awssdk.services.route53.model.DeleteKeySigningKeyResponse;
import software.amazon.awssdk.services.route53.model.DisableHostedZoneDnssecResponse;
import software.amazon.awssdk.services.route53.model.EnableHostedZoneDnssecResponse;
import software.amazon.awssdk.services.route53.model.GetChangeResponse;
import software.amazon.awssdk.services.route53.model.GetHealthCheckResponse;
import software.amazon.awssdk.services.route53.model.GetHostedZoneResponse;
import software.amazon.awssdk.services.route53.model.GetReusableDelegationSetResponse;
import software.amazon.awssdk.services.route53.model.HealthCheck;
import software.amazon.awssdk.services.route53.model.HostedZone;
import software.amazon.awssdk.services.route53.model.ListHealthChecksResponse;
import software.amazon.awssdk.services.route53.model.ListHostedZonesResponse;
import software.amazon.awssdk.services.route53.model.ListResourceRecordSetsResponse;
import software.amazon.awssdk.services.route53.model.ListReusableDelegationSetsResponse;
import software.amazon.awssdk.services.route53.model.ResourceRecordSet;
/**
* Route 53 returns a portion of the URL resource path as the ID for a few
* elements, but when the service accepts those IDs, the resource path portion
* cannot be included, otherwise requests fail. This handler removes those
* partial resource path elements from IDs returned by Route 53.
*/
@SdkInternalApi
public final class Route53IdInterceptor implements ExecutionInterceptor {
@Override
public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) {
SdkResponse response = context.response();
if (response instanceof ChangeResourceRecordSetsResponse) {
ChangeResourceRecordSetsResponse result = (ChangeResourceRecordSetsResponse) response;
return result.toBuilder()
.changeInfo(removePrefix(result.changeInfo()))
.build();
} else if (response instanceof CreateHostedZoneResponse) {
CreateHostedZoneResponse result = (CreateHostedZoneResponse) response;
return result.toBuilder()
.changeInfo(removePrefix(result.changeInfo()))
.hostedZone(removePrefix(result.hostedZone()))
.delegationSet(removePrefix(result.delegationSet()))
.build();
} else if (response instanceof DeleteHostedZoneResponse) {
DeleteHostedZoneResponse result = (DeleteHostedZoneResponse) response;
return result.toBuilder()
.changeInfo(removePrefix(result.changeInfo()))
.build();
} else if (response instanceof GetChangeResponse) {
GetChangeResponse result = (GetChangeResponse) response;
return result.toBuilder()
.changeInfo(removePrefix(result.changeInfo()))
.build();
} else if (response instanceof GetHostedZoneResponse) {
GetHostedZoneResponse result = (GetHostedZoneResponse) response;
return result.toBuilder()
.hostedZone(removePrefix(result.hostedZone()))
.delegationSet(removePrefix(result.delegationSet()))
.build();
} else if (response instanceof ListHostedZonesResponse) {
ListHostedZonesResponse result = (ListHostedZonesResponse) response;
return result.toBuilder()
.hostedZones(result.hostedZones().stream()
.map(this::removePrefix)
.collect(Collectors.toList()))
.build();
} else if (response instanceof ListResourceRecordSetsResponse) {
ListResourceRecordSetsResponse result = (ListResourceRecordSetsResponse) response;
return result.toBuilder()
.resourceRecordSets(result.resourceRecordSets().stream()
.map(this::removePrefix)
.collect(Collectors.toList()))
.build();
} else if (response instanceof CreateHealthCheckResponse) {
CreateHealthCheckResponse result = (CreateHealthCheckResponse) response;
return result.toBuilder()
.healthCheck(removePrefix(result.healthCheck()))
.build();
} else if (response instanceof GetHealthCheckResponse) {
GetHealthCheckResponse result = (GetHealthCheckResponse) response;
return result.toBuilder()
.healthCheck(removePrefix(result.healthCheck()))
.build();
} else if (response instanceof ListHealthChecksResponse) {
ListHealthChecksResponse result = (ListHealthChecksResponse) response;
return result.toBuilder()
.healthChecks(result.healthChecks().stream()
.map(this::removePrefix)
.collect(Collectors.toList()))
.build();
} else if (response instanceof CreateReusableDelegationSetResponse) {
CreateReusableDelegationSetResponse result = (CreateReusableDelegationSetResponse) response;
return result.toBuilder()
.delegationSet(removePrefix(result.delegationSet()))
.build();
} else if (response instanceof GetReusableDelegationSetResponse) {
GetReusableDelegationSetResponse result = (GetReusableDelegationSetResponse) response;
return result.toBuilder()
.delegationSet(removePrefix(result.delegationSet()))
.build();
} else if (response instanceof ListReusableDelegationSetsResponse) {
ListReusableDelegationSetsResponse result = (ListReusableDelegationSetsResponse) response;
return result.toBuilder()
.delegationSets(result.delegationSets().stream()
.map(this::removePrefix)
.collect(Collectors.toList()))
.build();
} else if (response instanceof CreateKeySigningKeyResponse) {
CreateKeySigningKeyResponse result = (CreateKeySigningKeyResponse) response;
return result.toBuilder()
.changeInfo(removePrefix(result.changeInfo()))
.build();
} else if (response instanceof DeleteKeySigningKeyResponse) {
DeleteKeySigningKeyResponse result = (DeleteKeySigningKeyResponse) response;
return result.toBuilder()
.changeInfo(removePrefix(result.changeInfo()))
.build();
} else if (response instanceof ActivateKeySigningKeyResponse) {
ActivateKeySigningKeyResponse result = (ActivateKeySigningKeyResponse) response;
return result.toBuilder()
.changeInfo(removePrefix(result.changeInfo()))
.build();
} else if (response instanceof DeactivateKeySigningKeyResponse) {
DeactivateKeySigningKeyResponse result = (DeactivateKeySigningKeyResponse) response;
return result.toBuilder()
.changeInfo(removePrefix(result.changeInfo()))
.build();
} else if (response instanceof EnableHostedZoneDnssecResponse) {
EnableHostedZoneDnssecResponse result = (EnableHostedZoneDnssecResponse) response;
return result.toBuilder()
.changeInfo(removePrefix(result.changeInfo()))
.build();
} else if (response instanceof DisableHostedZoneDnssecResponse) {
DisableHostedZoneDnssecResponse result = (DisableHostedZoneDnssecResponse) response;
return result.toBuilder()
.changeInfo(removePrefix(result.changeInfo()))
.build();
}
return response;
}
private ResourceRecordSet removePrefix(ResourceRecordSet rrset) {
if (rrset == null) {
return null;
}
return rrset.toBuilder()
.aliasTarget(removePrefix(rrset.aliasTarget()))
.healthCheckId(removePrefix(rrset.healthCheckId()))
.setIdentifier(removePrefix(rrset.setIdentifier()))
.build();
}
private AliasTarget removePrefix(AliasTarget aliasTarget) {
if (aliasTarget == null) {
return null;
}
return aliasTarget.toBuilder()
.hostedZoneId(removePrefix(aliasTarget.hostedZoneId()))
.build();
}
private ChangeInfo removePrefix(ChangeInfo changeInfo) {
if (changeInfo == null) {
return null;
}
return changeInfo.toBuilder()
.id(removePrefix(changeInfo.id()))
.build();
}
private HostedZone removePrefix(HostedZone hostedZone) {
if (hostedZone == null) {
return null;
}
return hostedZone.toBuilder()
.id(removePrefix(hostedZone.id()))
.build();
}
private HealthCheck removePrefix(HealthCheck healthCheck) {
if (healthCheck == null) {
return null;
}
return healthCheck.toBuilder()
.id(removePrefix(healthCheck.id()))
.build();
}
private DelegationSet removePrefix(DelegationSet delegationSet) {
if (delegationSet == null) {
return null;
}
return delegationSet.toBuilder()
.id(removePrefix(delegationSet.id()))
.build();
}
private String removePrefix(String s) {
if (s == null) {
return null;
}
int lastIndex = s.lastIndexOf('/');
if (lastIndex > 0) {
return s.substring(lastIndex + 1);
}
return s;
}
}
| 5,170 |
0 | Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services/ec2/Ec2ResponseMetadataIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.ec2;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesResponse;
import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase;
public class Ec2ResponseMetadataIntegrationTest extends AwsIntegrationTestBase {
@Test
public void ec2Response_shouldHaveRequestId() {
Ec2Client ec2Client = Ec2Client.builder()
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.build();
DescribeAvailabilityZonesResponse response = ec2Client.describeAvailabilityZones();
String requestId = response.responseMetadata().requestId();
assertThat(requestId).isNotEqualTo("UNKNOWN");
}
}
| 5,171 |
0 | Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services/ec2/Ec2AutoPaginatorIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.ec2;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import java.util.stream.Stream;
import org.junit.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.model.SpotPrice;
import software.amazon.awssdk.services.ec2.paginators.DescribeSpotPriceHistoryPublisher;
import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase;
public class Ec2AutoPaginatorIntegrationTest extends AwsIntegrationTestBase {
@Test
public void testSpotPriceHistorySyncPaginator() {
Ec2Client ec2Client = Ec2Client.builder()
.region(Region.US_EAST_1)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.build();
Stream<SpotPrice> spotPrices = ec2Client.describeSpotPriceHistoryPaginator(builder -> {
builder.availabilityZone("us-east-1a")
.productDescriptions("Linux/UNIX (Amazon VPC)")
.instanceTypesWithStrings("t1.micro")
.startTime(Instant.now().minusMillis(1));
}).spotPriceHistory().stream();
assertThat(spotPrices.count()).isEqualTo(1);
}
@Test
public void testSpotPriceHistoryAsyncPaginator() {
Ec2AsyncClient ec2Client = Ec2AsyncClient.builder()
.region(Region.US_EAST_1)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.build();
DescribeSpotPriceHistoryPublisher publisher = ec2Client.describeSpotPriceHistoryPaginator(builder -> {
builder.availabilityZone("us-east-1a")
.productDescriptions("Linux/UNIX (Amazon VPC)")
.instanceTypesWithStrings("t1.micro")
.startTime(Instant.now().minusMillis(1));
});
publisher.subscribe(r -> assertThat(r.spotPriceHistory().size()).isEqualTo(1))
.join();
}
}
| 5,172 |
0 | Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services/ec2/transform | Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services/ec2/transform/internal/GeneratePreSignUrlInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.ec2.transform.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.AWS_CREDENTIALS;
import java.net.URI;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.services.ec2.model.CopySnapshotRequest;
@RunWith(MockitoJUnitRunner.class)
public class GeneratePreSignUrlInterceptorTest {
private static final GeneratePreSignUrlInterceptor INTERCEPTOR = new GeneratePreSignUrlInterceptor();
@Mock
private Context.ModifyHttpRequest mockContext;
@Test
public void copySnapshotRequest_httpsProtocolAddedToEndpoint() {
SdkHttpFullRequest request = SdkHttpFullRequest.builder()
.uri(URI.create("https://ec2.us-west-2.amazonaws.com"))
.method(SdkHttpMethod.POST)
.build();
CopySnapshotRequest ec2Request = CopySnapshotRequest.builder()
.sourceRegion("us-west-2")
.destinationRegion("us-east-2")
.build();
when(mockContext.httpRequest()).thenReturn(request);
when(mockContext.request()).thenReturn(ec2Request);
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(AWS_CREDENTIALS, AwsBasicCredentials.create("foo", "bar"));
SdkHttpRequest modifiedRequest = INTERCEPTOR.modifyHttpRequest(mockContext, attrs);
String presignedUrl = modifiedRequest.rawQueryParameters().get("PresignedUrl").get(0);
assertThat(presignedUrl).startsWith("https://");
}
@Test
public void copySnapshotRequest_generatesCorrectPresignedUrl() {
// Expected URL was derived by first making a request to EC2 using
// valid credentials and a KMS encrypted snapshot and verifying that
// the snapshot was copied to the destination region, also encrypted.
// Then the same code was used to make a second request, changing only
// the credentials and snapshot ID.
String expectedPresignedUrl = "https://ec2.us-west-2.amazonaws.com?Action=CopySnapshot" +
"&Version=2016-11-15" +
"&DestinationRegion=us-east-1" +
"&SourceRegion=us-west-2" +
"&SourceSnapshotId=SNAPSHOT_ID" +
"&X-Amz-Algorithm=AWS4-HMAC-SHA256" +
"&X-Amz-Date=20200107T205609Z" +
"&X-Amz-SignedHeaders=host" +
"&X-Amz-Expires=604800" +
"&X-Amz-Credential=akid%2F20200107%2Fus-west-2%2Fec2%2Faws4_request" +
"&X-Amz-Signature=c1f5e34834292a86ff2b46b5e97cebaf2967b09641b4e2e60a382a37d137a03b";
ZoneId utcZone = ZoneId.of("UTC").normalized();
// Same signing date as the one used for the request above
Instant signingInstant = ZonedDateTime.of(2020, 1, 7, 20, 56, 9, 0, utcZone).toInstant();
Clock signingClock = Clock.fixed(signingInstant, utcZone);
GeneratePreSignUrlInterceptor interceptor = new GeneratePreSignUrlInterceptor(signingClock);
// These details don't really affect the test as they're not used in generating the signed URL
SdkHttpFullRequest request = SdkHttpFullRequest.builder()
.uri(URI.create("https://ec2.us-west-2.amazonaws.com"))
.method(SdkHttpMethod.POST)
.build();
CopySnapshotRequest ec2Request = CopySnapshotRequest.builder()
.sourceRegion("us-west-2")
.destinationRegion("us-east-1")
.sourceSnapshotId("SNAPSHOT_ID")
.build();
when(mockContext.httpRequest()).thenReturn(request);
when(mockContext.request()).thenReturn(ec2Request);
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid"));
SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(mockContext, attrs);
String generatedPresignedUrl = modifiedRequest.rawQueryParameters().get("PresignedUrl").get(0);
assertThat(generatedPresignedUrl).isEqualTo(expectedPresignedUrl);
}
}
| 5,173 |
0 | Create_ds/aws-sdk-java-v2/services/ec2/src/main/java/software/amazon/awssdk/services/ec2/transform | Create_ds/aws-sdk-java-v2/services/ec2/src/main/java/software/amazon/awssdk/services/ec2/transform/internal/TimestampFormatInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.ec2.transform.internal;
import java.util.List;
import java.util.regex.Pattern;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.services.ec2.model.DescribeSpotFleetRequestHistoryRequest;
import software.amazon.awssdk.services.ec2.model.RequestSpotFleetRequest;
/**
* A request handler that strips out millisecond precision from requests to
* RequestSpotFleet and DescribeSpotFleetRequestHistory, which don't expect
* timestamps to be so precise.
*/
@SdkInternalApi
public final class TimestampFormatInterceptor implements ExecutionInterceptor {
private static final Pattern PATTERN = Pattern.compile("\\.\\d\\d\\dZ");
private static final String START_TIME = "StartTime";
private static final String VALID_FROM = "SpotFleetRequestConfig.ValidFrom";
private static final String VALID_UNTIL = "SpotFleetRequestConfig.ValidUntil";
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
SdkHttpRequest request = context.httpRequest();
Object original = context.request();
if (original instanceof DescribeSpotFleetRequestHistoryRequest) {
List<String> startTime = request.firstMatchingRawQueryParameters(START_TIME);
if (startTime != null && !startTime.isEmpty()) {
return request.toBuilder()
.putRawQueryParameter(START_TIME, sanitize(startTime.get(0)))
.build();
}
} else if (original instanceof RequestSpotFleetRequest) {
List<String> validFrom = request.firstMatchingRawQueryParameters(VALID_FROM);
List<String> validUntil = request.firstMatchingRawQueryParameters(VALID_UNTIL);
return request.toBuilder().applyMutation(builder -> {
if (validFrom != null && !validFrom.isEmpty()) {
builder.putRawQueryParameter(VALID_FROM, sanitize(validFrom.get(0)));
}
if (validUntil != null && !validUntil.isEmpty()) {
builder.putRawQueryParameter(VALID_UNTIL, sanitize(validUntil.get(0)));
}
}).build();
}
return request;
}
private String sanitize(String input) {
return PATTERN.matcher(input).replaceFirst("Z");
}
}
| 5,174 |
0 | Create_ds/aws-sdk-java-v2/services/ec2/src/main/java/software/amazon/awssdk/services/ec2/transform | Create_ds/aws-sdk-java-v2/services/ec2/src/main/java/software/amazon/awssdk/services/ec2/transform/internal/GeneratePreSignUrlInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.ec2.transform.internal;
import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.AWS_CREDENTIALS;
import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME;
import java.net.URI;
import java.time.Clock;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.signer.Aws4Signer;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.awscore.util.AwsHostNameUtils;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
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.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.protocols.query.AwsEc2ProtocolFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.CopySnapshotRequest;
import software.amazon.awssdk.services.ec2.transform.CopySnapshotRequestMarshaller;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* ExecutionInterceptor that generates a pre-signed URL for copying encrypted snapshots
*/
@SdkInternalApi
public final class GeneratePreSignUrlInterceptor implements ExecutionInterceptor {
private static final URI CUSTOM_ENDPOINT_LOCALHOST = URI.create("http://localhost");
private static final AwsEc2ProtocolFactory PROTOCOL_FACTORY = AwsEc2ProtocolFactory
.builder()
// Need an endpoint to marshall but this will be overwritten in modifyHttpRequest
.clientConfiguration(SdkClientConfiguration.builder()
.option(SdkClientOption.ENDPOINT, CUSTOM_ENDPOINT_LOCALHOST)
.build())
.build();
private static final CopySnapshotRequestMarshaller MARSHALLER = new CopySnapshotRequestMarshaller(PROTOCOL_FACTORY);
private final Clock testClock; // for testing only
public GeneratePreSignUrlInterceptor() {
testClock = null;
}
@SdkTestInternalApi
GeneratePreSignUrlInterceptor(Clock testClock) {
this.testClock = testClock;
}
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
SdkHttpRequest request = context.httpRequest();
SdkRequest originalRequest = context.request();
if (originalRequest instanceof CopySnapshotRequest) {
CopySnapshotRequest originalCopySnapshotRequest = (CopySnapshotRequest) originalRequest;
// Return if presigned url is already specified by the user.
if (originalCopySnapshotRequest.presignedUrl() != null) {
return request;
}
String serviceName = "ec2";
// The source regions where the snapshot currently resides.
String sourceRegion = originalCopySnapshotRequest.sourceRegion();
String sourceSnapshotId = originalCopySnapshotRequest
.sourceSnapshotId();
/*
* The region where the snapshot has to be copied from the source.
* The original copy snap shot request will have the end point set
* as the destination region in the client before calling this
* request.
*/
String destinationRegion = originalCopySnapshotRequest.destinationRegion();
if (destinationRegion == null) {
destinationRegion =
AwsHostNameUtils.parseSigningRegion(request.host(), serviceName)
.orElseThrow(() -> new IllegalArgumentException("Could not determine region for " +
request.host()))
.id();
}
URI endPointSource = createEndpoint(sourceRegion, serviceName);
SdkHttpFullRequest requestForPresigning = generateRequestForPresigning(
sourceSnapshotId, sourceRegion, destinationRegion)
.toBuilder()
.uri(endPointSource)
.method(SdkHttpMethod.GET)
.build();
Aws4Signer signer = Aws4Signer.create();
Aws4PresignerParams signingParams = getPresignerParams(executionAttributes, sourceRegion, serviceName);
SdkHttpFullRequest presignedRequest = signer.presign(requestForPresigning, signingParams);
return request.toBuilder()
.putRawQueryParameter("DestinationRegion", destinationRegion)
.putRawQueryParameter("PresignedUrl", presignedRequest.getUri().toString())
.build();
}
return request;
}
private Aws4PresignerParams getPresignerParams(ExecutionAttributes attributes, String signingRegion, String signingName) {
return Aws4PresignerParams.builder()
.signingRegion(Region.of(signingRegion))
.signingName(signingName)
.awsCredentials(resolveCredentials(attributes))
.signingClockOverride(testClock)
.build();
}
// TODO(sra-identity-and-auth): add test case for SELECTED_AUTH_SCHEME case
private AwsCredentials resolveCredentials(ExecutionAttributes attributes) {
return attributes.getOptionalAttribute(SELECTED_AUTH_SCHEME)
.map(selectedAuthScheme -> selectedAuthScheme.identity())
.map(identityFuture -> CompletableFutureUtils.joinLikeSync(identityFuture))
.filter(identity -> identity instanceof AwsCredentialsIdentity)
.map(identity -> {
AwsCredentialsIdentity awsCredentialsIdentity = (AwsCredentialsIdentity) identity;
return CredentialUtils.toCredentials(awsCredentialsIdentity);
}).orElse(attributes.getAttribute(AWS_CREDENTIALS));
}
/**
* Generates a Request object for the pre-signed URL.
*/
private SdkHttpFullRequest generateRequestForPresigning(String sourceSnapshotId,
String sourceRegion,
String destinationRegion) {
CopySnapshotRequest copySnapshotRequest = CopySnapshotRequest.builder()
.sourceSnapshotId(sourceSnapshotId)
.sourceRegion(sourceRegion)
.destinationRegion(destinationRegion)
.build();
return MARSHALLER.marshall(copySnapshotRequest);
}
private URI createEndpoint(String regionName, String serviceName) {
Region region = Region.of(regionName);
if (region == null) {
throw SdkClientException.builder()
.message("{" + serviceName + ", " + regionName + "} was not "
+ "found in region metadata. Update to latest version of SDK and try again.")
.build();
}
URI endpoint = Ec2Client.serviceMetadata().endpointFor(region);
if (endpoint.getScheme() == null) {
return URI.create("https://" + endpoint);
}
return endpoint;
}
}
| 5,175 |
0 | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/NoIgnoreAnnotationsCheck.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.buildtools.checkstyle;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
/**
* Checks if a class uses the @Ignore annotation. Avoid disabling tests and work to
* resolve issues with the test instead.
*
* For manual tests and exceptional circumstances, use the commentation feature CHECKSTYLE: OFF
* to mark a test as ignored.
*/
public class NoIgnoreAnnotationsCheck extends AbstractCheck {
private static final String IGNORE_ANNOTATION = "Ignore";
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {TokenTypes.CLASS_DEF, TokenTypes.METHOD_DEF};
}
@Override
public void visitToken(DetailAST ast) {
if (!AnnotationUtil.containsAnnotation(ast, IGNORE_ANNOTATION)) {
return;
}
log(ast, "@Ignore annotation is not allowed");
}
}
| 5,176 |
0 | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/SdkIllegalImportCheck.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.buildtools.checkstyle;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
/**
* Checks if a class has illegal imports
*/
public class SdkIllegalImportCheck extends AbstractCheck {
private final List<Pattern> illegalPackagesRegexps = new ArrayList<>();
private final List<String> illegalPackages = new ArrayList<>();
private Pattern classNameToCheck;
private Pattern packageToCheck;
private boolean containsIllegalImport = false;
private boolean classMatched = false;
private boolean classPackageMatched = false;
public void setClassNameToCheck(String classNameToCheck) {
this.classNameToCheck = CommonUtil.createPattern(classNameToCheck);
}
public void setPackageToCheck(String packageToCheckRegexp) {
this.packageToCheck = CommonUtil.createPattern(packageToCheckRegexp);
}
public final void setIllegalPkgs(String... from) {
illegalPackages.clear();
illegalPackages.addAll(Arrays.asList(from));
illegalPackagesRegexps.clear();
for (String illegalPkg : illegalPackages) {
illegalPackagesRegexps.add(CommonUtil.createPattern("^" + illegalPkg));
}
}
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {TokenTypes.PACKAGE_DEF, TokenTypes.CLASS_DEF, TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT};
}
@Override
public void beginTree(DetailAST rootAST) {
containsIllegalImport = false;
classMatched = false;
classPackageMatched = false;
}
@Override
public void finishTree(DetailAST rootAST) {
// Set matched to true if no class package regex provided
if (packageToCheck == null) {
classPackageMatched = true;
}
if (containsIllegalImport && classMatched && classPackageMatched) {
log(rootAST, "Illegal imports found " + illegalPackagesRegexps);
}
}
@Override
public void visitToken(DetailAST ast) {
FullIdent importedPackage = null;
FullIdent classPackage = null;
switch (ast.getType()) {
case TokenTypes.PACKAGE_DEF:
classPackage = FullIdent.createFullIdent(ast.findFirstToken(TokenTypes.DOT));
break;
case TokenTypes.CLASS_DEF:
String className = ast.findFirstToken(TokenTypes.IDENT).getText();
if (classNameToCheck.matcher(className).matches()) {
classMatched = true;
}
break;
case TokenTypes.IMPORT:
importedPackage = FullIdent.createFullIdentBelow(ast);
break;
case TokenTypes.STATIC_IMPORT:
importedPackage = FullIdent.createFullIdent(ast.getFirstChild().getNextSibling());
break;
}
if (packageToCheck != null
&& classPackage != null
&& packageToCheck.matcher(classPackage.getText()).matches()) {
classPackageMatched = true;
}
if (importedPackage!= null && isIllegalImport(importedPackage.getText())) {
containsIllegalImport = true;
}
}
private boolean isIllegalImport(String importText) {
for (Pattern pattern : illegalPackagesRegexps) {
if (pattern.matcher(importText).matches()) {
return true;
}
}
return false;
}
}
| 5,177 |
0 | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/PluralEnumNames.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.buildtools.checkstyle;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* A rule that disallows plurality in enum names (eg. it should be "Property.MY_PROPERTY", not "Properties.MY_PROPERTY"). This
* also applies the validation to "pseudo-enums", classes with public static fields.
*/
public class PluralEnumNames extends AbstractCheck {
private static final List<String> PLURAL_ENDINGS = Arrays.asList("S", "s");
private static final List<String> NON_PLURAL_ENDINGS = Collections.singletonList("Status");
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] { TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF };
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public void visitToken(DetailAST ast) {
String classOrEnumName = ast.findFirstToken(TokenTypes.IDENT).getText();
if (isPlural(classOrEnumName) && isPluralDisallowed(ast)) {
log(ast, "Enum or class name should be singular, not plural (Property.VALUE not Properties.VALUE).");
}
}
private boolean isPlural(String className) {
return PLURAL_ENDINGS.stream().anyMatch(className::endsWith) &&
NON_PLURAL_ENDINGS.stream().noneMatch(className::endsWith);
}
private boolean isPluralDisallowed(DetailAST ast) {
return isEnum(ast) || hasPublicStaticField(ast);
}
private boolean isEnum(DetailAST ast) {
return ast.getType() == TokenTypes.ENUM_DEF;
}
private boolean hasPublicStaticField(DetailAST ast) {
DetailAST classBody = ast.findFirstToken(TokenTypes.OBJBLOCK);
DetailAST maybeVariableDefinition = classBody.getFirstChild();
String className = ast.findFirstToken(TokenTypes.IDENT).getText();
// Filter out util classes
if (className.endsWith("Utils")) {
return false;
}
while (maybeVariableDefinition != null) {
if (maybeVariableDefinition.getType() == TokenTypes.VARIABLE_DEF) {
DetailAST modifiers = maybeVariableDefinition.findFirstToken(TokenTypes.MODIFIERS);
if (modifiers != null && isPublic(modifiers) && isStatic(modifiers)) {
return true;
}
}
maybeVariableDefinition = maybeVariableDefinition.getNextSibling();
}
return false;
}
private boolean isPublic(DetailAST modifiers) {
return modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null;
}
private boolean isStatic(DetailAST modifiers) {
return modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
}
}
| 5,178 |
0 | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/MissingSdkAnnotationCheck.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.buildtools.checkstyle;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
import com.puppycrawl.tools.checkstyle.utils.ScopeUtil;
import java.util.Arrays;
import java.util.List;
/**
* A rule that checks if sdk annotation is missing on any non-test classes. Inner classes are ignored.
*/
public class MissingSdkAnnotationCheck extends AbstractCheck {
private static final List<String> SDK_ANNOTATIONS = Arrays.asList("SdkPublicApi", "SdkInternalApi", "SdkProtectedApi");
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {
TokenTypes.CLASS_DEF,
TokenTypes.INTERFACE_DEF
};
}
@Override
public void visitToken(DetailAST ast) {
if (!ScopeUtil.isOuterMostType(ast) || SDK_ANNOTATIONS.stream().anyMatch(a -> AnnotationUtil.containsAnnotation
(ast, a))) {
return;
}
log(ast, "SDK annotation is missing on this class. eg: @SdkProtectedApi");
}
}
| 5,179 |
0 | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/UnnecessaryFinalOnLocalVariableCheck.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.buildtools.checkstyle;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.ScopeUtil;
/**
* A rule that disallows unnecessary 'final' on local variables
*/
public class UnnecessaryFinalOnLocalVariableCheck extends AbstractCheck {
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] { TokenTypes.VARIABLE_DEF };
}
@Override
public void visitToken(DetailAST ast) {
if (ScopeUtil.isLocalVariableDef(ast) && ast.findFirstToken(TokenTypes.MODIFIERS)
.findFirstToken(TokenTypes.FINAL) != null) {
log(ast, "final should be removed from local variable");
}
}
}
| 5,180 |
0 | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/SdkPublicMethodNameCheck.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.buildtools.checkstyle;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.checks.naming.MethodNameCheck;
import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
/**
* Sdk Method Name check to check only public methods in the classes with {@code @SdkPublicApi} annotation.
*/
public final class SdkPublicMethodNameCheck extends MethodNameCheck {
/**
* {@link Override Override} annotation name.
*/
private static final String OVERRIDE = "Override";
private static final String SDK_PUBLIC_API = "SdkPublicApi";
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {
TokenTypes.METHOD_DEF
};
}
@Override
public void visitToken(DetailAST ast) {
// Get class classDef
DetailAST classDef = ast.getParent().getParent();
try {
if (!AnnotationUtil.containsAnnotation(ast, OVERRIDE)
&& AnnotationUtil.containsAnnotation(classDef, SDK_PUBLIC_API)) {
super.visitToken(ast);
}
} catch (NullPointerException ex) {
//If that method is in an anonymous class, it will throw NPE, ignoring those.
}
}
@Override
protected boolean mustCheckName(DetailAST ast) {
return ast.findFirstToken(TokenTypes.MODIFIERS)
.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null;
}
}
| 5,181 |
0 | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/NonJavaBaseModuleCheck.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.buildtools.checkstyle;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Verify that we're not using classes in rt.jar that aren't exported via the java.base module.
*
* If anything fails this check, it increases our module dependencies. If you absolutely must use one of these
* (e.g. java.beans) because it's fundamental to your functionality, you can suppress this checkstyle rule via
* {@link #setLegalPackages(String...)}, but know that it is not free - you're essentially adding a dependency
* for customers that use the module path.
*/
public class NonJavaBaseModuleCheck extends AbstractCheck {
private static final List<String> ILLEGAL_PACKAGES = Arrays.asList(
"java",
"javax",
"sun",
"apple",
"com.apple",
"com.oracle");
private static final Set<String> LEGAL_PACKAGES = new HashSet<>(Arrays.asList(
"java.io",
"java.lang",
"java.lang.annotation",
"java.lang.invoke",
"java.lang.module",
"java.lang.ref",
"java.lang.reflect",
"java.math",
"java.net",
"java.net.spi",
"java.nio",
"java.nio.channels",
"java.nio.channels.spi",
"java.nio.charset",
"java.nio.charset.spi",
"java.nio.file",
"java.nio.file.attribute",
"java.nio.file.spi",
"java.security",
"java.security.acl",
"java.security.cert",
"java.security.interfaces",
"java.security.spec",
"java.text",
"java.text.spi",
"java.time",
"java.time.chrono",
"java.time.format",
"java.time.temporal",
"java.time.zone",
"java.util",
"java.util.concurrent",
"java.util.concurrent.atomic",
"java.util.concurrent.locks",
"java.util.function",
"java.util.jar",
"java.util.regex",
"java.util.spi",
"java.util.stream",
"java.util.jar",
"java.util.zip",
"javax.crypto",
"javax.crypto.interfaces",
"javax.crypto.spec",
"javax.net",
"javax.net.ssl",
"javax.security.auth",
"javax.security.auth.callback",
"javax.security.auth.login",
"javax.security.auth.spi",
"javax.security.auth.x500",
"javax.security.cert"));
private static final Pattern CLASSNAME_START_PATTERN = Pattern.compile("[A-Z]");
private String currentSdkPackage;
private HashMap<String, Set<String>> additionalLegalPackagesBySdkPackage = new HashMap<>();
/**
* Additional legal packages are formatted as "sdk.package.name:jdk.package.name,sdk.package.name2:jdk.package.name2".
* Multiple SDK packages can be repeated.
*/
public void setLegalPackages(String... legalPackages) {
for (String additionalLegalPackage : legalPackages) {
String[] splitPackage = additionalLegalPackage.split(":", 2);
if (splitPackage.length != 2) {
throw new IllegalArgumentException("Invalid legal package definition '" + additionalLegalPackage + "'. Expected"
+ " format is sdk.package.name:jdk.package.name");
}
this.additionalLegalPackagesBySdkPackage.computeIfAbsent(splitPackage[0], k -> new HashSet<>())
.add(splitPackage[1]);
}
}
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] { TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT, TokenTypes.PACKAGE_DEF };
}
@Override
public void visitToken(DetailAST ast) {
if (ast.getType() == TokenTypes.PACKAGE_DEF) {
handlePackageDefToken(ast);
return;
}
handleImportToken(ast);
}
private void handlePackageDefToken(DetailAST ast) {
this.currentSdkPackage = FullIdent.createFullIdent(ast.getLastChild().getPreviousSibling()).getText();
}
private void handleImportToken(DetailAST ast) {
FullIdent importIdentifier;
if (ast.getType() == TokenTypes.IMPORT) {
importIdentifier = FullIdent.createFullIdentBelow(ast);
} else {
importIdentifier = FullIdent.createFullIdent(ast.getFirstChild().getNextSibling());
}
String importText = importIdentifier.getText();
if (isIllegalImport(importText) && !isLegalImport(importText)) {
log(ast, "Import '" + importText + "' uses a JDK class that is not in java.base. This essentially adds an "
+ "additional module dependency. Don't suppress this rule unless it's absolutely required, and only "
+ "suppress the specific package you need via checkstyle.xml instead of suppressing the entire rule.");
}
}
private boolean isIllegalImport(String importText) {
for (String illegalPackage : ILLEGAL_PACKAGES) {
if (importText.startsWith(illegalPackage + ".")) {
return true;
}
}
return false;
}
private boolean isLegalImport(String importText) {
String importPackageWithTrailingDot = CLASSNAME_START_PATTERN.split(importText, 2)[0];
String importPackage = importText.substring(0, importPackageWithTrailingDot.length() - 1);
if (LEGAL_PACKAGES.contains(importPackage)) {
return true;
}
if (additionalLegalPackagesBySdkPackage.entrySet()
.stream()
.anyMatch(e -> currentSdkPackage.startsWith(e.getKey()) &&
e.getValue().contains(importPackage))) {
return true;
}
return false;
}
}
| 5,182 |
0 | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/findbugs/DisallowMethodCall.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.buildtools.findbugs;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.ba.SignatureParser;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
import edu.umd.cs.findbugs.classfile.MethodDescriptor;
import java.util.AbstractMap.SimpleEntry;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.bcel.Const;
/**
* Blocks usage of disallowed methods in the SDK.
*/
public class DisallowMethodCall extends OpcodeStackDetector {
private static final Set<Entry<String, String>> PROHIBITED_METHODS = new HashSet<>();
private final BugReporter bugReporter;
static {
PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpHeaders", "headers"));
PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpResponse", "headers"));
PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpRequest", "headers"));
PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullRequest", "headers"));
PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullResponse", "headers"));
PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullRequest$Builder", "headers"));
PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullResponse$Builder", "headers"));
PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpRequest", "rawQueryParameters"));
PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullRequest", "rawQueryParameters"));
PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullRequest$Builder", "rawQueryParameters"));
}
public DisallowMethodCall(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
@Override
public void sawOpcode(int code) {
switch (code) {
case Const.INVOKEVIRTUAL:
case Const.INVOKESPECIAL:
case Const.INVOKESTATIC:
case Const.INVOKEINTERFACE:
handleMethodCall(code);
return;
default:
// Ignore - not a method call.
}
}
private void handleMethodCall(int code) {
MethodDescriptor method = getMethodDescriptorOperand();
SignatureParser signature = new SignatureParser(method.getSignature());
Entry<String, String> calledMethod = new SimpleEntry<>(method.getSlashedClassName(), method.getName());
if (PROHIBITED_METHODS.contains(calledMethod) && signature.getNumParameters() == 0) {
bugReporter.reportBug(new BugInstance(this, "SDK_BAD_METHOD_CALL", NORMAL_PRIORITY)
.addClassAndMethod(this)
.addSourceLine(this, getPC()));
}
}
}
| 5,183 |
0 | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools | Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/findbugs/ToBuilderIsCorrect.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.buildtools.findbugs;
import static java.util.Collections.emptyList;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
import edu.umd.cs.findbugs.classfile.analysis.AnnotationValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.bcel.Const;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
/**
* A FindBugs/SpotBugs rule for verifying that implementations of
* software.amazon.awssdk.utils.builder.ToCopyableBuilder and CopyableBuilder are correct.
*/
public class ToBuilderIsCorrect extends OpcodeStackDetector {
private final BugReporter bugReporter;
/**
* All implementations of CopyableBuilder encountered in the module.
*/
private final Map<String, JavaClass> builders = new HashMap<>();
/**
* All implementations of ToCopyableBuilder encountered in the module.
*/
private final Map<String, JavaClass> buildables = new HashMap<>();
/**
* The fields in CopyableBuilder implementations that are expected to be copied.
*
* Keys: The builder FQCN, Values: the fields in the builder
*/
private final Map<String, List<String>> builderFields = new HashMap<>();
/**
* The fields in CopyableBuilder implementations that are not expected to be copied. These are configured on the toBuilder
* method using the @ToBuilderIgnoreField annotation.
*
* Keys: The builder FQCN, Values: the fields to ignore
*/
private final Map<String, List<String>> ignoredFields = new HashMap<>();
/**
* The implementations of CopyableBuilder that are not validated. These are determined automatically, e.g. because the
* class inherits its toBuilder implementation from a parent class.
*/
private final Set<String> ignoredBuildables = new HashSet<>();
/**
* Which fields are modified in a builder's constructor. This is used when a buildable uses a builder's constructor to copy
* over fields.
*
* Key 1: The builder FQCN, Key 2: The constructor signature, Values: the fields modified in the constructor
*/
private final Map<String, Map<String, List<String>>> builderConstructorModifiedFields = new HashMap<>();
/**
* Which fields are modified in a buildable's toBuilder method. This is used when a buildable invokes methods on the
* builder to copy over fields.
*
* Key 1: The buildable FQCN, Key 2: the invoked builder FQCN, Values: the fields modified in the
* toBuilder
*/
private final Map<String, Map<String, List<String>>> toBuilderModifiedFields = new HashMap<>();
/**
* Which constructors are invoked from a buildable's toBuilder method. This is used when a buildable uses a builder's
* constructor to copy over fields.
*
* Key 1: The buildable FQCN, Key 2: the invoked builder FQCN, Values: the signature of the constructor invoked by the
* toBuilder method.
*/
private final Map<String, Map<String, String>> constructorsInvokedFromToBuilder = new HashMap<>();
/**
* Which builder constructors reference which other builder constructors. This is used when a buildable uses a builder's
* constructor to copy over fields, and that constructor delegates some copying to another internal constructor.
*
* Key 1: The builder FQCN, Key 2: the invoking constructor signature, Value: the target constructor signature.
*/
private final Map<String, Map<String, String>> crossConstructorReferences = new HashMap<>();
/**
* Which classes or interfaces a builder extends. This is used to determine what builder is being modified when it is
* invoked virtually from a toBuilder implementation.
*
* Key: The builder FQCN, Value: the FQCN parent classes and interfaces (including transitive)
*/
private final Map<String, Set<String>> builderParents = new HashMap<>();
/**
* Whether the current class being assessed is a builder.
*/
private boolean isBuilder = false;
/**
* Whether the current class being assessed is a buildable.
*/
private boolean isBuildable = false;
/**
* Whether the current method being assessed is a builder's constructor.
*/
private boolean inBuilderConstructor = false;
/**
* Whether the current method being assessed is a buildable's toBuilder.
*/
private boolean inBuildableToBuilder = false;
public ToBuilderIsCorrect(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
/**
* Determine whether we should visit the provided class. We only visit builders and buildables.
*/
@Override
public boolean shouldVisit(JavaClass obj) {
isBuilder = false;
isBuildable = false;
inBuilderConstructor = false;
inBuildableToBuilder = false;
try {
if (obj.isInterface()) {
return false;
}
JavaClass[] parentInterfaces = obj.getAllInterfaces();
Set<String> parents = Stream.concat(Arrays.stream(parentInterfaces), Arrays.stream(obj.getSuperClasses()))
.map(JavaClass::getClassName)
.collect(Collectors.toSet());
for (JavaClass i : parentInterfaces) {
if (i.getClassName().equals("software.amazon.awssdk.utils.builder.CopyableBuilder")) {
builders.put(obj.getClassName(), obj);
builderParents.put(obj.getClassName(), parents);
isBuilder = true;
}
if (i.getClassName().equals("software.amazon.awssdk.utils.builder.ToCopyableBuilder")) {
buildables.put(obj.getClassName(), obj);
isBuildable = true;
}
}
if (isBuildable && isBuilder) {
System.err.println(obj.getClassName() + " implements both CopyableBuilder and ToCopyableBuilder.");
bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY)
.addClass(obj));
visitAfter(obj);
return false;
}
return isBuildable || isBuilder;
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
@Override
public void visit(Field obj) {
if (isBuilder && !obj.isStatic()) {
builderFields.computeIfAbsent(getDottedClassName(), c -> new ArrayList<>()).add(obj.getName());
}
}
@Override
public void visit(Method method) {
if (isBuilder && method.getName().equals(Const.CONSTRUCTOR_NAME)) {
// This is a builder constructor
builderConstructorModifiedFields.computeIfAbsent(getDottedClassName(), n1 -> new HashMap<>())
.computeIfAbsent(method.getSignature(), n -> new ArrayList<>());
crossConstructorReferences.computeIfAbsent(getDottedClassName(), n1 -> new HashMap<>());
inBuildableToBuilder = false;
inBuilderConstructor = true;
if (method.isPublic()) {
System.err.println(getDottedClassName() + getMethodSig() + " must not be public.");
bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY)
.addClassAndMethod(getXMethod()));
}
} else if (isBuildable && method.getName().equals("toBuilder") && method.getSignature().startsWith("()")) {
// This is a buildable toBuilder
constructorsInvokedFromToBuilder.computeIfAbsent(getDottedClassName(), n -> new HashMap<>());
toBuilderModifiedFields.computeIfAbsent(getDottedClassName(), n -> new HashMap<>());
inBuildableToBuilder = true;
inBuilderConstructor = false;
registerIgnoredFields();
} else {
inBuildableToBuilder = false;
inBuilderConstructor = false;
}
}
/**
* Register ignored fields specified in the current method's ToBuilderIgnoreField annotation.
*/
private void registerIgnoredFields() {
for (AnnotationValue annotation : getXMethod().getAnnotations()) {
if (annotation.getAnnotationClass()
.getDottedClassName()
.equals("software.amazon.awssdk.annotations.ToBuilderIgnoreField")) {
Object value = annotation.getValue("value");
for (Object ignoredField : (Object[]) value) {
ignoredFields.computeIfAbsent(getDottedClassName(), n -> new ArrayList<>())
.add((String) ignoredField);
}
}
}
}
@Override
public void sawOpcode(int seen) {
if (inBuilderConstructor) {
sawOpCodeInBuilderConstructor(seen);
} else if (inBuildableToBuilder) {
sawOpCodeInBuildableToBuilder(seen);
}
}
private void sawOpCodeInBuilderConstructor(int seen) {
// In builder constructor
if (seen == Const.PUTFIELD && !isEmptyAllocation()) {
// Writing directly to a field, but not with an empty value that was just constructed (likely empty maps, lists,
// etc.)
addConstructorModifiedField(getXFieldOperand().getName());
} else if (seen == Const.INVOKEVIRTUAL || seen == Const.INVOKEINTERFACE) {
XField field = getStack().getStackItem(1).getXField();
if (field != null && field.getClassName().equals(getDottedClassName())) {
// We're invoking a method on one of our fields. We just assume that counts as updating it (e.g. Map.putAll).
addConstructorModifiedField(field.getName());
}
} else if (seen == Const.INVOKESPECIAL &&
getDottedClassName().equals(getDottedClassConstantOperand()) &&
getNameConstantOperand().equals(Const.CONSTRUCTOR_NAME)) {
// Invoking another constructor on this builder
crossConstructorReferences.get(getDottedClassName())
.put(getXMethod().getSignature(), getSigConstantOperand());
}
}
/**
* Return true if the value on the top of the stack is a newly-allocated object, created from a zero-arg method. If so, we
* assume it's just allocating something empty (e.g. new HashMap(), new ArrayList(), etc.)
*/
private boolean isEmptyAllocation() {
OpcodeStack.Item topOfStack = getStack().getStackItem(0);
XMethod returnValueOf = topOfStack.getReturnValueOf();
if (returnValueOf == null) {
return false;
}
return topOfStack.isNewlyAllocated() && returnValueOf.getSignature().startsWith("()");
}
private void addConstructorModifiedField(String field) {
builderConstructorModifiedFields.get(getDottedClassName())
.get(getXMethod().getSignature())
.add(field);
}
private void sawOpCodeInBuildableToBuilder(int seen) {
// In toBuilder method
if (seen == Const.INVOKESPECIAL && getNameConstantOperand().equals(Const.CONSTRUCTOR_NAME)) {
// Invoking a constructor, possibly on a builder
constructorsInvokedFromToBuilder.get(getDottedClassName())
.put(getDottedClassConstantOperand(), getSigConstantOperand());
} else if (seen == Const.INVOKEVIRTUAL || seen == Const.INVOKEINTERFACE) {
// Invoking a method, possibly on a builder
toBuilderModifiedFields.get(getDottedClassName())
.computeIfAbsent(getDottedClassConstantOperand(), n -> new ArrayList<>())
.add(getNameConstantOperand());
} else if (seen == Const.INVOKESPECIAL && getNameConstantOperand().equals("toBuilder")) {
// Invoking another toBuilder. We make an assumption that it's doing the work instead of this buildable.
ignoredBuildables.add(getDottedClassName());
}
}
@Override
public void report() {
buildables.forEach((buildableClassName, buildableClass) -> {
// Find how toBuilder invokes the builder
if (ignoredBuildables.contains(buildableClassName)) {
// Skip validating this buildable because it delegates its toBuilder call to another buildable.
} else if (invokesBuilderViaMethods(buildableClassName)) {
validateBuilderViaMethods(buildableClassName, buildableClass);
} else if (invokesBuilderViaConstructor(buildableClassName)) {
validateBuilderConstructor(buildableClassName, buildableClass);
} else {
System.err.println(buildableClassName + ".toBuilder() does not invoke a constructor or method on a builder. A "
+ "toBuilder() method must either invoke a builder constructor or call builder() and "
+ "configure the fields on the builder.");
bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY)
.addClass(buildableClass));
}
});
}
private boolean invokesBuilderViaConstructor(String buildableClassName) {
Map<String, String> constructors = constructorsInvokedFromToBuilder.get(buildableClassName);
if (constructors == null) {
return false;
}
return constructors.keySet().stream().anyMatch(builders::containsKey);
}
private boolean invokesBuilderViaMethods(String buildableClassName) {
Map<String, List<String>> methods = toBuilderModifiedFields.get(buildableClassName);
if (methods == null) {
return false;
}
return methods.keySet()
.stream()
.anyMatch(builderClass -> builders.containsKey(builderClass) ||
builderParents.values()
.stream()
.anyMatch(parents -> parents.contains(builderClass)));
}
private void validateBuilderConstructor(String buildableClassName, JavaClass buildableClass) {
Map<String, String> invokedConstructors = constructorsInvokedFromToBuilder.get(buildableClassName);
// Remove and ignore any non-builder constructors the buildable invoked.
invokedConstructors.keySet().removeIf(builderClass -> !builders.containsKey(builderClass));
if (invokedConstructors.size() > 1) {
System.err.println(buildableClassName + ".toBuilder() invokes multiple builder constructors: " + invokedConstructors);
bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY)
.addClass(buildableClass));
}
// Find the constructor implementation that we actually invoked, along with all of the constructors that were
// transitively called
Map.Entry<String, String> invokedConstructor = invokedConstructors.entrySet().iterator().next();
String builder = invokedConstructor.getKey();
String calledConstructor = invokedConstructor.getValue();
List<String> allInvokedConstructors = getAllInvokedConstructors(builder, calledConstructor);
if (!builders.containsKey(builder)) {
System.err.println(buildableClassName + ".toBuilder() invokes the constructor of an unknown type: " + builder);
bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY)
.addClass(buildableClass));
}
// Find which fields we modified in those constructors
Set<String> builderFieldsForBuilder = new HashSet<>(builderFields.getOrDefault(builder, new ArrayList<>()));
Map<String, List<String>> allConstructors = builderConstructorModifiedFields.get(builder);
allInvokedConstructors.forEach(constructorSignature -> {
List<String> modifiedFields = allConstructors.get(constructorSignature);
if (modifiedFields == null) {
System.err.println(buildableClassName + ".toBuilder() invokes an unknown constructor: " + builder +
constructorSignature);
bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY)
.addClass(builders.get(builder)));
return;
}
modifiedFields.forEach(builderFieldsForBuilder::remove);
});
// Subtract ignored fields
ignoredFields.getOrDefault(buildableClassName, emptyList()).forEach(builderFieldsForBuilder::remove);
// Anything left is unmodified
if (!builderFieldsForBuilder.isEmpty()) {
System.err.println(buildableClassName + ".toBuilder() does not update all of the builder's fields. "
+ "Missing fields: " + builderFieldsForBuilder + ". This check does not currently "
+ "consider transitive method calls. If this is a false positive, you can ignore this field by "
+ "annotating the toBuilder method with @ToBuilderIgnoreField and specifying the fields to "
+ "ignore.");
bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY)
.addClass(builders.get(builder)));
}
}
private List<String> getAllInvokedConstructors(String builder, String signature) {
List<String> result = new ArrayList<>();
while (signature != null) {
result.add(signature);
signature = crossConstructorReferences.get(builder).get(signature);
}
return result;
}
private void validateBuilderViaMethods(String buildableClassName, JavaClass buildableClass) {
// Find which methods were invoked in the builder
Map<String, List<String>> invokedMethodsByClass = toBuilderModifiedFields.get(buildableClassName);
invokedMethodsByClass.forEach((invokedClass, invokedMethods) -> {
// Create a best-guess on what buildable implementation we're actually working with (based on the parent interface
// we might be working with)
String concreteClass = resolveParentToConcrete(invokedClass);
if (builders.containsKey(concreteClass)) {
// We're invoking these methods on a known builder. Assume the method name matches the field name and validate
// based on that.
List<String> concreteClassBuilderFields = builderFields.getOrDefault(concreteClass, new ArrayList<>());
Set<String> builderFieldsForBuilder = new HashSet<>(concreteClassBuilderFields);
invokedMethods.forEach(builderFieldsForBuilder::remove);
ignoredFields.getOrDefault(buildableClassName, emptyList()).forEach(builderFieldsForBuilder::remove);
if (!builderFieldsForBuilder.isEmpty()) {
System.err.println(buildableClassName + ".toBuilder() does not update all of the builder's fields. "
+ "Missing fields: " + builderFieldsForBuilder + ". This check does not currently "
+ "consider transitive method calls.");
bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY)
.addClass(buildableClass));
}
}
});
}
private String resolveParentToConcrete(String parent) {
return builderParents.entrySet()
.stream()
.filter(parents -> parents.getValue().contains(parent))
.map(parents -> parents.getKey())
.findAny()
.orElse(parent);
}
}
| 5,184 |
0 | Create_ds/commons-pool | Create_ds/commons-pool/doc/ReaderUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file is one of the source files for the examples contained in
* /src/site/xdoc/examples.xml
* It is not intended to be included in a source release.
*/
import java.io.IOException;
import java.io.Reader;
import org.apache.commons.pool3.ObjectPool;
/**
* Maintains a pool of StringBuffers used to dump contents of Readers.
*/
public class ReaderUtil {
private ObjectPool<StringBuffer> pool;
public ReaderUtil(ObjectPool<StringBuffer> pool) {
this.pool = pool;
}
/**
* Dumps the contents of the {@link Reader} to a String, closing the {@link Reader} when done.
*/
public String readToString(Reader in)
throws IOException {
StringBuffer buf = null;
try {
buf = pool.borrowObject();
for (int c = in.read(); c != -1; c = in.read()) {
buf.append((char) c);
}
return buf.toString();
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Unable to borrow buffer from pool" + e.toString());
} finally {
try {
in.close();
} catch (Exception e) {
// ignored
}
try {
if (null != buf) {
pool.returnObject(buf);
}
} catch (Exception e) {
// ignored
}
}
}
}
| 5,185 |
0 | Create_ds/commons-pool | Create_ds/commons-pool/doc/ReaderUtilClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file is one of the source files for the examples contained in
* /src/site/xdoc/examples.xml
* It is not intended to be included in a source release.
*/
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import org.apache.commons.pool3.impl.GenericObjectPool;
/**
* Instantiates and uses a ReaderUtil. The GenericObjectPool supplied to the constructor will have
* default configuration properties.
*/
public class ReaderUtilClient {
public static void main(String[] args) {
ReaderUtil readerUtil = new ReaderUtil(new GenericObjectPool<StringBuffer>(new StringBufferFactory()));
Reader reader = new StringReader("foo");
try {
System.out.println(readerUtil.readToString(reader));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 5,186 |
0 | Create_ds/commons-pool | Create_ds/commons-pool/doc/StringBufferFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file is one of the source files for the examples contained in
* /src/site/xdoc/examples.xml
* It is not intended to be included in a source release.
*/
import org.apache.commons.pool3.BasePooledObjectFactory;
import org.apache.commons.pool3.PooledObject;
import org.apache.commons.pool3.impl.DefaultPooledObject;
/**
* Example PooledObjectFactory for pooled StringBuffers.
*/
public class StringBufferFactory
extends BasePooledObjectFactory<StringBuffer> {
@Override
public StringBuffer create() {
return new StringBuffer();
}
/**
* Use the default PooledObject implementation.
*/
@Override
public PooledObject<StringBuffer> wrap(StringBuffer buffer) {
return new DefaultPooledObject<StringBuffer>(buffer);
}
/**
* When an object is returned to the pool, clear the buffer.
*/
@Override
public void passivateObject(PooledObject<StringBuffer> pooledObject) {
pooledObject.getObject().setLength(0);
}
// for all other methods, the no-op implementation
// in BasePooledObjectFactory will suffice
}
| 5,187 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/Waiter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.ThreadUtils;
/**
* <p>Object created by {@link WaiterFactory}. Maintains active / valid state,
* last passivated and idle times. Waits with configurable latency when
* {@link #doWait()} method is called.</p>
*
* <p>This class is *not* threadsafe.</p>
*/
public class Waiter {
private static final AtomicInteger instanceCount = new AtomicInteger();
public static void sleepQuietly(final long millis) {
ThreadUtils.sleepQuietly(Duration.ofMillis(millis));
}
private boolean active;
private boolean valid;
private long latency;
private long lastPassivatedMillis;
private long lastIdleTimeMillis;
private long passivationCount;
private long validationCount;
private final int id = instanceCount.getAndIncrement();
public Waiter(final boolean active, final boolean valid, final long latency) {
this.active = active;
this.valid = valid;
this.latency = latency;
this.lastPassivatedMillis = System.currentTimeMillis();
}
/**
* Wait for {@link #getLatency()} milliseconds.
*/
public void doWait() {
sleepQuietly(latency);
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof Waiter)) {
return false;
}
return obj.hashCode() == id;
}
/**
* <p>Returns the last idle time for this instance in ms.</p>
*
* <p>When an instance is created, and each subsequent time it is passivated,
* the {@link #getLastPassivatedMillis() lastPassivated} property is updated with the
* current time. When the next activation occurs, {@code lastIdleTime} is
* updated with the elapsed time since passivation.<p>
*
* @return last idle time
*/
public long getLastIdleTimeMillis() {
return lastIdleTimeMillis;
}
/**
* <p>Returns the system time of this instance's last passivation.</p>
*
* <p>When an instance is created, this field is initialized to the system time.</p>
*
* @return time of last passivation
*/
public long getLastPassivatedMillis() {
return lastPassivatedMillis;
}
public long getLatency() {
return latency;
}
/**
* @return how many times this instance has been passivated
*/
public long getPassivationCount() {
return passivationCount;
}
/**
* @return how many times this instance has been validated
*/
public long getValidationCount() {
return validationCount;
}
@Override
public int hashCode() {
return id;
}
/**
* Whether or not the instance is active.
*
* @return true if the last lifecycle event for this instance was activation.
*/
public boolean isActive() {
return active;
}
public boolean isValid() {
validationCount++;
return valid;
}
/**
* <p>Sets the active state and updates {@link #getLastIdleTimeMillis() lastIdleTime}
* or {@link #getLastPassivatedMillis() lastPassivated} as appropriate.</p>
*
* <p>If the active state is changing from inactive to active, lastIdleTime
* is updated with the current time minus lastPassivated. If the state is
* changing from active to inactive, lastPassivated is updated with the
* current time.</p>
*
* <p>{@link WaiterFactory#activateObject(PooledObject)} and
* {@link WaiterFactory#passivateObject(PooledObject)} invoke this method on
* their actual parameter, passing {@code true} and {@code false},
* respectively.</p>
*
* @param active new active state
*/
public void setActive(final boolean active) {
final boolean activeState = this.active;
if (activeState == active) {
return;
}
this.active = active;
final long currentTimeMillis = System.currentTimeMillis();
if (active) { // activating
lastIdleTimeMillis = currentTimeMillis - lastPassivatedMillis;
} else { // passivating
lastPassivatedMillis = currentTimeMillis;
passivationCount++;
}
}
public void setLatency(final long latency) {
this.latency = latency;
}
public void setValid(final boolean valid) {
this.valid = valid;
}
@Override
public String toString() {
final StringBuilder buff = new StringBuilder();
buff.append("ID = " + id + '\n');
buff.append("valid = " + valid + '\n');
buff.append("active = " + active + '\n');
buff.append("lastPassivated = " + lastPassivatedMillis + '\n');
buff.append("lastIdleTimeMs = " + lastIdleTimeMillis + '\n');
buff.append("latency = " + latency + '\n');
return buff.toString();
}
}
| 5,188 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/AbstractTestKeyedObjectPool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import org.apache.commons.pool3.impl.DefaultPooledObject;
import org.apache.commons.pool3.impl.GenericKeyedObjectPool;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
/**
* Abstract test case for {@link ObjectPool} implementations.
*/
public abstract class AbstractTestKeyedObjectPool {
protected static class FailingKeyedPooledObjectFactory implements KeyedPooledObjectFactory<Object, Object, PrivateException> {
private final List<MethodCall> methodCalls = new ArrayList<>();
private int count;
private boolean makeObjectFail;
private boolean activateObjectFail;
private boolean validateObjectFail;
private boolean passivateObjectFail;
private boolean destroyObjectFail;
public FailingKeyedPooledObjectFactory() {
}
@Override
public void activateObject(final Object key, final PooledObject<Object> obj) {
methodCalls.add(new MethodCall("activateObject", key, obj.getObject()));
if (activateObjectFail) {
throw new PrivateException("activateObject");
}
}
@Override
public void destroyObject(final Object key, final PooledObject<Object> obj) {
methodCalls.add(new MethodCall("destroyObject", key, obj.getObject()));
if (destroyObjectFail) {
throw new PrivateException("destroyObject");
}
}
public int getCurrentCount() {
return count;
}
public List<MethodCall> getMethodCalls() {
return methodCalls;
}
public boolean isActivateObjectFail() {
return activateObjectFail;
}
public boolean isDestroyObjectFail() {
return destroyObjectFail;
}
public boolean isMakeObjectFail() {
return makeObjectFail;
}
public boolean isPassivateObjectFail() {
return passivateObjectFail;
}
public boolean isValidateObjectFail() {
return validateObjectFail;
}
@Override
public PooledObject<Object> makeObject(final Object key) {
final MethodCall call = new MethodCall("makeObject", key);
methodCalls.add(call);
final int originalCount = this.count++;
if (makeObjectFail) {
throw new PrivateException("makeObject");
}
// Deliberate choice to create new object in case future unit test
// checks for a specific object
final Integer obj = Integer.valueOf(originalCount);
call.setReturned(obj);
return new DefaultPooledObject<>(obj);
}
@Override
public void passivateObject(final Object key, final PooledObject<Object> obj) {
methodCalls.add(new MethodCall("passivateObject", key, obj.getObject()));
if (passivateObjectFail) {
throw new PrivateException("passivateObject");
}
}
public void reset() {
count = 0;
getMethodCalls().clear();
setMakeObjectFail(false);
setActivateObjectFail(false);
setValidateObjectFail(false);
setPassivateObjectFail(false);
setDestroyObjectFail(false);
}
public void setActivateObjectFail(final boolean activateObjectFail) {
this.activateObjectFail = activateObjectFail;
}
public void setCurrentCount(final int count) {
this.count = count;
}
public void setDestroyObjectFail(final boolean destroyObjectFail) {
this.destroyObjectFail = destroyObjectFail;
}
public void setMakeObjectFail(final boolean makeObjectFail) {
this.makeObjectFail = makeObjectFail;
}
public void setPassivateObjectFail(final boolean passivateObjectFail) {
this.passivateObjectFail = passivateObjectFail;
}
public void setValidateObjectFail(final boolean validateObjectFail) {
this.validateObjectFail = validateObjectFail;
}
@Override
public boolean validateObject(final Object key, final PooledObject<Object> obj) {
final MethodCall call = new MethodCall("validateObject", key, obj.getObject());
methodCalls.add(call);
if (validateObjectFail) {
throw new PrivateException("validateObject");
}
final boolean r = true;
call.returned(Boolean.valueOf(r));
return r;
}
}
private static final class TestFactory extends BaseKeyedPooledObjectFactory<Object, Object, RuntimeException> {
@Override
public Object create(final Object key) {
return new Object();
}
@Override
public PooledObject<Object> wrap(final Object value) {
return new DefaultPooledObject<>(value);
}
}
protected static final String KEY = "key";
private KeyedObjectPool<Object, Object, RuntimeException> pool;
// Deliberate choice to create a new object in case future unit tests check
// for a specific object.
private final Integer ZERO = Integer.valueOf(0);
private final Integer ONE = Integer.valueOf(1);
private void clear(final FailingKeyedPooledObjectFactory factory, final List<MethodCall> expectedMethods) {
factory.getMethodCalls().clear();
expectedMethods.clear();
}
/**
* Return what we expect to be the n<sup>th</sup>
* object (zero indexed) created by the pool
* for the given key.
* @param key Key for the object to be obtained
* @param n index of the object to be obtained
*
* @return the requested object
*/
protected abstract Object getNthObject(Object key, int n);
protected abstract boolean isFifo();
protected abstract boolean isLifo();
/**
* Creates an {@link KeyedObjectPool} instance
* that can contain at least <i>minCapacity</i>
* idle and active objects, or
* throw {@link IllegalArgumentException}
* if such a pool cannot be created.
* @param minCapacity Minimum capacity of the pool to create
*
* @return the newly created keyed object pool
*/
protected abstract <E extends Exception> KeyedObjectPool<Object, Object, E> makeEmptyPool(int minCapacity);
/**
* Creates an {@code KeyedObjectPool} with the specified factory.
* The pool should be in a default configuration and conform to the expected
* behaviors described in {@link KeyedObjectPool}.
* Generally speaking there should be no limits on the various object counts.
*
* @param <E> The type of exception thrown by the pool
* @param factory Factory to use to associate with the pool
* @return The newly created empty pool
*/
protected abstract <E extends Exception> KeyedObjectPool<Object, Object, E> makeEmptyPool(KeyedPooledObjectFactory<Object, Object, E> factory);
protected abstract Object makeKey(int n);
private <E extends Exception> void reset(final KeyedObjectPool<Object, Object, E> pool, final FailingKeyedPooledObjectFactory factory,
final List<MethodCall> expectedMethods) throws E {
pool.clear();
clear(factory, expectedMethods);
factory.reset();
}
@AfterEach
public void tearDown() {
pool = null;
}
@Test
public void testBaseAddObject() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException uoe) {
return; // skip this test if unsupported
}
final Object key = makeKey(0);
try {
assertEquals(0,pool.getNumIdle());
assertEquals(0,pool.getNumActive());
assertEquals(0,pool.getNumIdle(key));
assertEquals(0,pool.getNumActive(key));
pool.addObject(key);
assertEquals(1,pool.getNumIdle());
assertEquals(0,pool.getNumActive());
assertEquals(1,pool.getNumIdle(key));
assertEquals(0,pool.getNumActive(key));
final Object obj = pool.borrowObject(key);
assertEquals(getNthObject(key,0),obj);
assertEquals(0,pool.getNumIdle());
assertEquals(1,pool.getNumActive());
assertEquals(0,pool.getNumIdle(key));
assertEquals(1,pool.getNumActive(key));
pool.returnObject(key,obj);
assertEquals(1,pool.getNumIdle());
assertEquals(0,pool.getNumActive());
assertEquals(1,pool.getNumIdle(key));
assertEquals(0,pool.getNumActive(key));
} catch (final UnsupportedOperationException e) {
return; // skip this test if one of those calls is unsupported
} finally {
pool.close();
}
}
@Test
public void testBaseBorrow() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException uoe) {
return; // skip this test if unsupported
}
final Object keya = makeKey(0);
final Object keyb = makeKey(1);
assertEquals(getNthObject(keya,0),pool.borrowObject(keya),"1");
assertEquals(getNthObject(keyb,0),pool.borrowObject(keyb),"2");
assertEquals(getNthObject(keyb,1),pool.borrowObject(keyb),"3");
assertEquals(getNthObject(keya,1),pool.borrowObject(keya),"4");
assertEquals(getNthObject(keyb,2),pool.borrowObject(keyb),"5");
assertEquals(getNthObject(keya,2),pool.borrowObject(keya),"6");
pool.close();
}
@Test
public void testBaseBorrowReturn() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException uoe) {
return; // skip this test if unsupported
}
final Object keya = makeKey(0);
Object obj0 = pool.borrowObject(keya);
assertEquals(getNthObject(keya,0),obj0);
Object obj1 = pool.borrowObject(keya);
assertEquals(getNthObject(keya,1),obj1);
Object obj2 = pool.borrowObject(keya);
assertEquals(getNthObject(keya,2),obj2);
pool.returnObject(keya,obj2);
obj2 = pool.borrowObject(keya);
assertEquals(getNthObject(keya,2),obj2);
pool.returnObject(keya,obj1);
obj1 = pool.borrowObject(keya);
assertEquals(getNthObject(keya,1),obj1);
pool.returnObject(keya,obj0);
pool.returnObject(keya,obj2);
obj2 = pool.borrowObject(keya);
if (isLifo()) {
assertEquals(getNthObject(keya,2),obj2);
}
if (isFifo()) {
assertEquals(getNthObject(keya,0),obj2);
}
obj0 = pool.borrowObject(keya);
if (isLifo()) {
assertEquals(getNthObject(keya,0),obj0);
}
if (isFifo()) {
assertEquals(getNthObject(keya,2),obj0);
}
pool.close();
}
@Test
public void testBaseClear() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException uoe) {
return; // skip this test if unsupported
}
final Object keya = makeKey(0);
assertEquals(0,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
final Object obj0 = pool.borrowObject(keya);
final Object obj1 = pool.borrowObject(keya);
assertEquals(2,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
pool.returnObject(keya,obj1);
pool.returnObject(keya,obj0);
assertEquals(0,pool.getNumActive(keya));
assertEquals(2,pool.getNumIdle(keya));
pool.clear(keya);
assertEquals(0,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
final Object obj2 = pool.borrowObject(keya);
assertEquals(getNthObject(keya,2),obj2);
pool.close();
}
@Test
public void testBaseInvalidateObject() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException uoe) {
return; // skip this test if unsupported
}
final Object keya = makeKey(0);
assertEquals(0,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
final Object obj0 = pool.borrowObject(keya);
final Object obj1 = pool.borrowObject(keya);
assertEquals(2,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
pool.invalidateObject(keya,obj0);
assertEquals(1,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
pool.invalidateObject(keya,obj1);
assertEquals(0,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
pool.close();
}
@Test
public void testBaseNumActiveNumIdle() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException uoe) {
return; // skip this test if unsupported
}
final Object keya = makeKey(0);
assertEquals(0,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
final Object obj0 = pool.borrowObject(keya);
assertEquals(1,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
final Object obj1 = pool.borrowObject(keya);
assertEquals(2,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
pool.returnObject(keya,obj1);
assertEquals(1,pool.getNumActive(keya));
assertEquals(1,pool.getNumIdle(keya));
pool.returnObject(keya,obj0);
assertEquals(0,pool.getNumActive(keya));
assertEquals(2,pool.getNumIdle(keya));
assertEquals(0,pool.getNumActive("xyzzy12345"));
assertEquals(0,pool.getNumIdle("xyzzy12345"));
pool.close();
}
@Test
public void testBaseNumActiveNumIdle2() {
try {
pool = makeEmptyPool(6);
} catch (final UnsupportedOperationException uoe) {
return; // skip this test if unsupported
}
final Object keya = makeKey(0);
final Object keyb = makeKey(1);
assertEquals(0,pool.getNumActive());
assertEquals(0,pool.getNumIdle());
assertEquals(0,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
assertEquals(0,pool.getNumActive(keyb));
assertEquals(0,pool.getNumIdle(keyb));
final Object objA0 = pool.borrowObject(keya);
final Object objB0 = pool.borrowObject(keyb);
assertEquals(2,pool.getNumActive());
assertEquals(0,pool.getNumIdle());
assertEquals(1,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
assertEquals(1,pool.getNumActive(keyb));
assertEquals(0,pool.getNumIdle(keyb));
final Object objA1 = pool.borrowObject(keya);
final Object objB1 = pool.borrowObject(keyb);
assertEquals(4,pool.getNumActive());
assertEquals(0,pool.getNumIdle());
assertEquals(2,pool.getNumActive(keya));
assertEquals(0,pool.getNumIdle(keya));
assertEquals(2,pool.getNumActive(keyb));
assertEquals(0,pool.getNumIdle(keyb));
pool.returnObject(keya,objA0);
pool.returnObject(keyb,objB0);
assertEquals(2,pool.getNumActive());
assertEquals(2,pool.getNumIdle());
assertEquals(1,pool.getNumActive(keya));
assertEquals(1,pool.getNumIdle(keya));
assertEquals(1,pool.getNumActive(keyb));
assertEquals(1,pool.getNumIdle(keyb));
pool.returnObject(keya,objA1);
pool.returnObject(keyb,objB1);
assertEquals(0,pool.getNumActive());
assertEquals(4,pool.getNumIdle());
assertEquals(0,pool.getNumActive(keya));
assertEquals(2,pool.getNumIdle(keya));
assertEquals(0,pool.getNumActive(keyb));
assertEquals(2,pool.getNumIdle(keyb));
pool.close();
}
@Test
public void testClosedPoolBehavior() {
final KeyedObjectPool<Object, Object, RuntimeException> pool;
try {
pool = makeEmptyPool(new TestFactory());
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final Object o1 = pool.borrowObject(KEY);
final Object o2 = pool.borrowObject(KEY);
pool.close();
assertThrows(IllegalStateException.class, () -> pool.addObject(KEY),
"A closed pool must throw an IllegalStateException when addObject is called.");
assertThrows(IllegalStateException.class, () -> pool.borrowObject(KEY),
"A closed pool must throw an IllegalStateException when borrowObject is called.");
// The following should not throw exceptions just because the pool is closed.
assertEquals( 0, pool.getNumIdle(KEY),"A closed pool shouldn't have any idle objects.");
assertEquals( 0, pool.getNumIdle(),"A closed pool shouldn't have any idle objects.");
pool.getNumActive();
pool.getNumActive(KEY);
pool.returnObject(KEY, o1);
assertEquals( 0, pool.getNumIdle(KEY),"returnObject should not add items back into the idle object pool for a closed pool.");
assertEquals( 0, pool.getNumIdle(),"returnObject should not add items back into the idle object pool for a closed pool.");
pool.invalidateObject(KEY, o2);
pool.clear(KEY);
pool.clear();
pool.close();
}
@Test
public void testKPOFAddObjectUsage() {
final FailingKeyedPooledObjectFactory factory = new FailingKeyedPooledObjectFactory();
final KeyedObjectPool<Object, Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
// addObject should make a new object, passivate it and put it in the pool
pool.addObject(KEY);
expectedMethods.add(new MethodCall("makeObject", KEY).returned(ZERO));
expectedMethods.add(new MethodCall("passivateObject", KEY, ZERO));
assertEquals(expectedMethods, factory.getMethodCalls());
// Test exception handling of addObject
reset(pool, factory, expectedMethods);
// makeObject Exceptions should be propagated to client code from addObject
factory.setMakeObjectFail(true);
assertThrows(PrivateException.class, () -> pool.addObject(KEY), "Expected addObject to propagate makeObject exception.");
expectedMethods.add(new MethodCall("makeObject", KEY));
assertEquals(expectedMethods, factory.getMethodCalls());
clear(factory, expectedMethods);
// passivateObject Exceptions should be propagated to client code from addObject
factory.setMakeObjectFail(false);
factory.setPassivateObjectFail(true);
assertThrows(PrivateException.class, () -> pool.addObject(KEY), "Expected addObject to propagate passivateObject exception.");
expectedMethods.add(new MethodCall("makeObject", KEY).returned(ONE));
expectedMethods.add(new MethodCall("passivateObject", KEY, ONE));
assertEquals(expectedMethods, factory.getMethodCalls());
pool.close();
}
@Test
public void testKPOFBorrowObjectUsages() {
final FailingKeyedPooledObjectFactory factory = new FailingKeyedPooledObjectFactory();
final KeyedObjectPool<Object, Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
Object obj;
if (pool instanceof GenericKeyedObjectPool) {
((GenericKeyedObjectPool<Object, Object, PrivateException>) pool).setTestOnBorrow(true);
}
// Test correct behavior code paths
// existing idle object should be activated and validated
pool.addObject(KEY);
clear(factory, expectedMethods);
obj = pool.borrowObject(KEY);
expectedMethods.add(new MethodCall("activateObject", KEY, ZERO));
expectedMethods.add(new MethodCall("validateObject", KEY, ZERO).returned(Boolean.TRUE));
assertEquals(expectedMethods, factory.getMethodCalls());
pool.returnObject(KEY, obj);
// Test exception handling of borrowObject
reset(pool, factory, expectedMethods);
// makeObject Exceptions should be propagated to client code from borrowObject
factory.setMakeObjectFail(true);
assertThrows(PrivateException.class, () -> pool.borrowObject(KEY), "Expected borrowObject to propagate makeObject exception.");
expectedMethods.add(new MethodCall("makeObject", KEY));
assertEquals(expectedMethods, factory.getMethodCalls());
// when activateObject fails in borrowObject, a new object should be borrowed/created
reset(pool, factory, expectedMethods);
pool.addObject(KEY);
clear(factory, expectedMethods);
factory.setActivateObjectFail(true);
expectedMethods.add(new MethodCall("activateObject", KEY, obj));
assertThrows(NoSuchElementException.class, () -> pool.borrowObject(KEY));
// After idle object fails validation, new on is created and activation
// fails again for the new one.
expectedMethods.add(new MethodCall("makeObject", KEY).returned(ONE));
expectedMethods.add(new MethodCall("activateObject", KEY, ONE));
AbstractTestObjectPool.removeDestroyObjectCall(factory.getMethodCalls()); // The exact timing of destroyObject is flexible here.
assertEquals(expectedMethods, factory.getMethodCalls());
// when validateObject fails in borrowObject, a new object should be borrowed/created
reset(pool, factory, expectedMethods);
pool.addObject(KEY);
clear(factory, expectedMethods);
factory.setValidateObjectFail(true);
// testOnBorrow is on, so this will throw when the newly created instance
// fails validation
assertThrows(NoSuchElementException.class, () -> pool.borrowObject(KEY));
// Activate, then validate for idle instance
expectedMethods.add(new MethodCall("activateObject", KEY, ZERO));
expectedMethods.add(new MethodCall("validateObject", KEY, ZERO));
// Make new instance, activate succeeds, validate fails
expectedMethods.add(new MethodCall("makeObject", KEY).returned(ONE));
expectedMethods.add(new MethodCall("activateObject", KEY, ONE));
expectedMethods.add(new MethodCall("validateObject", KEY, ONE));
AbstractTestObjectPool.removeDestroyObjectCall(factory.getMethodCalls());
assertEquals(expectedMethods, factory.getMethodCalls());
pool.close();
}
@Test
public void testKPOFClearUsages() {
final FailingKeyedPooledObjectFactory factory = new FailingKeyedPooledObjectFactory();
final KeyedObjectPool<Object, Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
// Test correct behavior code paths
pool.addObjects(KEY, 5);
pool.clear();
// Test exception handling clear should swallow destroy object failures
reset(pool, factory, expectedMethods);
factory.setDestroyObjectFail(true);
pool.addObjects(KEY, 5);
pool.clear();
pool.close();
}
@Test
public void testKPOFCloseUsages() {
final FailingKeyedPooledObjectFactory factory = new FailingKeyedPooledObjectFactory();
KeyedObjectPool<Object, Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
// Test correct behavior code paths
pool.addObjects(KEY, 5);
pool.close();
// Test exception handling close should swallow failures
try (final KeyedObjectPool<Object, Object, PrivateException> pool2 = makeEmptyPool(factory)) {
reset(pool2, factory, expectedMethods);
factory.setDestroyObjectFail(true);
pool2.addObjects(KEY, 5);
}
}
@Test
public void testKPOFInvalidateObjectUsages() throws InterruptedException {
final FailingKeyedPooledObjectFactory factory = new FailingKeyedPooledObjectFactory();
final KeyedObjectPool<Object, Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
Object obj;
// Test correct behavior code paths
obj = pool.borrowObject(KEY);
clear(factory, expectedMethods);
// invalidated object should be destroyed
pool.invalidateObject(KEY, obj);
expectedMethods.add(new MethodCall("destroyObject", KEY, obj));
assertEquals(expectedMethods, factory.getMethodCalls());
// Test exception handling of invalidateObject
reset(pool, factory, expectedMethods);
final Object obj2 = pool.borrowObject(KEY);
clear(factory, expectedMethods);
factory.setDestroyObjectFail(true);
assertThrows(PrivateException.class, () -> pool.invalidateObject(KEY, obj2), "Expecting destroy exception to propagate");
Thread.sleep(250); // could be defered
AbstractTestObjectPool.removeDestroyObjectCall(factory.getMethodCalls());
assertEquals(expectedMethods, factory.getMethodCalls());
pool.close();
}
@Test
public void testKPOFReturnObjectUsages() {
final FailingKeyedPooledObjectFactory factory = new FailingKeyedPooledObjectFactory();
final KeyedObjectPool<Object, Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
Object obj;
// Test correct behavior code paths
obj = pool.borrowObject(KEY);
clear(factory, expectedMethods);
// returned object should be passivated
pool.returnObject(KEY, obj);
expectedMethods.add(new MethodCall("passivateObject", KEY, obj));
assertEquals(expectedMethods, factory.getMethodCalls());
// Test exception handling of returnObject
reset(pool, factory, expectedMethods);
// passivateObject should swallow exceptions and not add the object to the pool
pool.addObject(KEY);
pool.addObject(KEY);
pool.addObject(KEY);
assertEquals(3, pool.getNumIdle(KEY));
obj = pool.borrowObject(KEY);
obj = pool.borrowObject(KEY);
assertEquals(1, pool.getNumIdle(KEY));
assertEquals(2, pool.getNumActive(KEY));
clear(factory, expectedMethods);
factory.setPassivateObjectFail(true);
pool.returnObject(KEY, obj);
expectedMethods.add(new MethodCall("passivateObject", KEY, obj));
AbstractTestObjectPool.removeDestroyObjectCall(factory.getMethodCalls()); // The exact timing of destroyObject is flexible here.
assertEquals(expectedMethods, factory.getMethodCalls());
assertEquals(1, pool.getNumIdle(KEY)); // Not added
assertEquals(1, pool.getNumActive(KEY)); // But not active
reset(pool, factory, expectedMethods);
obj = pool.borrowObject(KEY);
clear(factory, expectedMethods);
factory.setPassivateObjectFail(true);
factory.setDestroyObjectFail(true);
try {
pool.returnObject(KEY, obj);
if (!(pool instanceof GenericKeyedObjectPool)) { // ugh, 1.3-compat
fail("Expecting destroyObject exception to be propagated");
}
} catch (final PrivateException ex) {
// Expected
}
pool.close();
}
@Test
public void testToString() {
final FailingKeyedPooledObjectFactory factory = new FailingKeyedPooledObjectFactory();
try (final KeyedObjectPool<Object, Object, PrivateException> pool = makeEmptyPool(factory)) {
pool.toString();
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
}
}
| 5,189 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/WaiterFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.pool3.impl.DefaultPooledObject;
/**
* Object factory with configurable latencies for object lifecycle methods.
* This factory will also track and enforce maxActive, maxActivePerKey contracts.
* If the factory's maxActive / maxActivePerKey are set to match those of the
* pool, makeObject will throw IllegalStateException if the number of makes - destroys
* (per key) exceeds the configured max.
*
* @param <K> The type of keys managed by this factory.
*/
public class WaiterFactory<K> implements PooledObjectFactory<Waiter, IllegalStateException>, KeyedPooledObjectFactory<K, Waiter, RuntimeException> {
/** Integer value 0. */
private static final Integer ZERO = Integer.valueOf(0);
/** Integer value 1. */
private static final Integer ONE = Integer.valueOf(1);
/** Latency of activateObject */
private final long activateLatency;
/** Latency of destroyObject */
private final long destroyLatency;
/** Latency of makeObject */
private final long makeLatency;
/** Latency of passivateObject */
private final long passivateLatency;
/** Latency of validateObject */
private final long validateLatency;
/** Latency of doWait for Waiter instances created by this factory */
private final long waiterLatency;
/** Probability that passivation will invalidate Waiter instances */
private final double passivateInvalidationProbability;
/** Count of (makes - destroys) since last reset */
private long activeCount;
/** Count of (makes - destroys) per key since last reset */
private final Map<K,Integer> activeCounts = new HashMap<>();
/** Maximum of (makes - destroys) - if exceeded IllegalStateException */
private final long maxActive; // GKOP 1.x calls this maxTotal
/** Maximum of (makes - destroys) per key */
private final long maxActivePerKey; // GKOP 1.x calls this maxActive
public WaiterFactory(final long activateLatency, final long destroyLatency,
final long makeLatency, final long passivateLatency, final long validateLatency,
final long waiterLatency) {
this(activateLatency, destroyLatency, makeLatency, passivateLatency,
validateLatency, waiterLatency, Long.MAX_VALUE, Long.MAX_VALUE, 0);
}
public WaiterFactory(final long activateLatency, final long destroyLatency,
final long makeLatency, final long passivateLatency, final long validateLatency,
final long waiterLatency,final long maxActive) {
this(activateLatency, destroyLatency, makeLatency, passivateLatency,
validateLatency, waiterLatency, maxActive, Long.MAX_VALUE, 0);
}
public WaiterFactory(final long activateLatency, final long destroyLatency,
final long makeLatency, final long passivateLatency, final long validateLatency,
final long waiterLatency,final long maxActive, final long maxActivePerKey,
final double passivateInvalidationProbability) {
this.activateLatency = activateLatency;
this.destroyLatency = destroyLatency;
this.makeLatency = makeLatency;
this.passivateLatency = passivateLatency;
this.validateLatency = validateLatency;
this.waiterLatency = waiterLatency;
this.maxActive = maxActive;
this.maxActivePerKey = maxActivePerKey;
this.passivateInvalidationProbability = passivateInvalidationProbability;
}
@Override
public void activateObject(final K key, final PooledObject<Waiter> obj) {
activateObject(obj);
}
@Override
public void activateObject(final PooledObject<Waiter> obj) {
doWait(activateLatency);
obj.getObject().setActive(true);
}
@Override
public void destroyObject(final K key, final PooledObject<Waiter> obj) {
destroyObject(obj);
synchronized (this) {
activeCounts.computeIfPresent(key, (k, v) -> Integer.valueOf(v.intValue() - 1));
}
}
@Override
public void destroyObject(final PooledObject<Waiter> obj) {
doWait(destroyLatency);
obj.getObject().setValid(false);
obj.getObject().setActive(false);
// Decrement *after* destroy
synchronized (this) {
activeCount--;
}
}
protected void doWait(final long latency) {
if (latency == 0) {
return;
}
Waiter.sleepQuietly(latency);
}
/**
* @return the maxActive
*/
public synchronized long getMaxActive() {
return maxActive;
}
@Override
public PooledObject<Waiter> makeObject() {
// Increment and test *before* make
synchronized (this) {
if (activeCount >= maxActive) {
throw new IllegalStateException("Too many active instances: " +
activeCount + " in circulation with maxActive = " + maxActive);
}
activeCount++;
}
doWait(makeLatency);
return new DefaultPooledObject<>(new Waiter(false, true, waiterLatency));
}
@Override
public PooledObject<Waiter> makeObject(final K key) {
synchronized (this) {
activeCounts.merge(key, ONE, (v1, v2) -> {
if (v1.intValue() >= maxActivePerKey) {
throw new IllegalStateException("Too many active " +
"instances for key = " + key + ": " + v1.intValue() +
" in circulation " + "with maxActivePerKey = " +
maxActivePerKey);
}
return Integer.valueOf(v1.intValue() + 1);
});
}
return makeObject();
}
@Override
public void passivateObject(final K key, final PooledObject<Waiter> obj) {
passivateObject(obj);
}
@Override
public void passivateObject(final PooledObject<Waiter> obj) {
obj.getObject().setActive(false);
doWait(passivateLatency);
if (Math.random() < passivateInvalidationProbability) {
obj.getObject().setValid(false);
}
}
public synchronized void reset() {
activeCount = 0;
if (activeCounts.isEmpty()) {
return;
}
for (K key : activeCounts.keySet()) {
activeCounts.put(key, ZERO);
}
}
@Override
public boolean validateObject(final K key, final PooledObject<Waiter> obj) {
return validateObject(obj);
}
@Override
public boolean validateObject(final PooledObject<Waiter> obj) {
doWait(validateLatency);
return obj.getObject().isValid();
}
}
| 5,190 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/AbstractTestObjectPool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import org.apache.commons.pool3.impl.GenericObjectPool;
import org.apache.commons.pool3.impl.SoftReferenceObjectPool;
import org.junit.jupiter.api.Test;
/**
* Abstract test case for {@link ObjectPool} implementations.
*/
public abstract class AbstractTestObjectPool {
private static void clear(final MethodCallPoolableObjectFactory factory, final List<MethodCall> expectedMethods) {
factory.getMethodCalls().clear();
expectedMethods.clear();
}
static void removeDestroyObjectCall(final List<MethodCall> calls) {
calls.removeIf(call -> "destroyObject".equals(call.getName()));
}
private static void reset(final ObjectPool<Object, ?> pool, final MethodCallPoolableObjectFactory factory, final List<MethodCall> expectedMethods) throws Exception {
pool.clear();
clear(factory, expectedMethods);
factory.reset();
}
// Deliberate choice to create a new object in case future unit tests check
// for a specific object.
private final Integer ZERO = Integer.valueOf(0);
private final Integer ONE = Integer.valueOf(1);
/**
* Create an {@code ObjectPool} with the specified factory.
* The pool should be in a default configuration and conform to the expected
* behaviors described in {@link ObjectPool}.
* Generally speaking there should be no limits on the various object counts.
*
* @param <E> The exception type throws by the pool
* @param factory The factory to be used by the object pool
*
* @return the newly created empty pool
*
* @throws UnsupportedOperationException if the pool being tested does not
* follow pool contracts.
*/
protected abstract <E extends Exception> ObjectPool<Object, E> makeEmptyPool(PooledObjectFactory<Object, E> factory) throws UnsupportedOperationException;
@Test
public void testClosedPoolBehavior() throws Exception {
final ObjectPool<Object, PrivateException> pool;
try {
pool = makeEmptyPool(new MethodCallPoolableObjectFactory());
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final Object o1 = pool.borrowObject();
final Object o2 = pool.borrowObject();
pool.close();
assertThrows(IllegalStateException.class, pool::addObject, "A closed pool must throw an IllegalStateException when addObject is called.");
assertThrows(IllegalStateException.class, pool::borrowObject, "A closed pool must throw an IllegalStateException when borrowObject is called.");
// The following should not throw exceptions just because the pool is closed.
if (pool.getNumIdle() >= 0) {
assertEquals( 0, pool.getNumIdle(),"A closed pool shouldn't have any idle objects.");
}
if (pool.getNumActive() >= 0) {
assertEquals( 2, pool.getNumActive(),"A closed pool should still keep count of active objects.");
}
pool.returnObject(o1);
if (pool.getNumIdle() >= 0) {
assertEquals( 0, pool.getNumIdle(),"returnObject should not add items back into the idle object pool for a closed pool.");
}
if (pool.getNumActive() >= 0) {
assertEquals( 1, pool.getNumActive(),"A closed pool should still keep count of active objects.");
}
pool.invalidateObject(o2);
if (pool.getNumIdle() >= 0) {
assertEquals( 0, pool.getNumIdle(),"invalidateObject must not add items back into the idle object pool.");
}
if (pool.getNumActive() >= 0) {
assertEquals( 0, pool.getNumActive(),"A closed pool should still keep count of active objects.");
}
pool.clear();
pool.close();
}
@Test
public void testPOFAddObjectUsage() throws Exception {
final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory();
final ObjectPool<Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
assertEquals(0, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
// addObject should make a new object, passivate it and put it in the pool
pool.addObject();
assertEquals(0, pool.getNumActive());
assertEquals(1, pool.getNumIdle());
expectedMethods.add(new MethodCall("makeObject").returned(ZERO));
// StackObjectPool, SoftReferenceObjectPool also validate on add
if (pool instanceof SoftReferenceObjectPool) {
expectedMethods.add(new MethodCall(
"validateObject", ZERO).returned(Boolean.TRUE));
}
expectedMethods.add(new MethodCall("passivateObject", ZERO));
assertEquals(expectedMethods, factory.getMethodCalls());
// Test exception handling of addObject
reset(pool, factory, expectedMethods);
// makeObject Exceptions should be propagated to client code from addObject
factory.setMakeObjectFail(true);
assertThrows(PrivateException.class, pool::addObject, "Expected addObject to propagate makeObject exception.");
expectedMethods.add(new MethodCall("makeObject"));
assertEquals(expectedMethods, factory.getMethodCalls());
clear(factory, expectedMethods);
// passivateObject Exceptions should be propagated to client code from addObject
factory.setMakeObjectFail(false);
factory.setPassivateObjectFail(true);
assertThrows(PrivateException.class, pool::addObject, "Expected addObject to propagate passivateObject exception.");
expectedMethods.add(new MethodCall("makeObject").returned(ONE));
// StackObjectPool, SofReferenceObjectPool also validate on add
if (pool instanceof SoftReferenceObjectPool) {
expectedMethods.add(new MethodCall("validateObject", ONE).returned(Boolean.TRUE));
}
expectedMethods.add(new MethodCall("passivateObject", ONE));
assertEquals(expectedMethods, factory.getMethodCalls());
pool.close();
}
@Test
public void testPOFBorrowObjectUsages() throws Exception {
final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory();
final ObjectPool<Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
if (pool instanceof GenericObjectPool) {
((GenericObjectPool<Object, PrivateException>) pool).setTestOnBorrow(true);
}
final List<MethodCall> expectedMethods = new ArrayList<>();
Object obj;
// Test correct behavior code paths
// existing idle object should be activated and validated
pool.addObject();
clear(factory, expectedMethods);
obj = pool.borrowObject();
expectedMethods.add(new MethodCall("activateObject", ZERO));
expectedMethods.add(new MethodCall("validateObject", ZERO).returned(Boolean.TRUE));
assertEquals(expectedMethods, factory.getMethodCalls());
pool.returnObject(obj);
// Test exception handling of borrowObject
reset(pool, factory, expectedMethods);
// makeObject Exceptions should be propagated to client code from borrowObject
factory.setMakeObjectFail(true);
assertThrows(PrivateException.class, pool::borrowObject, "Expected borrowObject to propagate makeObject exception.");
expectedMethods.add(new MethodCall("makeObject"));
assertEquals(expectedMethods, factory.getMethodCalls());
// when activateObject fails in borrowObject, a new object should be borrowed/created
reset(pool, factory, expectedMethods);
pool.addObject();
clear(factory, expectedMethods);
factory.setActivateObjectFail(true);
expectedMethods.add(new MethodCall("activateObject", obj));
// Expected NoSuchElementException - newly created object will also fail to activate
assertThrows(NoSuchElementException.class, pool::borrowObject, "Expecting NoSuchElementException");
// Idle object fails activation, new one created, also fails
expectedMethods.add(new MethodCall("makeObject").returned(ONE));
expectedMethods.add(new MethodCall("activateObject", ONE));
removeDestroyObjectCall(factory.getMethodCalls()); // The exact timing of destroyObject is flexible here.
assertEquals(expectedMethods, factory.getMethodCalls());
// when validateObject fails in borrowObject, a new object should be borrowed/created
reset(pool, factory, expectedMethods);
pool.addObject();
clear(factory, expectedMethods);
factory.setValidateObjectFail(true);
expectedMethods.add(new MethodCall("activateObject", ZERO));
expectedMethods.add(new MethodCall("validateObject", ZERO));
// Expected NoSuchElementException - newly created object will also fail to validate
assertThrows(NoSuchElementException.class, pool::borrowObject, "Expecting NoSuchElementException");
// Idle object is activated, but fails validation.
// New instance is created, activated and then fails validation
expectedMethods.add(new MethodCall("makeObject").returned(ONE));
expectedMethods.add(new MethodCall("activateObject", ONE));
expectedMethods.add(new MethodCall("validateObject", ONE));
removeDestroyObjectCall(factory.getMethodCalls()); // The exact timing of destroyObject is flexible here.
// Second activate and validate are missing from expectedMethods
assertTrue(factory.getMethodCalls().containsAll(expectedMethods));
pool.close();
}
@Test
public void testPOFClearUsages() throws Exception {
final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory();
final ObjectPool<Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
// Test correct behavior code paths
pool.addObjects(5);
pool.clear();
// Test exception handling clear should swallow destroy object failures
reset(pool, factory, expectedMethods);
factory.setDestroyObjectFail(true);
pool.addObjects(5);
pool.clear();
pool.close();
}
@Test
public void testPOFCloseUsages() throws Exception {
final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory();
ObjectPool<Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
// Test correct behavior code paths
pool.addObjects(5);
pool.close();
// Test exception handling close should swallow failures
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
reset(pool, factory, expectedMethods);
factory.setDestroyObjectFail(true);
pool.addObjects(5);
pool.close();
}
@Test
public void testPOFInvalidateObjectUsages() throws Exception {
final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory();
final ObjectPool<Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
Object obj;
// Test correct behavior code paths
obj = pool.borrowObject();
clear(factory, expectedMethods);
// invalidated object should be destroyed
pool.invalidateObject(obj);
expectedMethods.add(new MethodCall("destroyObject", obj));
assertEquals(expectedMethods, factory.getMethodCalls());
// Test exception handling of invalidateObject
reset(pool, factory, expectedMethods);
final Object obj2 = pool.borrowObject();
clear(factory, expectedMethods);
factory.setDestroyObjectFail(true);
assertThrows(PrivateException.class, () -> pool.invalidateObject(obj2));
Thread.sleep(250); // could be deferred
removeDestroyObjectCall(factory.getMethodCalls());
assertEquals(expectedMethods, factory.getMethodCalls());
pool.close();
}
@Test
public void testPOFReturnObjectUsages() throws Exception {
final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory();
final ObjectPool<Object, PrivateException> pool;
try {
pool = makeEmptyPool(factory);
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
final List<MethodCall> expectedMethods = new ArrayList<>();
Object obj;
// Test correct behavior code paths
obj = pool.borrowObject();
clear(factory, expectedMethods);
// returned object should be passivated
pool.returnObject(obj);
// StackObjectPool, SoftReferenceObjectPool also validate on return
if (pool instanceof SoftReferenceObjectPool) {
expectedMethods.add(new MethodCall(
"validateObject", obj).returned(Boolean.TRUE));
}
expectedMethods.add(new MethodCall("passivateObject", obj));
assertEquals(expectedMethods, factory.getMethodCalls());
// Test exception handling of returnObject
reset(pool, factory, expectedMethods);
pool.addObject();
pool.addObject();
pool.addObject();
assertEquals(3, pool.getNumIdle());
// passivateObject should swallow exceptions and not add the object to the pool
obj = pool.borrowObject();
pool.borrowObject();
assertEquals(1, pool.getNumIdle());
assertEquals(2, pool.getNumActive());
clear(factory, expectedMethods);
factory.setPassivateObjectFail(true);
pool.returnObject(obj);
// StackObjectPool, SoftReferenceObjectPool also validate on return
if (pool instanceof SoftReferenceObjectPool) {
expectedMethods.add(new MethodCall("validateObject", obj).returned(Boolean.TRUE));
}
expectedMethods.add(new MethodCall("passivateObject", obj));
removeDestroyObjectCall(factory.getMethodCalls()); // The exact timing of destroyObject is flexible here.
assertEquals(expectedMethods, factory.getMethodCalls());
assertEquals(1, pool.getNumIdle()); // Not returned
assertEquals(1, pool.getNumActive()); // But not in active count
// destroyObject should swallow exceptions too
reset(pool, factory, expectedMethods);
obj = pool.borrowObject();
clear(factory, expectedMethods);
factory.setPassivateObjectFail(true);
factory.setDestroyObjectFail(true);
pool.returnObject(obj);
pool.close();
}
@Test
public void testToString() {
final ObjectPool<Object, PrivateException> pool;
try {
pool = makeEmptyPool(new MethodCallPoolableObjectFactory());
} catch (final UnsupportedOperationException uoe) {
return; // test not supported
}
pool.toString();
pool.close();
}
}
| 5,191 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/ObjectPoolIssue326.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.commons.pool3.impl.BaseObjectPoolConfig;
import org.apache.commons.pool3.impl.DefaultPooledObject;
import org.apache.commons.pool3.impl.GenericKeyedObjectPool;
import org.apache.commons.pool3.impl.GenericKeyedObjectPoolConfig;
/**
* On my box with 4 cores this test fails at between 5s and 900s with an average
* of 240s (data from 10 runs of test).
*
* It is hard to turn this in a unit test because it can affect the build
* negatively since you need to run it for a while.
*/
public final class ObjectPoolIssue326 {
private static final class ObjectFactory extends BaseKeyedPooledObjectFactory<Integer, Object, RuntimeException> {
@Override
public Object create(final Integer s) {
return new TestObject();
}
@Override
public PooledObject<Object> wrap(final Object o) {
return new DefaultPooledObject<>(o);
}
}
private static final class Task<E extends Exception> implements Callable<Object> {
private final GenericKeyedObjectPool<Integer, Object, E> pool;
private final int key;
Task(final GenericKeyedObjectPool<Integer, Object, E> pool, final int count) {
this.pool = pool;
this.key = count % 20;
}
private void busyWait(final long timeMillis) {
// busy waiting intentionally as a simple thread.sleep fails to reproduce
final long endTimeMillis = System.currentTimeMillis() + timeMillis;
while (System.currentTimeMillis() < endTimeMillis) {
// empty
}
}
@Override
public Object call() throws E {
try {
final Object value;
value = pool.borrowObject(key);
// don't make this too long or it won't reproduce, and don't make it zero or it
// won't reproduce
// constant low value also doesn't reproduce
busyWait(System.currentTimeMillis() % 4);
pool.returnObject(key, value);
return "success";
} catch (final NoSuchElementException e) {
// ignore, we've exhausted the pool
// not sure whether what we do here matters for reproducing
busyWait(System.currentTimeMillis() % 20);
return "exhausted";
}
}
}
private static final class TestObject {
}
public static void main(final String[] args) {
try {
new ObjectPoolIssue326().run();
} catch (final Exception e) {
e.printStackTrace();
}
}
private <E extends Exception> List<Task<E>> createTasks(final GenericKeyedObjectPool<Integer, Object, E> pool) {
final List<Task<E>> tasks = new ArrayList<>();
for (int i = 0; i < 250; i++) {
tasks.add(new Task<>(pool, i));
}
return tasks;
}
private void run() throws InterruptedException, ExecutionException {
final GenericKeyedObjectPoolConfig<Object> poolConfig = new GenericKeyedObjectPoolConfig<>();
poolConfig.setMaxTotal(10);
poolConfig.setMaxTotalPerKey(5);
poolConfig.setMinIdlePerKey(-1);
poolConfig.setMaxIdlePerKey(-1);
poolConfig.setLifo(true);
poolConfig.setFairness(true);
poolConfig.setMaxWait(Duration.ofSeconds(30));
poolConfig.setMinEvictableIdleDuration(Duration.ofMillis(-1));
poolConfig.setSoftMinEvictableIdleDuration(Duration.ofMillis(-1));
poolConfig.setNumTestsPerEvictionRun(1);
poolConfig.setTestOnCreate(false);
poolConfig.setTestOnBorrow(false);
poolConfig.setTestOnReturn(false);
poolConfig.setTestWhileIdle(false);
poolConfig.setDurationBetweenEvictionRuns(Duration.ofSeconds(5));
poolConfig.setEvictionPolicyClassName(BaseObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME);
poolConfig.setBlockWhenExhausted(false);
poolConfig.setJmxEnabled(false);
poolConfig.setJmxNameBase(null);
poolConfig.setJmxNamePrefix(null);
final GenericKeyedObjectPool<Integer, Object, RuntimeException> pool = new GenericKeyedObjectPool<>(new ObjectFactory(), poolConfig);
// number of threads to reproduce is finicky. this count seems to be best for my
// 4 core box.
// too many doesn't reproduce it ever, too few doesn't either.
final ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
final Instant startTime = Instant.now();
long testIter = 0;
try {
while (true) {
testIter++;
if (testIter % 1000 == 0) {
System.out.println(testIter);
}
final List<Task<RuntimeException>> tasks = createTasks(pool);
final List<Future<Object>> futures = service.invokeAll(tasks);
for (final Future<Object> future : futures) {
future.get();
}
}
} finally {
System.out.println("Time: " + Duration.between(startTime, Instant.now()));
service.shutdown();
}
}
}
/*
* Example stack trace: java.util.concurrent.ExecutionException:
* java.lang.NullPointerException at
* java.util.concurrent.FutureTask.report(FutureTask.java:122) at
* java.util.concurrent.FutureTask.get(FutureTask.java:192) at
* threading_pool.ObjectPoolIssue.run(ObjectPoolIssue.java:63) at
* threading_pool.ObjectPoolIssue.main(ObjectPoolIssue.java:23) at
* sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
* sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
* at
* sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.
* java:43) at java.lang.reflect.Method.invoke(Method.java:498) at
* com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) Caused
* by: java.lang.NullPointerException at
* org.apache.commons.pool3.impl.GenericKeyedObjectPool.returnObject(
* GenericKeyedObjectPool.java:474) at
* threading_pool.ObjectPoolIssue$Task.call(ObjectPoolIssue.java:112) at
* java.util.concurrent.FutureTask.run(FutureTask.java:266) at
* java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:
* 1142) at
* java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:
* 617) at java.lang.Thread.run(Thread.java:745)
*/
| 5,192 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/TestBaseObjectPool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
/**
*/
public class TestBaseObjectPool extends AbstractTestObjectPool {
private static final class TestObjectPool extends BaseObjectPool<Object, RuntimeException> {
@Override
public Object borrowObject() {
return null;
}
@Override
public void invalidateObject(final Object obj) {
}
@Override
public void returnObject(final Object obj) {
}
}
private ObjectPool<String, RuntimeException> pool;
/**
* @param n Ignored by this implemented. Used by sub-classes.
*
* @return the Nth object (zero indexed)
*/
protected Object getNthObject(final int n) {
if (this.getClass() != TestBaseObjectPool.class) {
fail("Subclasses of TestBaseObjectPool must reimplement this method.");
}
throw new UnsupportedOperationException("BaseObjectPool isn't a complete implementation.");
}
protected boolean isFifo() {
if (this.getClass() != TestBaseObjectPool.class) {
fail("Subclasses of TestBaseObjectPool must reimplement this method.");
}
return false;
}
protected boolean isLifo() {
if (this.getClass() != TestBaseObjectPool.class) {
fail("Subclasses of TestBaseObjectPool must reimplement this method.");
}
return false;
}
/**
* @param minCapacity Ignored by this implemented. Used by sub-classes.
*
* @return A newly created empty pool
*/
protected <E extends Exception> ObjectPool<String, E> makeEmptyPool(final int minCapacity) {
if (this.getClass() != TestBaseObjectPool.class) {
fail("Subclasses of TestBaseObjectPool must reimplement this method.");
}
throw new UnsupportedOperationException("BaseObjectPool isn't a complete implementation.");
}
@Override
protected <E extends Exception> ObjectPool<Object, E> makeEmptyPool(final PooledObjectFactory<Object, E> factory) {
if (this.getClass() != TestBaseObjectPool.class) {
fail("Subclasses of TestBaseObjectPool must reimplement this method.");
}
throw new UnsupportedOperationException("BaseObjectPool isn't a complete implementation.");
}
@Test
public void testBaseAddObject() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException e) {
return; // skip this test if unsupported
}
try {
assertEquals(0, pool.getNumIdle());
assertEquals(0, pool.getNumActive());
pool.addObject();
assertEquals(1, pool.getNumIdle());
assertEquals(0, pool.getNumActive());
final String obj = pool.borrowObject();
assertEquals(getNthObject(0), obj);
assertEquals(0, pool.getNumIdle());
assertEquals(1, pool.getNumActive());
pool.returnObject(obj);
assertEquals(1, pool.getNumIdle());
assertEquals(0, pool.getNumActive());
} catch (final UnsupportedOperationException e) {
return; // skip this test if one of those calls is unsupported
} finally {
pool.close();
}
}
@Test
public void testBaseBorrow() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException e) {
return; // skip this test if unsupported
}
assertEquals(getNthObject(0), pool.borrowObject());
assertEquals(getNthObject(1), pool.borrowObject());
assertEquals(getNthObject(2), pool.borrowObject());
pool.close();
}
@Test
public void testBaseBorrowReturn() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException e) {
return; // skip this test if unsupported
}
String obj0 = pool.borrowObject();
assertEquals(getNthObject(0), obj0);
String obj1 = pool.borrowObject();
assertEquals(getNthObject(1), obj1);
String obj2 = pool.borrowObject();
assertEquals(getNthObject(2), obj2);
pool.returnObject(obj2);
obj2 = pool.borrowObject();
assertEquals(getNthObject(2), obj2);
pool.returnObject(obj1);
obj1 = pool.borrowObject();
assertEquals(getNthObject(1), obj1);
pool.returnObject(obj0);
pool.returnObject(obj2);
obj2 = pool.borrowObject();
if (isLifo()) {
assertEquals(getNthObject(2),obj2);
}
if (isFifo()) {
assertEquals(getNthObject(0),obj2);
}
obj0 = pool.borrowObject();
if (isLifo()) {
assertEquals(getNthObject(0),obj0);
}
if (isFifo()) {
assertEquals(getNthObject(2),obj0);
}
pool.close();
}
@Test
public void testBaseClear() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException e) {
return; // skip this test if unsupported
}
assertEquals(0, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
final String obj0 = pool.borrowObject();
final String obj1 = pool.borrowObject();
assertEquals(2, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
pool.returnObject(obj1);
pool.returnObject(obj0);
assertEquals(0, pool.getNumActive());
assertEquals(2, pool.getNumIdle());
pool.clear();
assertEquals(0, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
final Object obj2 = pool.borrowObject();
assertEquals(getNthObject(2), obj2);
pool.close();
}
@Test
public void testBaseClosePool() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException e) {
return; // skip this test if unsupported
}
final String obj = pool.borrowObject();
pool.returnObject(obj);
pool.close();
assertThrows(IllegalStateException.class, pool::borrowObject);
}
@Test
public void testBaseInvalidateObject() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException e) {
return; // skip this test if unsupported
}
assertEquals(0, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
final String obj0 = pool.borrowObject();
final String obj1 = pool.borrowObject();
assertEquals(2, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
pool.invalidateObject(obj0);
assertEquals(1, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
pool.invalidateObject(obj1);
assertEquals(0, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
pool.close();
}
@Test
public void testBaseNumActiveNumIdle() {
try {
pool = makeEmptyPool(3);
} catch (final UnsupportedOperationException e) {
return; // skip this test if unsupported
}
assertEquals(0, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
final String obj0 = pool.borrowObject();
assertEquals(1, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
final String obj1 = pool.borrowObject();
assertEquals(2, pool.getNumActive());
assertEquals(0, pool.getNumIdle());
pool.returnObject(obj1);
assertEquals(1, pool.getNumActive());
assertEquals(1, pool.getNumIdle());
pool.returnObject(obj0);
assertEquals(0, pool.getNumActive());
assertEquals(2, pool.getNumIdle());
pool.close();
}
@Test
public void testClose() {
@SuppressWarnings("resource")
final ObjectPool<Object, RuntimeException> pool = new TestObjectPool();
pool.close();
pool.close(); // should not error as of Pool 2.0.
}
@Test
public void testUnsupportedOperations() {
if (!getClass().equals(TestBaseObjectPool.class)) {
return; // skip redundant tests
}
try (final ObjectPool<Object,RuntimeException> pool = new TestObjectPool()) {
assertTrue( pool.getNumIdle() < 0,"Negative expected.");
assertTrue( pool.getNumActive() < 0,"Negative expected.");
assertThrows(UnsupportedOperationException.class, pool::clear);
assertThrows(UnsupportedOperationException.class, pool::addObject);
}
}
}
| 5,193 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/TestPoolUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import org.apache.commons.pool3.impl.DefaultPooledObject;
import org.apache.commons.pool3.impl.GenericKeyedObjectPool;
import org.apache.commons.pool3.impl.GenericObjectPool;
import org.junit.jupiter.api.Test;
import org.opentest4j.AssertionFailedError;
/**
* Unit tests for {@link PoolUtils}.
*
* TODO Replace our own mocking with a mocking library like Mockito.
*/
public class TestPoolUtils {
private static class MethodCallLogger implements InvocationHandler {
private final List<String> calledMethods;
MethodCallLogger(final List<String> calledMethods) {
this.calledMethods = calledMethods;
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if (calledMethods == null) {
return null;
}
calledMethods.add(method.getName());
if (boolean.class.equals(method.getReturnType())) {
return Boolean.FALSE;
}
if (int.class.equals(method.getReturnType())) {
return Integer.valueOf(0);
}
if (long.class.equals(method.getReturnType())) {
return Long.valueOf(0);
}
if (Object.class.equals(method.getReturnType())) {
return new Object();
}
if (PooledObject.class.equals(method.getReturnType())) {
return new DefaultPooledObject<>(new Object());
}
return null;
}
}
/** Period between checks for minIdle tests. Increase this if you happen to get too many false failures. */
private static final int CHECK_PERIOD = 300;
/** Times to let the minIdle check run. */
private static final int CHECK_COUNT = 4;
/** Sleep time to let the minIdle tests run CHECK_COUNT times. */
private static final int CHECK_SLEEP_PERIOD = CHECK_PERIOD * (CHECK_COUNT - 1) + CHECK_PERIOD / 2;
@SuppressWarnings("unchecked")
private static <T> T createProxy(final Class<T> clazz, final InvocationHandler handler) {
return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, handler);
}
private static <T> T createProxy(final Class<T> clazz, final List<String> logger) {
return createProxy(clazz, new MethodCallLogger(logger));
}
private static List<String> invokeEveryMethod(final KeyedObjectPool<Object, Object, RuntimeException> kop) {
kop.addObject(null);
kop.borrowObject(null);
kop.clear();
kop.clear(null);
kop.close();
kop.getKeys();
kop.getNumActive();
kop.getNumActive(null);
kop.getNumIdle();
kop.getNumIdle(null);
kop.invalidateObject(null, new Object());
kop.returnObject(null, new Object());
kop.toString();
return Arrays.asList("addObject", "borrowObject", "clear", "clear", "close", "getKeys", "getNumActive", "getNumActive", "getNumIdle", "getNumIdle",
"invalidateObject", "returnObject", "toString");
}
private static <K, V> List<String> invokeEveryMethod(final KeyedPooledObjectFactory<K, V, RuntimeException> kpof) {
kpof.activateObject(null, null);
kpof.destroyObject(null, null);
kpof.makeObject(null);
kpof.passivateObject(null, null);
kpof.validateObject(null, null);
kpof.toString();
return Arrays.asList("activateObject", "destroyObject", "makeObject", "passivateObject", "validateObject", "toString");
}
private static List<String> invokeEveryMethod(final ObjectPool<Object, RuntimeException> op) {
op.addObject();
op.borrowObject();
op.clear();
op.close();
op.getNumActive();
op.getNumIdle();
op.invalidateObject(new Object());
op.returnObject(new Object());
op.toString();
return Arrays.asList("addObject", "borrowObject", "clear", "close", "getNumActive", "getNumIdle", "invalidateObject",
"returnObject", "toString");
}
private static <T, E extends Exception> List<String> invokeEveryMethod(final PooledObjectFactory<T, E> pof) throws E {
pof.activateObject(null);
pof.destroyObject(null);
pof.makeObject();
pof.passivateObject(null);
pof.validateObject(null);
pof.toString();
return Arrays.asList("activateObject", "destroyObject", "makeObject", "passivateObject", "validateObject", "toString");
}
@Test
public void testCheckMinIdleKeyedObjectPool() throws InterruptedException {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.checkMinIdle(null, new Object(), 1, 1),
"PoolUtils.checkMinIdle(KeyedObjectPool,Object,int,long) must not allow null pool.");
try (@SuppressWarnings("unchecked")
final KeyedObjectPool<Object, Object, RuntimeException> pool = createProxy(KeyedObjectPool.class, (List<String>) null)) {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.checkMinIdle(pool, (Object) null, 1, 1),
"PoolUtils.checkMinIdle(KeyedObjectPool,Object,int,long) must not accept null keys.");
}
try (@SuppressWarnings("unchecked")
final KeyedObjectPool<Object, Object, RuntimeException> pool = createProxy(KeyedObjectPool.class, (List<String>) null)) {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.checkMinIdle(pool, new Object(), -1, 1),
"PoolUtils.checkMinIdle(KeyedObjectPool,Object,int,long) must not accept negative min idle values.");
}
final List<String> calledMethods = new ArrayList<>();
final Object key = new Object();
// Test that the minIdle check doesn't add too many idle objects
@SuppressWarnings("unchecked")
final KeyedPooledObjectFactory<Object, Object, RuntimeException> kpof = createProxy(KeyedPooledObjectFactory.class, calledMethods);
try (final KeyedObjectPool<Object, Object, RuntimeException> kop = new GenericKeyedObjectPool<>(kpof)) {
PoolUtils.checkMinIdle(kop, key, 2, 100);
Thread.sleep(400);
assertEquals(2, kop.getNumIdle(key));
assertEquals(2, kop.getNumIdle());
}
int makeObjectCount = 0;
for (String methodName : calledMethods) {
if ("makeObject".equals(methodName)) {
makeObjectCount++;
}
}
assertEquals(2, makeObjectCount, "makeObject should have been called two time");
// Because this isn't deterministic and you can get false failures, try more than once.
AssertionFailedError afe = null;
int triesLeft = 3;
do {
afe = null;
try {
calledMethods.clear();
try (@SuppressWarnings("unchecked")
final KeyedObjectPool<Object, Object, RuntimeException> pool = createProxy(KeyedObjectPool.class, calledMethods)) {
// checks minIdle immediately
final TimerTask task = PoolUtils.checkMinIdle(pool, key, 1, CHECK_PERIOD);
Thread.sleep(CHECK_SLEEP_PERIOD); // will check CHECK_COUNT more times.
task.cancel();
task.toString();
final List<String> expectedMethods = new ArrayList<>();
for (int i = 0; i < CHECK_COUNT; i++) {
expectedMethods.add("getNumIdle");
expectedMethods.add("addObject");
}
expectedMethods.add("toString");
assertEquals(expectedMethods, calledMethods); // may fail because of the thread scheduler
}
} catch (final AssertionFailedError e) {
afe = e;
}
} while (--triesLeft > 0 && afe != null);
if (afe != null) {
throw afe;
}
}
@Test
public void testCheckMinIdleKeyedObjectPoolKeys() throws InterruptedException {
// Because this isn't deterministic and you can get false failures, try more than once.
AssertionFailedError afe = null;
int triesLeft = 3;
do {
afe = null;
final List<String> calledMethods = new ArrayList<>();
try (@SuppressWarnings("unchecked")
final KeyedObjectPool<String, Object, RuntimeException> pool = createProxy(KeyedObjectPool.class, calledMethods)) {
final Collection<String> keys = new ArrayList<>(2);
keys.add("one");
keys.add("two");
// checks minIdle immediately
final Map<String, TimerTask> tasks = PoolUtils.checkMinIdle(pool, keys, 1, CHECK_PERIOD);
Thread.sleep(CHECK_SLEEP_PERIOD); // will check CHECK_COUNT more times.
tasks.values().forEach(TimerTask::cancel);
final List<String> expectedMethods = new ArrayList<>();
for (int i = 0; i < CHECK_COUNT * keys.size(); i++) {
expectedMethods.add("getNumIdle");
expectedMethods.add("addObject");
}
assertEquals(expectedMethods, calledMethods); // may fail because of the thread scheduler
} catch (final AssertionFailedError e) {
afe = e;
}
} while (--triesLeft > 0 && afe != null);
if (afe != null) {
throw afe;
}
}
@Test
public void testCheckMinIdleKeyedObjectPoolKeysNulls() {
try (@SuppressWarnings("unchecked")
final KeyedObjectPool<Object, Object, RuntimeException> pool = createProxy(KeyedObjectPool.class, (List<String>) null)) {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.checkMinIdle(pool, (Collection<?>) null, 1, 1),
"PoolUtils.checkMinIdle(KeyedObjectPool,Collection,int,long) must not accept null keys.");
}
try (@SuppressWarnings("unchecked")
final KeyedObjectPool<Object, Object, RuntimeException> pool = createProxy(KeyedObjectPool.class, (List<String>) null)) {
PoolUtils.checkMinIdle(pool, (Collection<?>) Collections.emptyList(), 1, 1);
} catch (final IllegalArgumentException iae) {
fail("PoolUtils.checkMinIdle(KeyedObjectPool,Collection,int,long) must accept empty lists.");
}
}
@Test
public void testCheckMinIdleObjectPool() throws InterruptedException {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.checkMinIdle(null, 1, 1),
"PoolUtils.checkMinIdle(ObjectPool,,) must not allow null pool.");
try (@SuppressWarnings("unchecked")
final ObjectPool<Object, RuntimeException> pool = createProxy(ObjectPool.class, (List<String>) null)) {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.checkMinIdle(pool, -1, 1),
"PoolUtils.checkMinIdle(ObjectPool,,) must not accept negative min idle values.");
}
final List<String> calledMethods = new ArrayList<>();
// Test that the minIdle check doesn't add too many idle objects
@SuppressWarnings("unchecked")
final PooledObjectFactory<Object, RuntimeException> pof = createProxy(PooledObjectFactory.class, calledMethods);
try (final ObjectPool<Object, RuntimeException> op = new GenericObjectPool<>(pof)) {
PoolUtils.checkMinIdle(op, 2, 100);
Thread.sleep(1000);
assertEquals(2, op.getNumIdle());
}
int makeObjectCount = 0;
for (String methodName : calledMethods) {
if ("makeObject".equals(methodName)) {
makeObjectCount++;
}
}
assertEquals(2, makeObjectCount, "makeObject should have been called two time");
// Because this isn't deterministic and you can get false failures, try more than once.
AssertionFailedError afe = null;
int triesLeft = 3;
do {
afe = null;
try {
calledMethods.clear();
try (@SuppressWarnings("unchecked")
final ObjectPool<Object, RuntimeException> pool = createProxy(ObjectPool.class, calledMethods)) {
final TimerTask task = PoolUtils.checkMinIdle(pool, 1, CHECK_PERIOD); // checks minIdle immediately
Thread.sleep(CHECK_SLEEP_PERIOD); // will check CHECK_COUNT more times.
task.cancel();
task.toString();
final List<String> expectedMethods = new ArrayList<>();
for (int i = 0; i < CHECK_COUNT; i++) {
expectedMethods.add("getNumIdle");
expectedMethods.add("addObject");
}
expectedMethods.add("toString");
assertEquals(expectedMethods, calledMethods); // may fail because of the thread scheduler
}
} catch (final AssertionFailedError e) {
afe = e;
}
} while (--triesLeft > 0 && afe != null);
if (afe != null) {
throw afe;
}
}
@Test
public void testCheckRethrow() {
assertDoesNotThrow(() -> PoolUtils.checkRethrow(new Exception()),
"PoolUtils.checkRethrow(Throwable) must rethrow only ThreadDeath and VirtualMachineError.");
assertThrows(ThreadDeath.class, () -> PoolUtils.checkRethrow(new ThreadDeath()),
"PoolUtils.checkRethrow(Throwable) must rethrow only ThreadDeath and VirtualMachineError.");
assertThrows(VirtualMachineError.class, () -> PoolUtils.checkRethrow(new InternalError()),
"PoolUtils.checkRethrow(Throwable) must rethrow only ThreadDeath and VirtualMachineError.");
}
@Test
public void testErodingObjectPoolDefaultFactor() {
try (@SuppressWarnings("unchecked")
final ObjectPool<Object, RuntimeException> internalPool = createProxy(ObjectPool.class, (arg0, arg1, arg2) -> null);
final ObjectPool<Object, RuntimeException> pool = PoolUtils.erodingPool(internalPool)) {
final String expectedToString = "ErodingObjectPool{factor=ErodingFactor{factor=1.0, idleHighWaterMark=1}, pool=" +
internalPool + "}";
// The factor is not exposed, but will be printed in the toString() method
// In this case since we didn't pass one, the default 1.0f will be printed
assertEquals(expectedToString, pool.toString());
}
}
@Test
public void testErodingPerKeyKeyedObjectPool() throws InterruptedException {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool((KeyedObjectPool<Object, Object, RuntimeException>) null, 1f, true),
"PoolUtils.erodingPool(KeyedObjectPool) must not allow a null pool.");
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool((KeyedObjectPool<Object, Object, RuntimeException>) null, 0f, true),
"PoolUtils.erodingPool(ObjectPool, float, boolean) must not allow a non-positive factor.");
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool((KeyedObjectPool<Object, Object, RuntimeException>) null, 1f, true),
"PoolUtils.erodingPool(KeyedObjectPool, float, boolean) must not allow a null pool.");
final List<String> calledMethods = new ArrayList<>();
final InvocationHandler handler = new MethodCallLogger(calledMethods) {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
Object o = super.invoke(proxy, method, args);
if (o instanceof Integer) {
// so getNumActive/getNumIdle are not zero.
o = Integer.valueOf(1);
}
return o;
}
};
// If the logic behind PoolUtils.erodingPool changes then this will need to be tweaked.
final float factor = 0.01f; // about ~9 seconds until first discard
try (@SuppressWarnings("unchecked")
final KeyedObjectPool<Object, Object, RuntimeException> pool = PoolUtils.erodingPool(createProxy(KeyedObjectPool.class, handler), factor, true)) {
final List<String> expectedMethods = new ArrayList<>();
assertEquals(expectedMethods, calledMethods);
final Object key = "key";
Object o = pool.borrowObject(key);
expectedMethods.add("borrowObject");
assertEquals(expectedMethods, calledMethods);
pool.returnObject(key, o);
expectedMethods.add("returnObject");
assertEquals(expectedMethods, calledMethods);
for (int i = 0; i < 5; i++) {
o = pool.borrowObject(key);
expectedMethods.add("borrowObject");
Thread.sleep(50);
pool.returnObject(key, o);
expectedMethods.add("returnObject");
assertEquals(expectedMethods, calledMethods);
expectedMethods.clear();
calledMethods.clear();
}
Thread.sleep(10000); // 10 seconds
o = pool.borrowObject(key);
expectedMethods.add("borrowObject");
pool.returnObject(key, o);
expectedMethods.add("getNumIdle");
expectedMethods.add("invalidateObject");
assertEquals(expectedMethods, calledMethods);
final String expectedToString = "ErodingPerKeyKeyedObjectPool{factor=" + factor + ", keyedPool=null}";
assertEquals(expectedToString, pool.toString());
}
}
@Test
public void testErodingPoolKeyedObjectPool() throws InterruptedException {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool((KeyedObjectPool<Object, Object, RuntimeException>) null),
"PoolUtils.erodingPool(KeyedObjectPool) must not allow a null pool.");
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool((KeyedObjectPool<Object, Object, RuntimeException>) null, 1f),
"PoolUtils.erodingPool(KeyedObjectPool, float) must not allow a null pool.");
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool((KeyedObjectPool<Object, Object, RuntimeException>) null, 1f, true),
"PoolUtils.erodingPool(KeyedObjectPool, float, boolean) must not allow a null pool.");
final List<String> calledMethods = new ArrayList<>();
final InvocationHandler handler = new MethodCallLogger(calledMethods) {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
Object o = super.invoke(proxy, method, args);
if (o instanceof Integer) {
// so getNumActive/getNumIdle are not zero.
o = Integer.valueOf(1);
}
return o;
}
};
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool(createProxy(KeyedObjectPool.class, handler), 0f),
"PoolUtils.erodingPool(ObjectPool, float) must not allow a non-positive factor.");
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool(createProxy(KeyedObjectPool.class, handler), 0f, false),
"PoolUtils.erodingPool(ObjectPool, float, boolean) must not allow a non-positive factor.");
// If the logic behind PoolUtils.erodingPool changes then this will need to be tweaked.
final float factor = 0.01f; // about ~9 seconds until first discard
final List<String> expectedMethods = new ArrayList<>();
try (@SuppressWarnings("unchecked")
final KeyedObjectPool<Object, Object, RuntimeException> pool = PoolUtils.erodingPool(createProxy(KeyedObjectPool.class, handler), factor)) {
assertEquals(expectedMethods, calledMethods);
final Object key = "key";
pool.addObject(key);
expectedMethods.add("addObject");
Object o = pool.borrowObject(key);
expectedMethods.add("borrowObject");
assertEquals(expectedMethods, calledMethods);
pool.returnObject(key, o);
expectedMethods.add("returnObject");
assertEquals(expectedMethods, calledMethods);
// the invocation handler always returns 1
assertEquals(1, pool.getNumActive());
expectedMethods.add("getNumActive");
assertEquals(1, pool.getNumIdle());
expectedMethods.add("getNumIdle");
for (int i = 0; i < 5; i++) {
o = pool.borrowObject(key);
expectedMethods.add("borrowObject");
Thread.sleep(50);
pool.returnObject(key, o);
expectedMethods.add("returnObject");
assertEquals(expectedMethods, calledMethods);
expectedMethods.clear();
calledMethods.clear();
}
Thread.sleep(10000); // 10 seconds
o = pool.borrowObject(key);
expectedMethods.add("borrowObject");
pool.returnObject(key, o);
expectedMethods.add("getNumIdle");
expectedMethods.add("invalidateObject");
pool.clear();
}
expectedMethods.add("clear");
expectedMethods.add("close");
assertEquals(expectedMethods, calledMethods);
}
@Test
public void testErodingPoolKeyedObjectPoolDefaultFactor() {
try (@SuppressWarnings("unchecked")
final KeyedObjectPool<Object, Object, RuntimeException> internalPool = createProxy(KeyedObjectPool.class,
(arg0, arg1, arg2) -> null);
final KeyedObjectPool<Object, Object, RuntimeException> pool = PoolUtils.erodingPool(internalPool)) {
final String expectedToString = "ErodingKeyedObjectPool{factor=ErodingFactor{factor=1.0, idleHighWaterMark=1}, keyedPool=" +
internalPool + "}";
// The factor is not exposed, but will be printed in the toString() method
// In this case since we didn't pass one, the default 1.0f will be printed
assertEquals(expectedToString, pool.toString());
}
}
@Test
public void testErodingPoolObjectPool() throws InterruptedException {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool((ObjectPool<Object, RuntimeException>) null),
"PoolUtils.erodingPool(ObjectPool) must not allow a null pool.");
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool((ObjectPool<Object, RuntimeException>) null, 1f),
"PoolUtils.erodingPool(ObjectPool, float) must not allow a null pool.");
final List<String> calledMethods = new ArrayList<>();
final InvocationHandler handler = new MethodCallLogger(calledMethods) {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
Object o = super.invoke(proxy, method, args);
if (o instanceof Integer) {
// so getNumActive/getNumIdle are not zero.
o = Integer.valueOf(1);
}
return o;
}
};
assertThrows(IllegalArgumentException.class, () -> PoolUtils.erodingPool(createProxy(ObjectPool.class, handler), -1f),
"PoolUtils.erodingPool(ObjectPool, float) must not allow a non-positive factor.");
// If the logic behind PoolUtils.erodingPool changes then this will need to be tweaked.
final float factor = 0.01f; // about ~9 seconds until first discard
final List<String> expectedMethods = new ArrayList<>();
try (@SuppressWarnings("unchecked")
final ObjectPool<Object, RuntimeException> pool = PoolUtils.erodingPool(createProxy(ObjectPool.class, handler), factor)) {
assertEquals(expectedMethods, calledMethods);
pool.addObject();
expectedMethods.add("addObject");
Object o = pool.borrowObject();
expectedMethods.add("borrowObject");
assertEquals(expectedMethods, calledMethods);
pool.returnObject(o);
expectedMethods.add("returnObject");
assertEquals(expectedMethods, calledMethods);
// the invocation handler always returns 1
assertEquals(1, pool.getNumActive());
expectedMethods.add("getNumActive");
assertEquals(1, pool.getNumIdle());
expectedMethods.add("getNumIdle");
for (int i = 0; i < 5; i++) {
o = pool.borrowObject();
expectedMethods.add("borrowObject");
Thread.sleep(50);
pool.returnObject(o);
expectedMethods.add("returnObject");
assertEquals(expectedMethods, calledMethods);
expectedMethods.clear();
calledMethods.clear();
}
Thread.sleep(10000); // 10 seconds
o = pool.borrowObject();
expectedMethods.add("borrowObject");
pool.returnObject(o);
expectedMethods.add("getNumIdle");
expectedMethods.add("invalidateObject");
pool.clear();
}
expectedMethods.add("clear");
expectedMethods.add("close");
assertEquals(expectedMethods, calledMethods);
}
@Test
public void testJavaBeanInstantiation() {
assertNotNull(new PoolUtils());
}
@Test
public void testSynchronizedPoolableFactoryKeyedPooledObjectFactory() {
assertThrows(IllegalArgumentException.class,
() -> PoolUtils.synchronizedKeyedPooledFactory((KeyedPooledObjectFactory<Object, Object, RuntimeException>) null),
"PoolUtils.synchronizedPoolableFactory(KeyedPooledObjectFactory) must not allow a null factory.");
final List<String> calledMethods = new ArrayList<>();
@SuppressWarnings("unchecked")
final KeyedPooledObjectFactory<Object, Object, RuntimeException> kpof = createProxy(KeyedPooledObjectFactory.class, calledMethods);
final KeyedPooledObjectFactory<Object, Object, RuntimeException> skpof = PoolUtils.synchronizedKeyedPooledFactory(kpof);
final List<String> expectedMethods = invokeEveryMethod(skpof);
assertEquals(expectedMethods, calledMethods);
// TODO: Anyone feel motivated to construct a test that verifies proper synchronization?
}
@Test
public void testSynchronizedPoolableFactoryPoolableObjectFactory() throws Exception {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.synchronizedPooledFactory((PooledObjectFactory<Object, Exception>) null),
"PoolUtils.synchronizedPoolableFactory(PoolableObjectFactory) must not allow a null factory.");
final List<String> calledMethods = new ArrayList<>();
@SuppressWarnings("unchecked")
final PooledObjectFactory<Object, Exception> pof = createProxy(PooledObjectFactory.class, calledMethods);
final PooledObjectFactory<Object, Exception> spof = PoolUtils.synchronizedPooledFactory(pof);
final List<String> expectedMethods = invokeEveryMethod(spof);
assertEquals(expectedMethods, calledMethods);
// TODO: Anyone feel motivated to construct a test that verifies proper synchronization?
}
@Test
public void testSynchronizedPoolKeyedObjectPool() {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.synchronizedPool((KeyedObjectPool<Object, Object, RuntimeException>) null),
"PoolUtils.synchronizedPool(KeyedObjectPool) must not allow a null pool.");
final List<String> calledMethods = new ArrayList<>();
try (@SuppressWarnings("unchecked")
final KeyedObjectPool<Object, Object, RuntimeException> kop = createProxy(KeyedObjectPool.class, calledMethods);
final KeyedObjectPool<Object, Object, RuntimeException> skop = PoolUtils.synchronizedPool(kop)) {
final List<String> expectedMethods = invokeEveryMethod(skop);
assertEquals(expectedMethods, calledMethods);
}
// TODO: Anyone feel motivated to construct a test that verifies proper synchronization?
}
@Test
public void testSynchronizedPoolObjectPool() {
assertThrows(IllegalArgumentException.class, () -> PoolUtils.synchronizedPool((ObjectPool<Object, RuntimeException>) null),
"PoolUtils.synchronizedPool(ObjectPool) must not allow a null pool.");
final List<String> calledMethods = new ArrayList<>();
try (@SuppressWarnings("unchecked")
final ObjectPool<Object, RuntimeException> op = createProxy(ObjectPool.class, calledMethods); final ObjectPool<Object, RuntimeException> sop = PoolUtils.synchronizedPool(op)) {
final List<String> expectedMethods = invokeEveryMethod(sop);
assertEquals(expectedMethods, calledMethods);
// TODO: Anyone feel motivated to construct a test that verifies proper synchronization?
}
}
/**
* Tests the {@link PoolUtils} timer holder.
*/
@Test
public void testTimerHolder() {
final PoolUtils.TimerHolder h = new PoolUtils.TimerHolder();
assertNotNull(h);
assertNotNull(PoolUtils.TimerHolder.MIN_IDLE_TIMER);
}
}
| 5,194 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/VisitTrackerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
import org.apache.commons.pool3.impl.DefaultPooledObject;
/**
* Factory that creates VisitTracker instances. Used to test Evictor runs.
*
* @param <K> The VisitTracker key type.
*/
public class VisitTrackerFactory<K>
implements PooledObjectFactory<VisitTracker<K>, RuntimeException>, KeyedPooledObjectFactory<K, VisitTracker<K>, RuntimeException> {
private int nextId;
@Override
public void activateObject(final K key, final PooledObject<VisitTracker<K>> ref) {
ref.getObject().activate();
}
@Override
public void activateObject(final PooledObject<VisitTracker<K>> ref) {
ref.getObject().activate();
}
@Override
public void destroyObject(final K key, final PooledObject<VisitTracker<K>> ref) {
ref.getObject().destroy();
}
@Override
public void destroyObject(final PooledObject<VisitTracker<K>> ref) {
ref.getObject().destroy();
}
@Override
public PooledObject<VisitTracker<K>> makeObject() {
return new DefaultPooledObject<>(new VisitTracker<>(nextId++));
}
@Override
public PooledObject<VisitTracker<K>> makeObject(final K key) {
return new DefaultPooledObject<>(new VisitTracker<>(nextId++, key));
}
@Override
public void passivateObject(final K key, final PooledObject<VisitTracker<K>> ref) {
ref.getObject().passivate();
}
@Override
public void passivateObject(final PooledObject<VisitTracker<K>> ref) {
ref.getObject().passivate();
}
public void resetId() {
nextId = 0;
}
@Override
public boolean validateObject(final K key, final PooledObject<VisitTracker<K>> ref) {
return ref.getObject().validate();
}
@Override
public boolean validateObject(final PooledObject<VisitTracker<K>> ref) {
return ref.getObject().validate();
}
}
| 5,195 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/VisitTracker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
/**
* Test pooled object class. Keeps track of how many times it has been validated, activated, passivated.
*
* @param <K> The key type.
*/
public class VisitTracker<K> {
private int validateCount;
private int activateCount;
private int passivateCount;
private boolean destroyed;
private int id;
private K key;
public VisitTracker() {
reset();
}
public VisitTracker(final int id) {
this.id = id;
reset();
}
public VisitTracker(final int id, final K key) {
this.id = id;
this.key = key;
reset();
}
public void activate() {
if (destroyed) {
fail("attempted to activate a destroyed object");
}
activateCount++;
}
public void destroy() {
destroyed = true;
}
private void fail(final String message) {
throw new IllegalStateException(message);
}
public int getActivateCount() {
return activateCount;
}
public int getId() {
return id;
}
public K getKey() {
return key;
}
public int getPassivateCount() {
return passivateCount;
}
public int getValidateCount() {
return validateCount;
}
public boolean isDestroyed() {
return destroyed;
}
public void passivate() {
if (destroyed) {
fail("attempted to passivate a destroyed object");
}
passivateCount++;
}
public void reset() {
validateCount = 0;
activateCount = 0;
passivateCount = 0;
destroyed = false;
}
@Override
public String toString() {
return "Key: " + key + " id: " + id;
}
public boolean validate() {
if (destroyed) {
fail("attempted to validate a destroyed object");
}
validateCount++;
return true;
}
}
| 5,196 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/PoolTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.time.Duration;
import org.apache.commons.pool3.impl.DefaultPooledObject;
import org.apache.commons.pool3.impl.GenericObjectPool;
import org.apache.commons.pool3.impl.GenericObjectPoolConfig;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@Disabled
public class PoolTest {
private static final class Foo {
}
private static final class PooledFooFactory implements PooledObjectFactory<Foo, RuntimeException> {
private static final long VALIDATION_WAIT_IN_MILLIS = 1000;
@Override
public void activateObject(final PooledObject<Foo> pooledObject) {
}
@Override
public void destroyObject(final PooledObject<Foo> pooledObject) {
}
@Override
public PooledObject<Foo> makeObject() {
return new DefaultPooledObject<>(new Foo());
}
@Override
public void passivateObject(final PooledObject<Foo> pooledObject) {
}
@Override
public boolean validateObject(final PooledObject<Foo> pooledObject) {
try {
Thread.sleep(VALIDATION_WAIT_IN_MILLIS);
} catch (final InterruptedException e) {
Thread.interrupted();
}
return false;
}
}
private static final CharSequence COMMONS_POOL_EVICTIONS_TIMER_THREAD_NAME = "commons-pool-EvictionTimer";
private static final long EVICTION_PERIOD_IN_MILLIS = 100;
private static final Duration EVICTION_DURATION = Duration.ofMillis(100);
@Test
public void testPool() {
final GenericObjectPoolConfig<Foo> poolConfig = new GenericObjectPoolConfig<>();
poolConfig.setTestWhileIdle(true /* testWhileIdle */);
final PooledFooFactory pooledFooFactory = new PooledFooFactory();
try (GenericObjectPool<Foo, RuntimeException> pool = new GenericObjectPool<>(pooledFooFactory, poolConfig)) {
pool.setDurationBetweenEvictionRuns(EVICTION_DURATION);
assertEquals(EVICTION_PERIOD_IN_MILLIS, pool.getDurationBetweenEvictionRuns().toMillis());
assertEquals(EVICTION_PERIOD_IN_MILLIS, pool.getDurationBetweenEvictionRuns().toMillis());
pool.setDurationBetweenEvictionRuns(Duration.ofMillis(EVICTION_PERIOD_IN_MILLIS));
assertEquals(EVICTION_PERIOD_IN_MILLIS, pool.getDurationBetweenEvictionRuns().toMillis());
pool.addObject();
try {
Thread.sleep(EVICTION_PERIOD_IN_MILLIS);
} catch (final InterruptedException e) {
Thread.interrupted();
}
}
final Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
for (final Thread thread : threads) {
if (thread == null) {
continue;
}
final String name = thread.getName();
assertFalse( name.contains(COMMONS_POOL_EVICTIONS_TIMER_THREAD_NAME),name);
}
}
} | 5,197 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/TestException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
/**
* A custom exception for unit tests.
*/
public class TestException extends Exception {
private static final long serialVersionUID = 1L;
public TestException() {
// empty
}
public TestException(final String message) {
super(message);
}
public TestException(final String message, final Throwable cause) {
super(message, cause);
}
public TestException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public TestException(final Throwable cause) {
super(cause);
}
}
| 5,198 |
0 | Create_ds/commons-pool/src/test/java/org/apache/commons | Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/PrivateException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.pool3;
/**
* An exception that only is thrown by these tests.
*/
public class PrivateException extends RuntimeException {
private static final long serialVersionUID = 1L;
public PrivateException(final String message) {
super(message);
}
}
| 5,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.