index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/model/CannedSignerRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.model; import java.nio.file.Path; import java.security.PrivateKey; import java.time.Instant; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.cloudfront.internal.utils.SigningUtils; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Request to generate CloudFront signed URLs or signed cookies with a canned policy */ @Immutable @ThreadSafe @SdkPublicApi public final class CannedSignerRequest implements CloudFrontSignerRequest, ToCopyableBuilder<CannedSignerRequest.Builder, CannedSignerRequest> { private final String resourceUrl; private final PrivateKey privateKey; private final String keyPairId; private final Instant expirationDate; private CannedSignerRequest(DefaultBuilder builder) { this.resourceUrl = builder.resourceUrl; this.privateKey = builder.privateKey; this.keyPairId = builder.keyPairId; this.expirationDate = builder.expirationDate; } /** * Create a builder that can be used to create a {@link CannedSignerRequest} */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public String resourceUrl() { return resourceUrl; } @Override public PrivateKey privateKey() { return privateKey; } @Override public String keyPairId() { return keyPairId; } @Override public Instant expirationDate() { return expirationDate; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CannedSignerRequest cookie = (CannedSignerRequest) o; return Objects.equals(resourceUrl, cookie.resourceUrl) && Objects.equals(privateKey, cookie.privateKey) && Objects.equals(keyPairId, cookie.keyPairId) && Objects.equals(expirationDate, cookie.expirationDate); } @Override public int hashCode() { int result = resourceUrl != null ? resourceUrl.hashCode() : 0; result = 31 * result + (privateKey != null ? privateKey.hashCode() : 0); result = 31 * result + (keyPairId != null ? keyPairId.hashCode() : 0); result = 31 * result + (expirationDate != null ? expirationDate.hashCode() : 0); return result; } @NotThreadSafe @SdkPublicApi public interface Builder extends CopyableBuilder<CannedSignerRequest.Builder, CannedSignerRequest> { /** * Configure the resource URL to be signed * <p> * The URL or path that uniquely identifies a resource within a * distribution. For standard distributions the resource URL will * be <tt>"http://" + distributionName + "/" + objectKey</tt> * (may also include URL parameters. For distributions with the * HTTPS required protocol, the resource URL must start with * <tt>"https://"</tt> */ Builder resourceUrl(String resourceUrl); /** * Configure the private key to be used to sign the policy. * Takes a PrivateKey object directly */ Builder privateKey(PrivateKey privateKey); /** * Configure the private key to be used to sign the policy. * Takes a Path to the key file, and loads it to return a PrivateKey object */ Builder privateKey(Path keyFile) throws Exception; /** * Configure the ID of the key pair stored in the AWS account */ Builder keyPairId(String keyPairId); /** * Configure the expiration date of the signed URL or signed cookie */ Builder expirationDate(Instant expirationDate); } private static final class DefaultBuilder implements Builder { private String resourceUrl; private PrivateKey privateKey; private String keyPairId; private Instant expirationDate; private DefaultBuilder() { } private DefaultBuilder(CannedSignerRequest request) { this.resourceUrl = request.resourceUrl; this.privateKey = request.privateKey; this.keyPairId = request.keyPairId; this.expirationDate = request.expirationDate; } @Override public Builder resourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; return this; } @Override public Builder privateKey(PrivateKey privateKey) { this.privateKey = privateKey; return this; } @Override public Builder privateKey(Path keyFile) throws Exception { this.privateKey = SigningUtils.loadPrivateKey(keyFile); return this; } @Override public Builder keyPairId(String keyPairId) { this.keyPairId = keyPairId; return this; } @Override public Builder expirationDate(Instant expirationDate) { this.expirationDate = expirationDate; return this; } @Override public CannedSignerRequest build() { return new CannedSignerRequest(this); } } }
4,700
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/model/CustomSignerRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.model; import java.nio.file.Path; import java.security.PrivateKey; import java.time.Instant; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.cloudfront.internal.utils.SigningUtils; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Request to generate CloudFront signed URLs or signed cookies with a custom policy */ @Immutable @ThreadSafe @SdkPublicApi public final class CustomSignerRequest implements CloudFrontSignerRequest, ToCopyableBuilder<CustomSignerRequest.Builder, CustomSignerRequest> { private final String resourceUrl; private final PrivateKey privateKey; private final String keyPairId; private final Instant expirationDate; private final Instant activeDate; private final String ipRange; private CustomSignerRequest(DefaultBuilder builder) { this.resourceUrl = builder.resourceUrl; this.privateKey = builder.privateKey; this.keyPairId = builder.keyPairId; this.expirationDate = builder.expirationDate; this.activeDate = builder.activeDate; this.ipRange = builder.ipRange; } /** * Create a builder that can be used to create a {@link CustomSignerRequest} */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public String resourceUrl() { return resourceUrl; } @Override public PrivateKey privateKey() { return privateKey; } @Override public String keyPairId() { return keyPairId; } @Override public Instant expirationDate() { return expirationDate; } /** * Returns the active date, before which users will not yet be able to use the signed URL/cookie to access your private * content */ public Instant activeDate() { return activeDate; } /** * Returns the IP range of the users allowed to access your private content */ public String ipRange() { return ipRange; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomSignerRequest cookie = (CustomSignerRequest) o; return Objects.equals(resourceUrl, cookie.resourceUrl) && Objects.equals(privateKey, cookie.privateKey) && Objects.equals(keyPairId, cookie.keyPairId) && Objects.equals(expirationDate, cookie.expirationDate) && Objects.equals(activeDate, cookie.activeDate) && Objects.equals(ipRange, cookie.ipRange); } @Override public int hashCode() { int result = resourceUrl != null ? resourceUrl.hashCode() : 0; result = 31 * result + (privateKey != null ? privateKey.hashCode() : 0); result = 31 * result + (keyPairId != null ? keyPairId.hashCode() : 0); result = 31 * result + (expirationDate != null ? expirationDate.hashCode() : 0); result = 31 * result + (activeDate != null ? activeDate.hashCode() : 0); result = 31 * result + (ipRange != null ? ipRange.hashCode() : 0); return result; } @NotThreadSafe @SdkPublicApi public interface Builder extends CopyableBuilder<CustomSignerRequest.Builder, CustomSignerRequest> { /** * Configure the resource URL to be signed * <p> * The URL or path that uniquely identifies a resource within a * distribution. For standard distributions the resource URL will * be <tt>"http://" + distributionName + "/" + objectKey</tt> * (may also include URL parameters. For distributions with the * HTTPS required protocol, the resource URL must start with * <tt>"https://"</tt> */ Builder resourceUrl(String resourceUrl); /** * Configure the private key to be used to sign the policy. * Takes a PrivateKey object directly */ Builder privateKey(PrivateKey privateKey); /** * Configure the private key to be used to sign the policy. * Takes a Path to the key file, and loads it to return a PrivateKey object */ Builder privateKey(Path keyFile) throws Exception; /** * Configure the ID of the key pair stored in the AWS account */ Builder keyPairId(String keyPairId); /** * Configure the expiration date of the signed URL or signed cookie */ Builder expirationDate(Instant expirationDate); /** * Configure the active date of the signed URL or signed cookie - for custom policies (optional field) */ Builder activeDate(Instant activeDate); /** * Configure the IP range of the signed URL or signed cookie - for custom policies (optional field) * <p> * The allowed IP address range of the client making the GET * request, in IPv4 CIDR form (e.g. 192.168.0.1/24). * IPv6 format is not supported. */ Builder ipRange(String ipRange); } private static final class DefaultBuilder implements Builder { private String resourceUrl; private PrivateKey privateKey; private String keyPairId; private Instant expirationDate; private Instant activeDate; private String ipRange; private DefaultBuilder() { } private DefaultBuilder(CustomSignerRequest request) { this.resourceUrl = request.resourceUrl; this.privateKey = request.privateKey; this.keyPairId = request.keyPairId; this.expirationDate = request.expirationDate; this.activeDate = request.activeDate; this.ipRange = request.ipRange; } @Override public Builder resourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; return this; } @Override public Builder privateKey(PrivateKey privateKey) { this.privateKey = privateKey; return this; } @Override public Builder privateKey(Path keyFile) throws Exception { this.privateKey = SigningUtils.loadPrivateKey(keyFile); return this; } @Override public Builder keyPairId(String keyPairId) { this.keyPairId = keyPairId; return this; } @Override public Builder expirationDate(Instant expirationDate) { this.expirationDate = expirationDate; return this; } @Override public Builder activeDate(Instant activeDate) { this.activeDate = activeDate; return this; } @Override public Builder ipRange(String ipRange) { this.ipRange = ipRange; return this; } @Override public CustomSignerRequest build() { return new CustomSignerRequest(this); } } }
4,701
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/cookie/CookiesForCustomPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.cookie; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Base interface class for CloudFront cookies with custom policies */ @SdkPublicApi public interface CookiesForCustomPolicy extends SignedCookie, ToCopyableBuilder<CookiesForCustomPolicy.Builder, CookiesForCustomPolicy> { /** * Returns the cookie policy header value that can be appended to an HTTP GET request * i.e., "CloudFront-Policy=[POLICY_VALUE]" */ String policyHeaderValue(); @NotThreadSafe interface Builder extends CopyableBuilder<CookiesForCustomPolicy.Builder, CookiesForCustomPolicy> { /** * Configure the resource URL */ Builder resourceUrl(String resourceUrl); /** * Configure the cookie signature header value */ Builder signatureHeaderValue(String signatureHeaderValue); /** * Configure the cookie key pair ID header value */ Builder keyPairIdHeaderValue(String keyPairIdHeaderValue); /** * Configure the cookie policy header value */ Builder policyHeaderValue(String policyHeaderValue); } }
4,702
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/cookie/SignedCookie.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.cookie; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpRequest; /** * Base interface class for CloudFront signed cookies */ @Immutable @ThreadSafe @SdkPublicApi public interface SignedCookie { String COOKIE = "Cookie"; /** * Returns the resource URL */ String resourceUrl(); /** * Generates an HTTP GET request that can be executed by an HTTP client to access the resource */ SdkHttpRequest createHttpGetRequest(); /** * Returns the cookie signature header value that can be appended to an HTTP GET request * i.e., "CloudFront-Signature=[SIGNATURE_VALUE]" */ String signatureHeaderValue(); /** * Returns the cookie key-pair-Id header value that can be appended to an HTTP GET request * i.e., "CloudFront-Key-Pair-Id=[KEY_PAIR_ID_VALUE]" */ String keyPairIdHeaderValue(); }
4,703
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/cookie/CookiesForCannedPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.cookie; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Base interface class for CloudFront cookies with canned policies */ @SdkPublicApi public interface CookiesForCannedPolicy extends SignedCookie, ToCopyableBuilder<CookiesForCannedPolicy.Builder, CookiesForCannedPolicy> { /** * Returns the cookie expires header value that can be appended to an HTTP GET request * i.e., "CloudFront-Expires=[EXPIRES_VALUE]" */ String expiresHeaderValue(); @NotThreadSafe interface Builder extends CopyableBuilder<CookiesForCannedPolicy.Builder, CookiesForCannedPolicy> { /** * Configure the resource URL */ Builder resourceUrl(String resourceUrl); /** * Configure the cookie signature header value */ Builder signatureHeaderValue(String signatureHeaderValue); /** * Configure the cookie key pair ID header value */ Builder keyPairIdHeaderValue(String keyPairIdHeaderValue); /** * Configure the cookie expires header value */ Builder expiresHeaderValue(String expiresHeaderValue); } }
4,704
0
Create_ds/aws-sdk-java-v2/services/glacier/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/glacier/src/test/java/software/amazon/awssdk/services/glacier/UploadArchiveHeaderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.glacier; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; 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 software.amazon.awssdk.http.Header.CONTENT_TYPE; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.File; import java.io.IOException; import java.net.URI; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.model.UploadArchiveRequest; import software.amazon.awssdk.testutils.RandomTempFile; public class UploadArchiveHeaderTest { @Rule public WireMockRule mockServer = new WireMockRule(0); private GlacierClient glacier; private UploadArchiveRequest request; @Before public void setup() { glacier = GlacierClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2).endpointOverride(URI.create(getEndpoint())) .build(); request = UploadArchiveRequest.builder().vaultName("test").build(); } private String getEndpoint() { return "http://localhost:" + mockServer.port(); } @Test public void putObjectBytes_headerShouldContainContentType() { stubFor(any(urlMatching(".*")) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); glacier.uploadArchive(request, RequestBody.fromBytes("test".getBytes())); verify(postRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(Mimetype.MIMETYPE_OCTET_STREAM))); } @Test public void uploadArchiveFile_headerShouldContainContentType() throws IOException { File file = new RandomTempFile("test.tsv", 10); stubFor(any(urlMatching(".*")) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); glacier.uploadArchive(request, RequestBody.fromFile(file)); file.delete(); verify(postRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo("text/tab-separated-values"))); } @Test public void uploadArchiveFile_contentTypeShouldNotBeOverrideIfSet() throws IOException { stubFor(any(urlMatching(".*")) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); request = (UploadArchiveRequest) request.toBuilder().overrideConfiguration(b -> b.putHeader(CONTENT_TYPE, "test")).build(); glacier.uploadArchive(request, RequestBody.fromBytes("test".getBytes())); verify(postRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo("test"))); } }
4,705
0
Create_ds/aws-sdk-java-v2/services/glacier/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/glacier/src/test/java/software/amazon/awssdk/services/glacier/AccountIdDefaultValueTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.glacier; 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.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.model.ListVaultsRequest; /** * Glacier has a customization to default accountId to '-' (which indicates the current account) if not provided. */ public class AccountIdDefaultValueTest { @Rule public WireMockRule mockServer = new WireMockRule(0); private GlacierClient glacier; @Before public void setup() { glacier = GlacierClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2).endpointOverride(URI.create(getEndpoint())) .build(); } private String getEndpoint() { return "http://localhost:" + mockServer.port(); } @Test public void noAccountIdProvided_DefaultsToHyphen() { stubFor(any(urlMatching(".*")) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); glacier.listVaults(ListVaultsRequest.builder().build()); verify(getRequestedFor(urlEqualTo("/-/vaults"))); } @Test public void accountIdProvided_DoesNotChangeValue() { stubFor(any(urlMatching(".*")) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); glacier.listVaults(ListVaultsRequest.builder().accountId("1234").build()); verify(getRequestedFor(urlEqualTo("/1234/vaults"))); } }
4,706
0
Create_ds/aws-sdk-java-v2/services/glacier/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/glacier/src/it/java/software/amazon/awssdk/services/glacier/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.glacier; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.assertj.core.api.Condition; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.glacier.model.ListVaultsRequest; import software.amazon.awssdk.services.glacier.model.ResourceNotFoundException; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class ServiceIntegrationTest extends AwsIntegrationTestBase { private GlacierClient client; private CapturingExecutionInterceptor capturingExecutionInterceptor = new CapturingExecutionInterceptor(); @Before public void setup() { client = GlacierClient.builder() .credentialsProvider(getCredentialsProvider()) .overrideConfiguration(ClientOverrideConfiguration .builder() .addExecutionInterceptor(capturingExecutionInterceptor) .build()) .build(); } /** * API version is a required parameter inserted by the * {@link software.amazon.awssdk.services.glacier.internal.GlacierExecutionInterceptor} */ @Test public void listVaults_SendsApiVersion() { client.listVaults(ListVaultsRequest.builder().build()); assertThat(capturingExecutionInterceptor.beforeTransmission) .is(new Condition<>(r -> r.firstMatchingHeader("x-amz-glacier-version") .orElseThrow(() -> new AssertionError("x-amz-glacier-version header not found")) .equals("2012-06-01"), "Glacier API version is present in header")); } /** * Glacier has a custom field name for it's error code so we make sure that works here. */ @Test public void modeledException_IsUnmarshalledCorrectly() { assertThatThrownBy(() -> client.describeVault(r -> r.vaultName("nope"))) .isInstanceOf(ResourceNotFoundException.class); } public static class CapturingExecutionInterceptor implements ExecutionInterceptor { private SdkHttpRequest beforeTransmission; @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { this.beforeTransmission = context.httpRequest(); } } }
4,707
0
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier/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.glacier.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) { return context.httpRequest() .toBuilder() .putHeader("Accept", "application/json") .build(); } }
4,708
0
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier/internal/GlacierExecutionInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.glacier.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; import software.amazon.awssdk.services.glacier.model.DescribeJobRequest; import software.amazon.awssdk.services.glacier.model.GetJobOutputRequest; import software.amazon.awssdk.services.glacier.model.UploadMultipartPartRequest; import software.amazon.awssdk.utils.StringUtils; @SdkInternalApi public final class GlacierExecutionInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); Object originalRequest = context.request(); return request.toBuilder() .applyMutation(b -> beforeRequest(originalRequest, b)) .build(); } private SdkHttpRequest.Builder beforeRequest(Object originalRequest, SdkHttpRequest.Builder mutableRequest) { mutableRequest.putHeader("x-amz-glacier-version", "2012-06-01"); // "x-amz-content-sha256" header is required for sig v4 for some streaming operations mutableRequest.putHeader("x-amz-content-sha256", "required"); if (originalRequest instanceof UploadMultipartPartRequest) { mutableRequest.firstMatchingHeader("Content-Range") .ifPresent(range -> mutableRequest.putHeader("Content-Length", Long.toString(parseContentLengthFromRange(range)))); } else if (originalRequest instanceof GetJobOutputRequest || originalRequest instanceof DescribeJobRequest) { String resourcePath = mutableRequest.encodedPath(); if (resourcePath != null) { String newResourcePath = StringUtils.replace(resourcePath, "{jobType}", "archive-retrievals"); mutableRequest.encodedPath(newResourcePath); } } return mutableRequest; } private long parseContentLengthFromRange(String range) { if (range.startsWith("bytes=") || range.startsWith("bytes ")) { range = range.substring(6); } String start = range.substring(0, range.indexOf('-')); String end = range.substring(range.indexOf('-') + 1); if (end.contains("/")) { end = end.substring(0, end.indexOf('/')); } return Long.parseLong(end) - Long.parseLong(start) + 1; } }
4,709
0
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier/transform/DefaultAccountIdSupplier.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.glacier.transform; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class DefaultAccountIdSupplier { /** * Value that indicates the current account. */ private static final String CURRENT_ACCOUNT_ID = "-"; private static final Supplier<String> INSTANCE = () -> CURRENT_ACCOUNT_ID; private DefaultAccountIdSupplier() { } public static Supplier<String> getInstance() { return INSTANCE; } }
4,710
0
Create_ds/aws-sdk-java-v2/services/elasticbeanstalk/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/elasticbeanstalk/src/it/java/software/amazon/awssdk/services/elasticbeanstalk/ElasticBeanstalkIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.elasticbeanstalk; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static software.amazon.awssdk.testutils.SdkAsserts.assertNotEmpty; import java.util.List; import org.junit.Test; import software.amazon.awssdk.services.elasticbeanstalk.model.ListAvailableSolutionStacksRequest; /** * Integration test to bring up a new ElasticBeanstalk environment and run through as * many operations as possible. */ public class ElasticBeanstalkIntegrationTest extends ElasticBeanstalkIntegrationTestBase { /** Tests that we can describe the available solution stacks. */ @Test public void testListAvailableSolutionStacks() throws Exception { List<String> solutionStacks = elasticbeanstalk.listAvailableSolutionStacks(ListAvailableSolutionStacksRequest.builder().build()) .solutionStacks(); assertNotNull(solutionStacks); assertTrue(solutionStacks.size() > 1); for (String stack : solutionStacks) { assertNotEmpty(stack); } } }
4,711
0
Create_ds/aws-sdk-java-v2/services/elasticbeanstalk/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/elasticbeanstalk/src/it/java/software/amazon/awssdk/services/elasticbeanstalk/ElasticBeanstalkIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.elasticbeanstalk; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for ElasticBeanstalk integration tests; responsible for loading AWS account info for * running the tests, and instantiating clients for tests to use. */ public abstract class ElasticBeanstalkIntegrationTestBase extends AwsTestBase { protected static ElasticBeanstalkClient elasticbeanstalk; /** * Loads the AWS account info for the integration tests and creates an clients for tests to use. */ @BeforeClass public static void setUp() throws IOException { setUpCredentials(); elasticbeanstalk = ElasticBeanstalkClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); } }
4,712
0
Create_ds/aws-sdk-java-v2/services/cloudsearchdomain/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/services/cloudsearchdomain/src/test/java/software/amazon/awssdk/cloudsearchdomain/SearchRequestUnitTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.cloudsearchdomain; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import com.github.tomakehurst.wiremock.common.ConsoleNotifier; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URI; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudsearchdomain.CloudSearchDomainClient; import software.amazon.awssdk.services.cloudsearchdomain.model.SearchRequest; /** * Unit tests for {@link SearchRequest}. */ public class SearchRequestUnitTest { private static final AwsBasicCredentials CREDENTIALS = AwsBasicCredentials.create("access", "secret"); @Rule public WireMockRule wireMockRule = new WireMockRule(new WireMockConfiguration().port(0).notifier(new ConsoleNotifier(true))); private CloudSearchDomainClient searchClient; @Before public void testSetup() { searchClient = CloudSearchDomainClient.builder() .credentialsProvider(StaticCredentialsProvider.create(CREDENTIALS)) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMockRule.port())) .build(); } /** * Test that search requests use POST instead of (the also supported) GET. * @throws IOException */ @Test public void testPostUsedForSearchRequest() throws IOException { stubFor(post(urlMatching("/.*")) .willReturn(aResponse() .withStatus(200) .withBody("{\"status\":{\"rid\":\"fooBar\",\"time-ms\":7},\"hits\":{\"found\":0,\"start\":0,\"hit\":[]}}"))); searchClient.search(SearchRequest.builder().query("Lord of the Rings").build()); verify(postRequestedFor(urlEqualTo("/2013-01-01/search")) .withRequestBody(equalTo("format=sdk&pretty=true&q=Lord+of+the+Rings")) .withHeader("Content-Type", equalTo("application/x-www-form-urlencoded"))); } }
4,713
0
Create_ds/aws-sdk-java-v2/services/cloudsearchdomain/src/main/java/software/amazon/awssdk/services/cloudsearchdomain
Create_ds/aws-sdk-java-v2/services/cloudsearchdomain/src/main/java/software/amazon/awssdk/services/cloudsearchdomain/internal/SwitchToPostInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudsearchdomain.internal; import static java.util.Collections.singletonList; import static software.amazon.awssdk.utils.StringUtils.lowerCase; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.cloudsearchdomain.model.SearchRequest; /** * Ensures that all SearchRequests use <code>POST</code> instead of <code>GET</code>, moving the query parameters to be form data. */ @SdkInternalApi public final class SwitchToPostInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest httpRequest = context.httpRequest(); if (context.request() instanceof SearchRequest) { return httpRequest.toBuilder() .clearQueryParameters() .method(SdkHttpMethod.POST) .putHeader("Content-Type", singletonList("application/x-www-form-urlencoded")) .build(); } return context.httpRequest(); } @Override public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof SearchRequest) { byte[] params = context.httpRequest().encodedQueryParametersAsFormData().orElse("") .getBytes(StandardCharsets.UTF_8); return Optional.of(RequestBody.fromContentProvider(() -> new ByteArrayInputStream(params), params.length, "application/x-www-form-urlencoded; charset=" + lowerCase(StandardCharsets.UTF_8.toString()))); } return context.requestBody(); } }
4,714
0
Create_ds/aws-sdk-java-v2/services/neptune/src/test/java/software/amazon/awssdk/services/neptune
Create_ds/aws-sdk-java-v2/services/neptune/src/test/java/software/amazon/awssdk/services/neptune/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.neptune.internal; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; 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.neptune.NeptuneClient; import java.net.URI; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; @RunWith(MockitoJUnitRunner.class) public class PresignRequestWireMockTest { @ClassRule public static final WireMockRule WIRE_MOCK = new WireMockRule(0); public static NeptuneClient client; @BeforeClass public static void setup() { client = NeptuneClient.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.copyDBClusterSnapshot(r -> r.sourceRegion("us-west-2")), "CopyDBClusterSnapshot"); } @Test public void createDbClusterWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.createDBCluster(r -> r.sourceRegion("us-west-2")), "CreateDBCluster"); } @Test public void createDBInstanceReadReplicaWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.createDBCluster(r -> r.sourceRegion("us-west-2")), "CreateDBCluster"); } 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"); } }
4,715
0
Create_ds/aws-sdk-java-v2/services/neptune/src/test/java/software/amazon/awssdk/services/neptune
Create_ds/aws-sdk-java-v2/services/neptune/src/test/java/software/amazon/awssdk/services/neptune/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.neptune.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.neptune.model.CopyDbClusterSnapshotRequest; import software.amazon.awssdk.services.neptune.model.NeptuneRequest; import software.amazon.awssdk.services.neptune.transform.CopyDbClusterSnapshotRequestMarshaller; /** * 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 final RdsPresignInterceptor<CopyDbClusterSnapshotRequest> presignInterceptor = new CopyDbClusterSnapshotPresignInterceptor(); private final CopyDbClusterSnapshotRequestMarshaller marshaller = new CopyDbClusterSnapshotRequestMarshaller(RdsPresignInterceptor.PROTOCOL_FACTORY); @Test public void testSetsPresignedUrl() { CopyDbClusterSnapshotRequest request = makeTestRequest(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertNotNull(presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testComputesPresignedUrlCorrectlyForCopyDbClusterSnapshotRequest() { // 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 CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.builder() .sourceDBClusterSnapshotIdentifier("arn:aws:rds:us-east-1:123456789012:snapshot:rds:test-instance-ss-2016-12-20-23-19") .targetDBClusterSnapshotIdentifier("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<CopyDbClusterSnapshotRequest> interceptor = new CopyDbClusterSnapshotPresignInterceptor(signingDateOverride); SdkHttpRequest presignedRequest = modifyHttpRequest(interceptor, request, marshallRequest(request)); final String expectedPreSignedUrl = "https://rds.us-east-1.amazonaws.com?" + "Action=CopyDBClusterSnapshot" + "&Version=2014-10-31" + "&SourceDBClusterSnapshotIdentifier=arn%3Aaws%3Ards%3Aus-east-1%3A123456789012%3Asnapshot%3Ards%3Atest-instance-ss-2016-12-20-23-19" + "&TargetDBClusterSnapshotIdentifier=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=00822ebbba95e2e6ac09112aa85621fbef060a596e3e1480f9f4ac61493e9821"; assertEquals(expectedPreSignedUrl, presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testSkipsPresigningIfUrlSet() { CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.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() { CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.builder().build(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertNull(presignedRequest.rawQueryParameters().get("PreSignedUrl")); } @Test public void testParsesDestinationRegionfromRequestEndpoint() throws URISyntaxException { CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.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() { CopyDbClusterSnapshotRequest request = makeTestRequest(); SdkHttpFullRequest marshalled = marshallRequest(request); SdkHttpRequest actual = modifyHttpRequest(presignInterceptor, request, marshalled); assertFalse(actual.rawQueryParameters().containsKey("SourceRegion")); } private SdkHttpFullRequest marshallRequest(CopyDbClusterSnapshotRequest 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 CopyDbClusterSnapshotRequest makeTestRequest() { return CopyDbClusterSnapshotRequest.builder() .sourceDBClusterSnapshotIdentifier("arn:aws:rds:us-east-1:123456789012:snapshot:rds:test-instance-ss-2016-12-20-23-19") .targetDBClusterSnapshotIdentifier("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, NeptuneRequest request, SdkHttpFullRequest httpRequest) { InterceptorContext context = InterceptorContext.builder().request(request).httpRequest(httpRequest).build(); return interceptor.modifyHttpRequest(context, executionAttributes()); } }
4,716
0
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune/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.neptune.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.neptune.model.CopyDbClusterSnapshotRequest; import software.amazon.awssdk.services.neptune.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); } @SdkTestInternalApi CopyDbClusterSnapshotPresignInterceptor(Clock signingDateOverride) { super(CopyDbClusterSnapshotRequest.class, signingDateOverride); } @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); } }; } }
4,717
0
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune/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.neptune.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.neptune.model.CreateDbClusterRequest; import software.amazon.awssdk.services.neptune.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); } }; } }
4,718
0
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune/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.neptune.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.neptune.model.NeptuneRequest; 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 NeptuneRequest> 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; protected RdsPresignInterceptor(Class<T> requestClassToPreSign) { this(requestClassToPreSign, null); } protected 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(); } }
4,719
0
Create_ds/aws-sdk-java-v2/services/ecr/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ecr/src/it/java/software/amazon/awssdk/services/ecr/EcrIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ecr; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.ecr.model.CreateRepositoryRequest; import software.amazon.awssdk.services.ecr.model.CreateRepositoryResponse; import software.amazon.awssdk.services.ecr.model.DeleteRepositoryRequest; import software.amazon.awssdk.services.ecr.model.DescribeRepositoriesRequest; import software.amazon.awssdk.services.ecr.model.Repository; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class EcrIntegrationTest extends AwsIntegrationTestBase { private static final String REPO_NAME = "java-sdk-test-repo-" + System.currentTimeMillis(); private static EcrClient ecr; @BeforeClass public static void setUpClient() throws Exception { ecr = EcrClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } @AfterClass public static void tearDownAfterClass() throws Exception { if (ecr != null) { ecr.deleteRepository(DeleteRepositoryRequest.builder() .repositoryName(REPO_NAME) .build()); } } @Test public void basicTest() { CreateRepositoryResponse result = ecr.createRepository( CreateRepositoryRequest.builder() .repositoryName(REPO_NAME) .build()); Assert.assertNotNull(result.repository()); Assert.assertEquals(result.repository().repositoryName(), REPO_NAME); Assert.assertNotNull(result.repository().repositoryArn()); Assert.assertNotNull(result.repository().registryId()); String repoArn = result.repository().repositoryArn(); String registryId = result.repository().registryId(); Repository repo = ecr.describeRepositories(DescribeRepositoriesRequest.builder() .repositoryNames(REPO_NAME) .build()) .repositories().get(0); Assert.assertEquals(repo.registryId(), registryId); Assert.assertEquals(repo.repositoryName(), REPO_NAME); Assert.assertEquals(repo.repositoryArn(), repoArn); } }
4,720
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test/util/DynamoDBTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.test.util; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.TableDescription; import software.amazon.awssdk.services.dynamodb.model.TableStatus; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.Logger; public class DynamoDBTestBase extends AwsTestBase { protected static final String ENDPOINT = "http://dynamodb.us-east-1.amazonaws.com/"; protected static final Region REGION = Region.US_EAST_1; protected static DynamoDbClient dynamo; protected static DynamoDbAsyncClient dynamoAsync; private static final Logger log = Logger.loggerFor(DynamoDBTestBase.class); public static void setUpTestBase() { try { setUpCredentials(); } catch (Exception e) { throw SdkClientException.builder().message("Unable to load credential property file.").cause(e).build(); } dynamo = DynamoDbClient.builder().region(REGION).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); dynamoAsync = DynamoDbAsyncClient.builder().region(REGION).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } public static DynamoDbClient getClient() { if (dynamo == null) { setUpTestBase(); } return dynamo; } protected static void waitForTableToBecomeDeleted(String tableName) { waitForTableToBecomeDeleted(dynamo, tableName); } public static void waitForTableToBecomeDeleted(DynamoDbClient dynamo, String tableName) { log.info(() -> "Waiting for " + tableName + " to become Deleted..."); long startTime = System.currentTimeMillis(); long endTime = startTime + (60_000); while (System.currentTimeMillis() < endTime) { try { Thread.sleep(5_000); } catch (Exception e) { // Ignored or expected. } try { DescribeTableRequest request = DescribeTableRequest.builder().tableName(tableName).build(); TableDescription table = dynamo.describeTable(request).table(); log.info(() -> " - current state: " + table.tableStatusAsString()); if (table.tableStatus() == TableStatus.DELETING) { continue; } } catch (AwsServiceException exception) { if (exception.awsErrorDetails().errorCode().equalsIgnoreCase("ResourceNotFoundException")) { log.info(() -> "successfully deleted"); return; } } } throw new RuntimeException("Table " + tableName + " never went deleted"); } protected static <T extends Object> void assertSetsEqual(Collection<T> expected, Collection<T> given) { Set<T> givenCopy = new HashSet<T>(); givenCopy.addAll(given); for (T e : expected) { if (!givenCopy.remove(e)) { fail("Expected element not found: " + e); } } assertTrue("Unexpected elements found: " + givenCopy, givenCopy.isEmpty()); } /** * Only valid for whole numbers */ protected static void assertNumericSetsEquals(Set<? extends Number> expected, Collection<String> given) { Set<BigDecimal> givenCopy = new HashSet<BigDecimal>(); for (String s : given) { BigDecimal bd = new BigDecimal(s); givenCopy.add(bd.setScale(0)); } Set<BigDecimal> expectedCopy = new HashSet<BigDecimal>(); for (Number n : expected) { BigDecimal bd = new BigDecimal(n.toString()); expectedCopy.add(bd.setScale(0)); } assertSetsEqual(expectedCopy, givenCopy); } protected static <T extends Object> Set<T> toSet(T... array) { Set<T> set = new HashSet<T>(); for (T t : array) { set.add(t); } return set; } protected static <T extends Object> Set<T> toSet(Collection<T> collection) { Set<T> set = new HashSet<T>(); for (T t : collection) { set.add(t); } return set; } protected static byte[] generateByteArray(int length) { byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = (byte) (i % Byte.MAX_VALUE); } return bytes; } /** * Gets a map of key values for the single hash key attribute value given. */ protected Map<String, AttributeValue> mapKey(String attributeName, AttributeValue value) { HashMap<String, AttributeValue> map = new HashMap<String, AttributeValue>(); map.put(attributeName, value); return map; } }
4,721
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test/util/DynamoDBIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.test.util; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest; import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse; import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; public class DynamoDBIntegrationTestBase extends DynamoDBTestBase { protected static final String KEY_NAME = "key"; protected static final String TABLE_NAME = "aws-java-sdk-util"; protected static final String TABLE_WITH_RANGE_ATTRIBUTE = "aws-java-sdk-range-test"; protected static final String TABLE_WITH_INDEX_RANGE_ATTRIBUTE = "aws-java-sdk-index-range-test"; protected static long startKey = System.currentTimeMillis(); @BeforeClass public static void setUp() throws Exception { setUpCredentials(); dynamo = DynamoDbClient.builder().region(Region.US_EAST_1).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); // Create a table String keyName = KEY_NAME; CreateTableRequest createTableRequest = CreateTableRequest.builder() .tableName(TABLE_NAME) .keySchema(KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build()) .attributeDefinitions( AttributeDefinition.builder().attributeName(keyName) .attributeType(ScalarAttributeType.S) .build()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(10L) .writeCapacityUnits(5L).build()) .build(); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_NAME); } } /** * Quick utility method to delete all tables when we have too much capacity * reserved for the region. */ public static void deleteAllTables() { ListTablesResponse listTables = dynamo.listTables(ListTablesRequest.builder().build()); for (String name : listTables.tableNames()) { dynamo.deleteTable(DeleteTableRequest.builder().tableName(name).build()); } } protected static void setUpTableWithRangeAttribute() throws Exception { setUp(); String keyName = DynamoDBIntegrationTestBase.KEY_NAME; String rangeKeyAttributeName = "rangeKey"; CreateTableRequest createTableRequest = CreateTableRequest.builder() .tableName(TABLE_WITH_RANGE_ATTRIBUTE) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(rangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .attributeDefinitions( AttributeDefinition.builder() .attributeName(keyName) .attributeType(ScalarAttributeType.N) .build(), AttributeDefinition.builder() .attributeName(rangeKeyAttributeName) .attributeType(ScalarAttributeType.N) .build()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(10L) .writeCapacityUnits(5L).build()) .build(); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_WITH_RANGE_ATTRIBUTE); } } protected static void setUpTableWithIndexRangeAttribute(boolean recreateTable) throws Exception { setUp(); if (recreateTable) { dynamo.deleteTable(DeleteTableRequest.builder().tableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE).build()); waitForTableToBecomeDeleted(TABLE_WITH_INDEX_RANGE_ATTRIBUTE); } String keyName = DynamoDBIntegrationTestBase.KEY_NAME; String rangeKeyAttributeName = "rangeKey"; String indexFooRangeKeyAttributeName = "indexFooRangeKey"; String indexBarRangeKeyAttributeName = "indexBarRangeKey"; String multipleIndexRangeKeyAttributeName = "multipleIndexRangeKey"; String fooAttributeName = "fooAttribute"; String barAttributeName = "barAttribute"; String indexFooName = "index_foo"; String indexBarName = "index_bar"; String indexFooCopyName = "index_foo_copy"; String indexBarCopyName = "index_bar_copy"; CreateTableRequest createTableRequest = CreateTableRequest.builder() .tableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(rangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .localSecondaryIndexes( LocalSecondaryIndex.builder() .indexName(indexFooName) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(indexFooRangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .projection(Projection.builder() .projectionType(ProjectionType.INCLUDE) .nonKeyAttributes(fooAttributeName) .build()) .build(), LocalSecondaryIndex.builder() .indexName(indexBarName) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(indexBarRangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .projection(Projection.builder() .projectionType(ProjectionType.INCLUDE) .nonKeyAttributes(barAttributeName) .build()) .build(), LocalSecondaryIndex.builder() .indexName(indexFooCopyName) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(multipleIndexRangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .projection(Projection.builder() .projectionType(ProjectionType.INCLUDE) .nonKeyAttributes(fooAttributeName) .build()) .build(), LocalSecondaryIndex.builder() .indexName(indexBarCopyName) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(multipleIndexRangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .projection(Projection.builder() .projectionType(ProjectionType.INCLUDE) .nonKeyAttributes(barAttributeName) .build()) .build()) .attributeDefinitions( AttributeDefinition.builder().attributeName(keyName).attributeType(ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName(rangeKeyAttributeName) .attributeType(ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName(indexFooRangeKeyAttributeName) .attributeType(ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName(indexBarRangeKeyAttributeName) .attributeType(ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName(multipleIndexRangeKeyAttributeName) .attributeType(ScalarAttributeType.N).build()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(10L) .writeCapacityUnits(5L).build()) .build(); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_WITH_INDEX_RANGE_ATTRIBUTE); } } }
4,722
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test/util/TableUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.test.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.ResourceInUseException; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.services.dynamodb.model.TableDescription; import software.amazon.awssdk.services.dynamodb.model.TableStatus; /** * Utility methods for working with DynamoDB tables. * * <pre class="brush: java"> * // ... create DynamoDB table ... * try { * waitUntilActive(dynamoDB, myTableName()); * } catch (SdkClientException e) { * // table didn't become active * } * // ... start making calls to table ... * </pre> */ public class TableUtils { private static final int DEFAULT_WAIT_TIMEOUT = 20 * 60 * 1000; private static final int DEFAULT_WAIT_INTERVAL = 10 * 1000; /** * The logging utility. */ private static final Logger log = LoggerFactory.getLogger(TableUtils.class); /** * Waits up to 10 minutes for a specified DynamoDB table to resolve, * indicating that it exists. If the table doesn't return a result after * this time, a SdkClientException is thrown. * * @param dynamo * The DynamoDB client to use to make requests. * @param tableName * The name of the table being resolved. * * @throws SdkClientException * If the specified table does not resolve before this method * times out and stops polling. * @throws InterruptedException * If the thread is interrupted while waiting for the table to * resolve. */ public static void waitUntilExists(final DynamoDbClient dynamo, final String tableName) throws InterruptedException { waitUntilExists(dynamo, tableName, DEFAULT_WAIT_TIMEOUT, DEFAULT_WAIT_INTERVAL); } /** * Waits up to a specified amount of time for a specified DynamoDB table to * resolve, indicating that it exists. If the table doesn't return a result * after this time, a SdkClientException is thrown. * * @param dynamo * The DynamoDB client to use to make requests. * @param tableName * The name of the table being resolved. * @param timeout * The maximum number of milliseconds to wait. * @param interval * The poll interval in milliseconds. * * @throws SdkClientException * If the specified table does not resolve before this method * times out and stops polling. * @throws InterruptedException * If the thread is interrupted while waiting for the table to * resolve. */ public static void waitUntilExists(final DynamoDbClient dynamo, final String tableName, final int timeout, final int interval) throws InterruptedException { TableDescription table = waitForTableDescription(dynamo, tableName, null, timeout, interval); if (table == null) { throw SdkClientException.builder().message("Table " + tableName + " never returned a result").build(); } } /** * Waits up to 10 minutes for a specified DynamoDB table to move into the * <code>ACTIVE</code> state. If the table does not exist or does not * transition to the <code>ACTIVE</code> state after this time, then * SdkClientException is thrown. * * @param dynamo * The DynamoDB client to use to make requests. * @param tableName * The name of the table whose status is being checked. * * @throws TableNeverTransitionedToStateException * If the specified table does not exist or does not transition * into the <code>ACTIVE</code> state before this method times * out and stops polling. * @throws InterruptedException * If the thread is interrupted while waiting for the table to * transition into the <code>ACTIVE</code> state. */ public static void waitUntilActive(final DynamoDbClient dynamo, final String tableName) throws InterruptedException, TableNeverTransitionedToStateException { waitUntilActive(dynamo, tableName, DEFAULT_WAIT_TIMEOUT, DEFAULT_WAIT_INTERVAL); } /** * Waits up to a specified amount of time for a specified DynamoDB table to * move into the <code>ACTIVE</code> state. If the table does not exist or * does not transition to the <code>ACTIVE</code> state after this time, * then a SdkClientException is thrown. * * @param dynamo * The DynamoDB client to use to make requests. * @param tableName * The name of the table whose status is being checked. * @param timeout * The maximum number of milliseconds to wait. * @param interval * The poll interval in milliseconds. * * @throws TableNeverTransitionedToStateException * If the specified table does not exist or does not transition * into the <code>ACTIVE</code> state before this method times * out and stops polling. * @throws InterruptedException * If the thread is interrupted while waiting for the table to * transition into the <code>ACTIVE</code> state. */ public static void waitUntilActive(final DynamoDbClient dynamo, final String tableName, final int timeout, final int interval) throws InterruptedException, TableNeverTransitionedToStateException { TableDescription table = waitForTableDescription(dynamo, tableName, TableStatus.ACTIVE, timeout, interval); if (table == null || !table.tableStatus().equals(TableStatus.ACTIVE)) { throw new TableNeverTransitionedToStateException(tableName, TableStatus.ACTIVE); } } /** * Wait for the table to reach the desired status and returns the table * description * * @param dynamo * Dynamo client to use * @param tableName * Table name to poll status of * @param desiredStatus * Desired {@link TableStatus} to wait for. If null this method * simply waits until DescribeTable returns something non-null * (i.e. any status) * @param timeout * Timeout in milliseconds to continue to poll for desired status * @param interval * Time to wait in milliseconds between poll attempts * @return Null if DescribeTables never returns a result, otherwise the * result of the last poll attempt (which may or may not have the * desired state) * @throws {@link * IllegalArgumentException} If timeout or interval is invalid */ private static TableDescription waitForTableDescription(final DynamoDbClient dynamo, final String tableName, TableStatus desiredStatus, final int timeout, final int interval) throws InterruptedException, IllegalArgumentException { if (timeout < 0) { throw new IllegalArgumentException("Timeout must be >= 0"); } if (interval <= 0 || interval >= timeout) { throw new IllegalArgumentException("Interval must be > 0 and < timeout"); } long startTime = System.currentTimeMillis(); long endTime = startTime + timeout; TableDescription table = null; while (System.currentTimeMillis() < endTime) { try { table = dynamo.describeTable(DescribeTableRequest.builder().tableName(tableName).build()).table(); if (desiredStatus == null || table.tableStatus().equals(desiredStatus)) { return table; } } catch (ResourceNotFoundException rnfe) { // ResourceNotFound means the table doesn't exist yet, // so ignore this error and just keep polling. } Thread.sleep(interval); } return table; } /** * Creates the table and ignores any errors if it already exists. * @param dynamo The Dynamo client to use. * @param createTableRequest The create table request. * @return True if created, false otherwise. */ public static boolean createTableIfNotExists(final DynamoDbClient dynamo, final CreateTableRequest createTableRequest) { try { dynamo.createTable(createTableRequest); return true; } catch (final ResourceInUseException e) { if (log.isTraceEnabled()) { log.trace("Table " + createTableRequest.tableName() + " already exists", e); } } return false; } /** * Deletes the table and ignores any errors if it doesn't exist. * @param dynamo The Dynamo client to use. * @param deleteTableRequest The delete table request. * @return True if deleted, false otherwise. */ public static boolean deleteTableIfExists(final DynamoDbClient dynamo, final DeleteTableRequest deleteTableRequest) { try { dynamo.deleteTable(deleteTableRequest); return true; } catch (final ResourceNotFoundException e) { if (log.isTraceEnabled()) { log.trace("Table " + deleteTableRequest.tableName() + " does not exist", e); } } return false; } /** * Thrown by {@link TableUtils} when a table never reaches a desired state */ public static class TableNeverTransitionedToStateException extends SdkClientException { private static final long serialVersionUID = 8920567021104846647L; public TableNeverTransitionedToStateException(String tableName, TableStatus desiredStatus) { super(SdkClientException.builder() .message("Table " + tableName + " never transitioned to desired state of " + desiredStatus.toString())); } } }
4,723
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test/resources/DynamoDBTableResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.test.resources; import java.util.List; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndexDescription; import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndexDescription; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.TableDescription; import software.amazon.awssdk.services.dynamodb.model.TableStatus; import software.amazon.awssdk.testutils.UnorderedCollectionComparator; import software.amazon.awssdk.utils.Logger; import utils.resources.TestResource; import utils.test.util.DynamoDBTestBase; import utils.test.util.TableUtils; public abstract class DynamoDBTableResource implements TestResource { private static final Logger log = Logger.loggerFor(DynamoDBTableResource.class); /** * Returns true if the two lists of GlobalSecondaryIndex and * GlobalSecondaryIndexDescription share the same set of: * 1) indexName * 2) projection * 3) keySchema (compared as unordered lists) */ static boolean equalUnorderedGsiLists(List<GlobalSecondaryIndex> listA, List<GlobalSecondaryIndexDescription> listB) { return UnorderedCollectionComparator.equalUnorderedCollections( listA, listB, new UnorderedCollectionComparator.CrossTypeComparator<GlobalSecondaryIndex, GlobalSecondaryIndexDescription>() { @Override public boolean equals(GlobalSecondaryIndex a, GlobalSecondaryIndexDescription b) { return a.indexName().equals(b.indexName()) && equalProjections(a.projection(), b.projection()) && UnorderedCollectionComparator.equalUnorderedCollections(a.keySchema(), b.keySchema()); } }); } /** * Returns true if the two lists of LocalSecondaryIndex and * LocalSecondaryIndexDescription share the same set of: * 1) indexName * 2) projection * 3) keySchema (compared as unordered lists) */ static boolean equalUnorderedLsiLists(List<LocalSecondaryIndex> listA, List<LocalSecondaryIndexDescription> listB) { return UnorderedCollectionComparator.equalUnorderedCollections( listA, listB, new UnorderedCollectionComparator.CrossTypeComparator<LocalSecondaryIndex, LocalSecondaryIndexDescription>() { @Override public boolean equals(LocalSecondaryIndex a, LocalSecondaryIndexDescription b) { // Project parameter might not be specified in the // CreateTableRequest. But it should be treated as equal // to the default projection type - KEYS_ONLY. return a.indexName().equals(b.indexName()) && equalProjections(a.projection(), b.projection()) && UnorderedCollectionComparator.equalUnorderedCollections(a.keySchema(), b.keySchema()); } }); } /** * Compares the Projection parameter included in the CreateTableRequest, * with the one returned from DescribeTableResponse. */ static boolean equalProjections(Projection fromCreateTableRequest, Projection fromDescribeTableResponse) { if (fromCreateTableRequest == null || fromDescribeTableResponse == null) { throw new IllegalStateException("The projection parameter should never be null."); } return fromCreateTableRequest.projectionType().equals( fromDescribeTableResponse.projectionType()) && UnorderedCollectionComparator.equalUnorderedCollections( fromCreateTableRequest.nonKeyAttributes(), fromDescribeTableResponse.nonKeyAttributes()); } protected abstract DynamoDbClient getClient(); protected abstract CreateTableRequest getCreateTableRequest(); /** * Implementation of TestResource interfaces */ @Override public void create(boolean waitTillFinished) { log.info(() -> "Creating " + this + "..."); getClient().createTable(getCreateTableRequest()); if (waitTillFinished) { log.info(() -> "Waiting for " + this + " to become active..."); try { TableUtils.waitUntilActive(getClient(), getCreateTableRequest().tableName()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } @Override public void delete(boolean waitTillFinished) { log.info(() -> "Deleting " + this + "..."); getClient().deleteTable(DeleteTableRequest.builder().tableName(getCreateTableRequest().tableName()).build()); if (waitTillFinished) { log.info(() -> "Waiting for " + this + " to become deleted..."); DynamoDBTestBase.waitForTableToBecomeDeleted(getClient(), getCreateTableRequest().tableName()); } } @Override public ResourceStatus getResourceStatus() { CreateTableRequest createRequest = getCreateTableRequest(); TableDescription table; try { table = getClient().describeTable(DescribeTableRequest.builder().tableName( createRequest.tableName()).build()).table(); } catch (AwsServiceException exception) { if (exception.awsErrorDetails().errorCode().equalsIgnoreCase("ResourceNotFoundException")) { return ResourceStatus.NOT_EXIST; } throw exception; } if (table.tableStatus() == TableStatus.ACTIVE) { // returns AVAILABLE only if table KeySchema + LSIs + GSIs all match. if (UnorderedCollectionComparator.equalUnorderedCollections(createRequest.keySchema(), table.keySchema()) && equalUnorderedGsiLists(createRequest.globalSecondaryIndexes(), table.globalSecondaryIndexes()) && equalUnorderedLsiLists(createRequest.localSecondaryIndexes(), table.localSecondaryIndexes())) { return ResourceStatus.AVAILABLE; } else { return ResourceStatus.EXIST_INCOMPATIBLE_RESOURCE; } } else if (table.tableStatus() == TableStatus.CREATING || table.tableStatus() == TableStatus.UPDATING || table.tableStatus() == TableStatus.DELETING) { return ResourceStatus.TRANSIENT; } else { return ResourceStatus.NOT_EXIST; } } /** * Object interfaces */ @Override public String toString() { return "DynamoDB Table [" + getCreateTableRequest().tableName() + "]"; } @Override public int hashCode() { return getCreateTableRequest().hashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof DynamoDBTableResource)) { return false; } return getCreateTableRequest().equals( ((DynamoDBTableResource) other).getCreateTableRequest()); } }
4,724
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/TestResourceUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources; import java.time.Duration; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.utils.Logger; import utils.resources.RequiredResources.ResourceCreationPolicy; import utils.resources.TestResource.ResourceStatus; public class TestResourceUtils { private static final Logger log = Logger.loggerFor(TestResourceUtils.class); public static void createResource(TestResource resource, ResourceCreationPolicy policy) throws InterruptedException { TestResource.ResourceStatus finalizedStatus = waitForFinalizedStatus(resource); if (policy == ResourceCreationPolicy.ALWAYS_RECREATE) { if (finalizedStatus != ResourceStatus.NOT_EXIST) { resource.delete(true); } resource.create(true); } else if (policy == ResourceCreationPolicy.REUSE_EXISTING) { switch (finalizedStatus) { case AVAILABLE: log.info(() -> "Found existing resource " + resource + " that could be reused..."); return; case EXIST_INCOMPATIBLE_RESOURCE: resource.delete(true); resource.create(true); // fallthru case NOT_EXIST: resource.create(true); break; default: break; } } } public static void deleteResource(TestResource resource) throws InterruptedException { ResourceStatus finalizedStatus = waitForFinalizedStatus(resource); if (finalizedStatus != ResourceStatus.NOT_EXIST) { resource.delete(false); } } public static ResourceStatus waitForFinalizedStatus(TestResource resource) throws InterruptedException { return Waiter.run(resource::getResourceStatus) .until(s -> s != ResourceStatus.TRANSIENT) .orFailAfter(Duration.ofMinutes(10)); } }
4,725
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/ResourceCentricBlockJUnit4ClassRunner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources; import java.util.HashSet; import java.util.Set; import org.junit.jupiter.api.Disabled; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import utils.resources.RequiredResources.RequiredResource; import utils.resources.RequiredResources.ResourceRetentionPolicy; public class ResourceCentricBlockJUnit4ClassRunner extends BlockJUnit4ClassRunner { private final Set<TestResource> resourcesToBeDestroyedAfterAllTests; private final RequiredResources classRequiredResourcesAnnotation; private final Logger log = LoggerFactory.getLogger(ResourceCentricBlockJUnit4ClassRunner.class); public ResourceCentricBlockJUnit4ClassRunner(Class<?> klass) throws InitializationError { super(klass); classRequiredResourcesAnnotation = klass.getAnnotation(RequiredResources.class); resourcesToBeDestroyedAfterAllTests = new HashSet<TestResource>(); } /** * */ private static TestResource createResourceInstance(RequiredResource resourceAnnotation) throws InstantiationException, IllegalAccessException { Class<? extends TestResource> resourceClazz = resourceAnnotation.resource(); if (resourceClazz == null) { throw new IllegalArgumentException( "resource parameter is missing for the @RequiredResource annotation."); } return resourceClazz.newInstance(); } @Override protected void runChild(final FrameworkMethod method, RunNotifier notifier) { Description description = describeChild(method); if (method.getAnnotation(Disabled.class) != null) { notifier.fireTestIgnored(description); } else { RequiredResources annotation = method.getAnnotation(RequiredResources.class); if (annotation != null) { try { beforeRunLeaf(annotation.value()); } catch (Exception e) { notifier.fireTestFailure(new Failure(description, e)); } } runLeaf(methodBlock(method), description, notifier); if (annotation != null) { try { afterRunLeaf(annotation.value()); } catch (Exception e) { notifier.fireTestFailure(new Failure(description, e)); } } } } /** * Override the withBeforeClasses method to inject executing resource * creation between @BeforeClass methods and test methods. */ @Override protected Statement withBeforeClasses(final Statement statement) { Statement withRequiredResourcesCreation = new Statement() { @Override public void evaluate() throws Throwable { if (classRequiredResourcesAnnotation != null) { beforeRunClass(classRequiredResourcesAnnotation.value()); } statement.evaluate(); } }; return super.withBeforeClasses(withRequiredResourcesCreation); } /** * Override the withAfterClasses method to inject executing resource * creation between test methods and the @AfterClass methods. */ @Override protected Statement withAfterClasses(final Statement statement) { Statement withRequiredResourcesDeletion = new Statement() { @Override public void evaluate() throws Throwable { statement.evaluate(); afterRunClass(); } }; return super.withAfterClasses(withRequiredResourcesDeletion); } private void beforeRunClass(RequiredResource[] resourcesAnnotation) throws InstantiationException, IllegalAccessException, InterruptedException { log.debug("Processing @RequiredResources before running the test class..."); for (RequiredResource resourceAnnotation : resourcesAnnotation) { TestResource resource = createResourceInstance(resourceAnnotation); TestResourceUtils.createResource(resource, resourceAnnotation.creationPolicy()); if (resourceAnnotation.retentionPolicy() != ResourceRetentionPolicy.KEEP) { resourcesToBeDestroyedAfterAllTests.add(resource); } } } private void afterRunClass() throws InstantiationException, IllegalAccessException, InterruptedException { log.debug("Processing @RequiredResources after running the test class..."); for (TestResource resource : resourcesToBeDestroyedAfterAllTests) { TestResourceUtils.deleteResource(resource); } } private void beforeRunLeaf(RequiredResource[] resourcesAnnotation) throws InstantiationException, IllegalAccessException, InterruptedException { log.debug("Processing @RequiredResources before running the test..."); for (RequiredResource resourceAnnotation : resourcesAnnotation) { TestResource resource = createResourceInstance(resourceAnnotation); TestResourceUtils.createResource(resource, resourceAnnotation.creationPolicy()); if (resourceAnnotation.retentionPolicy() == ResourceRetentionPolicy.DESTROY_AFTER_ALL_TESTS) { resourcesToBeDestroyedAfterAllTests.add(resource); } } } private void afterRunLeaf(RequiredResource[] resourcesAnnotation) throws InstantiationException, IllegalAccessException, InterruptedException { log.debug("Processing @RequiredResources after running the test..."); for (RequiredResource resourceAnnotation : resourcesAnnotation) { TestResource resource = createResourceInstance(resourceAnnotation); if (resourceAnnotation.retentionPolicy() == ResourceRetentionPolicy.DESTROY_IMMEDIATELY) { TestResourceUtils.deleteResource(resource); } } } }
4,726
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/TestResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources; /** * An interface which represents a resource to be used in a test case. * <p> * Note that sub-classes implementing this interface must provide a no-arg * constructor. */ public interface TestResource { /** * Create/initialize the resource which this TestResource represents. * * @param waitTillFinished Whether this method should block until the resource is fully * initialized. */ void create(boolean waitTillFinished); /** * Delete the resource which this TestResource represents. * * @param waitTillFinished Whether this method should block until the resource is fully * initialized. */ void delete(boolean waitTillFinished); /** * Returns the current status of the resource which this TestResource * represents. */ ResourceStatus getResourceStatus(); /** * Enum of all the generalized resource statuses. */ enum ResourceStatus { /** * The resource is currently available, and it is compatible with the * required resource. */ AVAILABLE, /** * The resource does not exist and there is no existing resource that is * incompatible. */ NOT_EXIST, /** * There is an existing resource that has to be removed before creating * the required resource. For example, DDB table with the same name but * different table schema. */ EXIST_INCOMPATIBLE_RESOURCE, /** * The resource is in transient state (e.g. creating/deleting/updating) */ TRANSIENT, } }
4,727
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/RequiredResources.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation for resources required for the test case. It could be applied to * either a type (test class) or a method (test method). */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface RequiredResources { /** * An array of RequiredResource annotations */ RequiredResource[] value() default {}; enum ResourceCreationPolicy { /** * Existing resource will be reused if it matches the required resource * definition (i.e. TestResource.getResourceStatus() returns AVAILABLE). */ REUSE_EXISTING, /** * Always destroy existing resources (if any) and then recreate new ones for test. */ ALWAYS_RECREATE; } enum ResourceRetentionPolicy { /** * Do not delete the created resource after test. */ KEEP, /** * When used for @RequiredAnnota */ DESTROY_IMMEDIATELY, DESTROY_AFTER_ALL_TESTS; } @interface RequiredResource { /** * The Class object of the TestResource class */ Class<? extends TestResource> resource(); /** * How the resource should be created before the test starts. */ ResourceCreationPolicy creationPolicy(); /** * Retention policy after the test is done. */ ResourceRetentionPolicy retentionPolicy(); } }
4,728
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/tables/TempTableWithSecondaryIndexes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources.tables; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import utils.test.resources.DynamoDBTableResource; import utils.test.util.DynamoDBTestBase; /** * The table used by SecondaryIndexesIntegrationTest */ public class TempTableWithSecondaryIndexes extends DynamoDBTableResource { public static final String TEMP_TABLE_NAME = "java-sdk-indexes-" + System.currentTimeMillis(); public static final String HASH_KEY_NAME = "hash_key"; public static final String RANGE_KEY_NAME = "range_key"; public static final String LSI_NAME = "local_secondary_index"; public static final String LSI_RANGE_KEY_NAME = "local_secondary_index_attribute"; public static final String GSI_NAME = "global_secondary_index"; public static final String GSI_HASH_KEY_NAME = "global_secondary_index_hash_attribute"; public static final String GSI_RANGE_KEY_NAME = "global_secondary_index_range_attribute"; public static final ProvisionedThroughput GSI_PROVISIONED_THROUGHPUT = ProvisionedThroughput.builder() .readCapacityUnits(5L) .writeCapacityUnits(5L) .build(); @Override protected DynamoDbClient getClient() { return DynamoDBTestBase.getClient(); } /** * Table schema: * Hash Key : HASH_KEY_NAME (S) * Range Key : RANGE_KEY_NAME (N) * LSI schema: * Hash Key : HASH_KEY_NAME (S) * Range Key : LSI_RANGE_KEY_NAME (N) * GSI schema: * Hash Key : GSI_HASH_KEY_NAME (N) * Range Key : GSI_RANGE_KEY_NAME (N) */ @Override protected CreateTableRequest getCreateTableRequest() { CreateTableRequest createTableRequest = CreateTableRequest.builder() .tableName(TEMP_TABLE_NAME) .keySchema( KeySchemaElement.builder() .attributeName(HASH_KEY_NAME) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(RANGE_KEY_NAME) .keyType(KeyType.RANGE) .build()) .attributeDefinitions( AttributeDefinition.builder().attributeName( HASH_KEY_NAME).attributeType( ScalarAttributeType.S).build(), AttributeDefinition.builder().attributeName( RANGE_KEY_NAME).attributeType( ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName( LSI_RANGE_KEY_NAME).attributeType( ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName( GSI_HASH_KEY_NAME).attributeType( ScalarAttributeType.S).build(), AttributeDefinition.builder().attributeName( GSI_RANGE_KEY_NAME).attributeType( ScalarAttributeType.N).build()) .provisionedThroughput(BasicTempTable.DEFAULT_PROVISIONED_THROUGHPUT) .localSecondaryIndexes( LocalSecondaryIndex.builder() .indexName(LSI_NAME) .keySchema( KeySchemaElement.builder() .attributeName( HASH_KEY_NAME) .keyType(KeyType.HASH).build(), KeySchemaElement.builder() .attributeName( LSI_RANGE_KEY_NAME) .keyType(KeyType.RANGE).build()) .projection( Projection.builder() .projectionType(ProjectionType.KEYS_ONLY).build()).build()) .globalSecondaryIndexes( GlobalSecondaryIndex.builder().indexName(GSI_NAME) .keySchema( KeySchemaElement.builder() .attributeName( GSI_HASH_KEY_NAME) .keyType(KeyType.HASH).build(), KeySchemaElement.builder() .attributeName( GSI_RANGE_KEY_NAME) .keyType(KeyType.RANGE).build()) .projection( Projection.builder() .projectionType(ProjectionType.KEYS_ONLY).build()) .provisionedThroughput( GSI_PROVISIONED_THROUGHPUT).build()) .build(); return createTableRequest; } }
4,729
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/tables/TempTableWithBinaryKey.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources.tables; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import utils.test.resources.DynamoDBTableResource; import utils.test.util.DynamoDBTestBase; public class TempTableWithBinaryKey extends DynamoDBTableResource { public static final String TEMP_BINARY_TABLE_NAME = "java-sdk-binary-" + System.currentTimeMillis(); public static final String HASH_KEY_NAME = "hash"; public static final Long READ_CAPACITY = 10L; public static final Long WRITE_CAPACITY = 5L; public static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT = ProvisionedThroughput.builder().readCapacityUnits(READ_CAPACITY).writeCapacityUnits(WRITE_CAPACITY).build(); @Override protected DynamoDbClient getClient() { return DynamoDBTestBase.getClient(); } @Override protected CreateTableRequest getCreateTableRequest() { CreateTableRequest request = CreateTableRequest.builder() .tableName(TEMP_BINARY_TABLE_NAME) .keySchema( KeySchemaElement.builder().attributeName(HASH_KEY_NAME) .keyType(KeyType.HASH).build()) .attributeDefinitions( AttributeDefinition.builder().attributeName( HASH_KEY_NAME).attributeType( ScalarAttributeType.B).build()) .provisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT) .build(); return request; } }
4,730
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/tables/BasicTempTable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources.tables; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import utils.test.resources.DynamoDBTableResource; import utils.test.util.DynamoDBTestBase; public class BasicTempTable extends DynamoDBTableResource { public static final String TEMP_TABLE_NAME = "java-sdk-" + System.currentTimeMillis(); public static final String HASH_KEY_NAME = "hash"; public static final Long READ_CAPACITY = 10L; public static final Long WRITE_CAPACITY = 5L; public static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT = ProvisionedThroughput.builder().readCapacityUnits(READ_CAPACITY).writeCapacityUnits(WRITE_CAPACITY).build(); @Override protected DynamoDbClient getClient() { return DynamoDBTestBase.getClient(); } @Override protected CreateTableRequest getCreateTableRequest() { CreateTableRequest request = CreateTableRequest.builder() .tableName(TEMP_TABLE_NAME) .keySchema( KeySchemaElement.builder().attributeName(HASH_KEY_NAME) .keyType(KeyType.HASH).build()) .attributeDefinitions( AttributeDefinition.builder().attributeName( HASH_KEY_NAME).attributeType( ScalarAttributeType.S).build()) .provisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT).build(); return request; } }
4,731
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/tables/BasicTempTableWithLowThroughput.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources.tables; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import utils.test.resources.DynamoDBTableResource; import utils.test.util.DynamoDBTestBase; /** * DynamoDB table used by {@link ProvisionedThroughputThrottlingIntegrationTest} */ public class BasicTempTableWithLowThroughput extends DynamoDBTableResource { public static final String TEMP_TABLE_NAME = "java-sdk-low-throughput-" + System.currentTimeMillis(); public static final String HASH_KEY_NAME = "hash"; public static final Long READ_CAPACITY = 1L; public static final Long WRITE_CAPACITY = 1L; public static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT = ProvisionedThroughput.builder().readCapacityUnits(READ_CAPACITY).writeCapacityUnits(WRITE_CAPACITY).build(); @Override protected DynamoDbClient getClient() { return DynamoDBTestBase.getClient(); } @Override protected CreateTableRequest getCreateTableRequest() { CreateTableRequest request = CreateTableRequest.builder() .tableName(TEMP_TABLE_NAME) .keySchema( KeySchemaElement.builder().attributeName(HASH_KEY_NAME) .keyType(KeyType.HASH).build()) .attributeDefinitions( AttributeDefinition.builder().attributeName( HASH_KEY_NAME).attributeType( ScalarAttributeType.S).build()) .provisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT) .build(); return request; } }
4,732
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/tables/TestTableForParallelScan.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources.tables; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import utils.test.resources.DynamoDBTableResource; import utils.test.util.DynamoDBTestBase; /** * Test table for {@link ParallelScanIntegrationTest} */ public class TestTableForParallelScan extends DynamoDBTableResource { public static final String TABLE_NAME = "java-sdk-parallel-scan"; public static final String HASH_KEY_NAME = "hash"; public static final Long READ_CAPACITY = 10L; public static final Long WRITE_CAPACITY = 5L; public static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT = ProvisionedThroughput.builder().readCapacityUnits(READ_CAPACITY).writeCapacityUnits(WRITE_CAPACITY).build(); @Override protected DynamoDbClient getClient() { return DynamoDBTestBase.getClient(); } @Override protected CreateTableRequest getCreateTableRequest() { CreateTableRequest createTableRequest = CreateTableRequest.builder() .tableName(TABLE_NAME) .keySchema( KeySchemaElement.builder().attributeName(HASH_KEY_NAME) .keyType(KeyType.HASH).build()) .attributeDefinitions( AttributeDefinition.builder().attributeName( HASH_KEY_NAME).attributeType( ScalarAttributeType.N).build()) .provisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT) .build(); return createTableRequest; } }
4,733
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/global
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/global/handlers/TestGlobalExecutionInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.global.handlers; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; public class TestGlobalExecutionInterceptor implements ExecutionInterceptor { private static boolean wasCalled = false; public static void reset() { wasCalled = false; } public static boolean wasCalled() { return wasCalled; } @Override public void beforeMarshalling(Context.BeforeMarshalling context, ExecutionAttributes executionAttributes) { wasCalled = true; } }
4,734
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/GlobalRequestHandlerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; 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.SdkException; import software.amazon.awssdk.global.handlers.TestGlobalExecutionInterceptor; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest; public class GlobalRequestHandlerTest { @BeforeEach public void setup() { TestGlobalExecutionInterceptor.reset(); } @Test public void clientCreatedWithConstructor_RegistersGlobalHandlers() { assertFalse(TestGlobalExecutionInterceptor.wasCalled()); DynamoDbClient client = DynamoDbClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2) .build(); callApi(client); assertTrue(TestGlobalExecutionInterceptor.wasCalled()); } @Test public void clientCreatedWithBuilder_RegistersGlobalHandlers() { assertFalse(TestGlobalExecutionInterceptor.wasCalled()); DynamoDbClient client = DynamoDbClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2) .build(); callApi(client); assertTrue(TestGlobalExecutionInterceptor.wasCalled()); } private void callApi(DynamoDbClient client) { try { client.listTables(ListTablesRequest.builder().build()); } catch (SdkException expected) { // Ignored or expected. } } }
4,735
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/PutItemRequestMarshallerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import static org.junit.jupiter.api.Assertions.assertEquals; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkBytes; 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.json.AwsJsonProtocol; import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.transform.PutItemRequestMarshaller; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.ImmutableMap; public class PutItemRequestMarshallerTest { private static final ObjectMapper MAPPER = new ObjectMapper(); private final PutItemRequestMarshaller marshaller = new PutItemRequestMarshaller( AwsJsonProtocolFactory.builder() .clientConfiguration( SdkClientConfiguration.builder() .option(SdkClientOption.ENDPOINT, URI.create("http://localhost")) .build()) .protocolVersion("1.1") .protocol(AwsJsonProtocol.AWS_JSON) .build()); /**l * Regression test for TT0075355961 */ @Test public void onlyRemainingByteBufferDataIsMarshalled() throws IOException { final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 1, 1}); // Consume some of the byte buffer byteBuffer.position(3); SdkHttpFullRequest marshalled = marshaller.marshall(PutItemRequest.builder().item( ImmutableMap.of("binaryProp", AttributeValue.builder().b(SdkBytes.fromByteBuffer(byteBuffer)).build())).build()); JsonNode marshalledContent = MAPPER.readTree(marshalled.contentStreamProvider().get().newStream()); String base64Binary = marshalledContent.get("Item").get("binaryProp").get("B").asText(); // Only the remaining data in the byte buffer should have been read and marshalled. assertEquals(BinaryUtils.toBase64(new byte[] {1, 1, 1}), base64Binary); } }
4,736
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/WaitersUserAgentTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; 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.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertTrue; import com.github.tomakehurst.wiremock.common.ConsoleNotifier; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.util.concurrent.CompletableFuture; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; 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.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbAsyncWaiter; import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter; public class WaitersUserAgentTest { @Rule public WireMockRule mockServer = new WireMockRule(options().notifier(new ConsoleNotifier(true)).dynamicHttpsPort().dynamicPort()); private DynamoDbClient dynamoDbClient; private DynamoDbAsyncClient dynamoDbAsyncClient; private ExecutionInterceptor interceptor; @Before public void setup() { interceptor = Mockito.spy(AbstractExecutionInterceptor.class); dynamoDbClient = DynamoDbClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) .region(Region.US_WEST_2) .endpointOverride(URI.create("http://localhost:" + mockServer.port())) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)) .build(); dynamoDbAsyncClient = DynamoDbAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials .create("test", "test"))) .region(Region.US_WEST_2) .endpointOverride(URI.create("http://localhost:" + mockServer.port())) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)) .build(); } @Test public void syncWaiters_shouldHaveWaitersUserAgent() { stubFor(any(urlEqualTo("/")).willReturn(aResponse().withStatus(500))); DynamoDbWaiter waiter = dynamoDbClient.waiter(); assertThatThrownBy(() -> waiter.waitUntilTableExists(DescribeTableRequest.builder().tableName("table").build())).isNotNull(); ArgumentCaptor<Context.BeforeTransmission> context = ArgumentCaptor.forClass(Context.BeforeTransmission.class); Mockito.verify(interceptor).beforeTransmission(context.capture(), ArgumentMatchers.any()); assertTrue(context.getValue().httpRequest().headers().get("User-Agent").toString().contains("waiter")); } @Test public void asyncWaiters_shouldHaveWaitersUserAgent() { DynamoDbAsyncWaiter waiter = dynamoDbAsyncClient.waiter(); CompletableFuture<WaiterResponse<DescribeTableResponse>> responseFuture = waiter.waitUntilTableExists(DescribeTableRequest.builder().tableName("table").build()); ArgumentCaptor<Context.BeforeTransmission> context = ArgumentCaptor.forClass(Context.BeforeTransmission.class); Mockito.verify(interceptor).beforeTransmission(context.capture(), ArgumentMatchers.any()); assertTrue(context.getValue().httpRequest().headers().get("User-Agent").toString().contains("waiter")); responseFuture.cancel(true); } public static abstract class AbstractExecutionInterceptor implements ExecutionInterceptor { @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { throw new RuntimeException("Interrupting the request."); } } }
4,737
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/EmptyAttributeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; 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.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.util.Collections; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.GetRecordsResponse; import software.amazon.awssdk.services.dynamodb.model.StreamRecord; import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsAsyncClient; import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsClient; public class EmptyAttributeTest { private static final AttributeValue EMPTY_STRING = AttributeValue.builder().s("").build(); private static final AttributeValue EMPTY_BINARY = AttributeValue.builder().b(SdkBytes.fromByteArray(new byte[]{})).build(); @Rule public WireMockRule mockServer = new WireMockRule(0); private DynamoDbClient dynamoDbClient; private DynamoDbAsyncClient dynamoDbAsyncClient; private DynamoDbStreamsClient dynamoDbStreamsClient; private DynamoDbStreamsAsyncClient dynamoDbStreamsAsyncClient; @Before public void setup() { dynamoDbClient = DynamoDbClient.builder() .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) .region(Region.US_WEST_2) .endpointOverride(URI.create("http://localhost:" + mockServer.port())) .build(); dynamoDbAsyncClient = DynamoDbAsyncClient.builder() .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) .region(Region.US_WEST_2) .endpointOverride(URI.create("http://localhost:" + mockServer.port())) .build(); dynamoDbStreamsClient = DynamoDbStreamsClient.builder() .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) .region(Region.US_WEST_2) .endpointOverride(URI.create("http://localhost:" + mockServer.port())) .build(); dynamoDbStreamsAsyncClient = DynamoDbStreamsAsyncClient.builder() .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) .region(Region.US_WEST_2) .endpointOverride(URI.create("http://localhost:" + mockServer.port())) .build(); } @Test public void syncClient_getItem_emptyString() { stubFor(any(urlEqualTo("/")) .willReturn(aResponse().withStatus(200).withBody("{\"Item\": {\"attribute\": {\"S\": \"\"}}}"))); GetItemResponse response = dynamoDbClient.getItem(r -> r.tableName("test")); assertThat(response.item()).containsKey("attribute"); AttributeValue attributeValue = response.item().get("attribute"); assertThat(attributeValue.s()).isEmpty(); } @Test public void asyncClient_getItem_emptyString() { stubFor(any(urlEqualTo("/")) .willReturn(aResponse().withStatus(200).withBody("{\"Item\": {\"attribute\": {\"S\": \"\"}}}"))); GetItemResponse response = dynamoDbAsyncClient.getItem(r -> r.tableName("test")).join(); assertThat(response.item()).containsKey("attribute"); AttributeValue attributeValue = response.item().get("attribute"); assertThat(attributeValue.s()).isEmpty(); } @Test public void syncClient_getItem_emptyBinary() { stubFor(any(urlEqualTo("/")) .willReturn(aResponse().withStatus(200).withBody("{\"Item\": {\"attribute\": {\"B\": \"\"}}}"))); GetItemResponse response = dynamoDbClient.getItem(r -> r.tableName("test")); assertThat(response.item()).containsKey("attribute"); AttributeValue attributeValue = response.item().get("attribute"); assertThat(attributeValue.b().asByteArray()).isEmpty(); } @Test public void asyncClient_getItem_emptyBinary() { stubFor(any(urlEqualTo("/")) .willReturn(aResponse().withStatus(200).withBody("{\"Item\": {\"attribute\": {\"B\": \"\"}}}"))); GetItemResponse response = dynamoDbAsyncClient.getItem(r -> r.tableName("test")).join(); assertThat(response.item()).containsKey("attribute"); AttributeValue attributeValue = response.item().get("attribute"); assertThat(attributeValue.b().asByteArray()).isEmpty(); } @Test public void syncClient_putItem_emptyString() { stubFor(any(urlEqualTo("/")).willReturn((aResponse().withStatus(200)))); dynamoDbClient.putItem(r -> r.item(Collections.singletonMap("stringAttribute", EMPTY_STRING))); verify(postRequestedFor(urlEqualTo("/")) .withRequestBody(equalTo("{\"Item\":{\"stringAttribute\":{\"S\":\"\"}}}"))); } @Test public void asyncClient_putItem_emptyString() { stubFor(any(urlEqualTo("/")).willReturn((aResponse().withStatus(200)))); dynamoDbAsyncClient.putItem(r -> r.item(Collections.singletonMap("stringAttribute", EMPTY_STRING))).join(); verify(postRequestedFor(urlEqualTo("/")) .withRequestBody(equalTo("{\"Item\":{\"stringAttribute\":{\"S\":\"\"}}}"))); } @Test public void syncClient_putItem_emptyBinary() { stubFor(any(urlEqualTo("/")).willReturn((aResponse().withStatus(200)))); dynamoDbClient.putItem(r -> r.item(Collections.singletonMap("binaryAttribute", EMPTY_BINARY))); verify(postRequestedFor(urlEqualTo("/")) .withRequestBody(equalTo("{\"Item\":{\"binaryAttribute\":{\"B\":\"\"}}}"))); } @Test public void asyncClient_putItem_emptyStrring() { stubFor(any(urlEqualTo("/")).willReturn((aResponse().withStatus(200)))); dynamoDbAsyncClient.putItem(r -> r.item(Collections.singletonMap("binaryAttribute", EMPTY_BINARY))).join(); verify(postRequestedFor(urlEqualTo("/")) .withRequestBody(equalTo("{\"Item\":{\"binaryAttribute\":{\"B\":\"\"}}}"))); } @Test public void syncClient_getRecords_emptyString() { stubFor(any(urlEqualTo("/")) .willReturn(aResponse().withStatus(200).withBody( "{" + " \"NextShardIterator\": \"arn:aws:dynamodb:us-west-2:111122223333:table/Forum/stream/2015-05-20T20:51:10.252|1|AAAAAAAAAAGQBYshYDEe\",\n" + " \"Records\": [\n" + " {\n" + " \"awsRegion\": \"us-west-2\",\n" + " \"dynamodb\": {\n" + " \"ApproximateCreationDateTime\": 1.46480431E9,\n" + " \"Keys\": {\n" + " \"stringKey\": {\"S\": \"DynamoDB\"}\n" + " },\n" + " \"NewImage\": {\n" + " \"stringAttribute\": {\"S\": \"\"}\n" + " },\n" + " \"OldImage\": {\n" + " \"stringAttribute\": {\"S\": \"\"}\n" + " },\n" + " \"SequenceNumber\": \"300000000000000499659\",\n" + " \"SizeBytes\": 41,\n" + " \"StreamViewType\": \"NEW_AND_OLD_IMAGES\"\n" + " },\n" + " \"eventID\": \"e2fd9c34eff2d779b297b26f5fef4206\",\n" + " \"eventName\": \"INSERT\",\n" + " \"eventSource\": \"aws:dynamodb\",\n" + " \"eventVersion\": \"1.0\"\n" + " }\n" + " ]\n" + "}"))); GetRecordsResponse response = dynamoDbStreamsClient.getRecords(r -> r.shardIterator("test")); assertThat(response.records()).hasSize(1); StreamRecord record = response.records().get(0).dynamodb(); assertThat(record.oldImage()).containsEntry("stringAttribute", EMPTY_STRING); assertThat(record.newImage()).containsEntry("stringAttribute", EMPTY_STRING); } @Test public void asyncClient_getRecords_emptyString() { stubFor(any(urlEqualTo("/")) .willReturn(aResponse().withStatus(200).withBody( "{" + " \"NextShardIterator\": \"arn:aws:dynamodb:us-west-2:111122223333:table/Forum/stream/2015-05-20T20:51:10.252|1|AAAAAAAAAAGQBYshYDEe\",\n" + " \"Records\": [\n" + " {\n" + " \"awsRegion\": \"us-west-2\",\n" + " \"dynamodb\": {\n" + " \"ApproximateCreationDateTime\": 1.46480431E9,\n" + " \"Keys\": {\n" + " \"stringKey\": {\"S\": \"DynamoDB\"}\n" + " },\n" + " \"NewImage\": {\n" + " \"stringAttribute\": {\"S\": \"\"}\n" + " },\n" + " \"OldImage\": {\n" + " \"stringAttribute\": {\"S\": \"\"}\n" + " },\n" + " \"SequenceNumber\": \"300000000000000499659\",\n" + " \"SizeBytes\": 41,\n" + " \"StreamViewType\": \"NEW_AND_OLD_IMAGES\"\n" + " },\n" + " \"eventID\": \"e2fd9c34eff2d779b297b26f5fef4206\",\n" + " \"eventName\": \"INSERT\",\n" + " \"eventSource\": \"aws:dynamodb\",\n" + " \"eventVersion\": \"1.0\"\n" + " }\n" + " ]\n" + "}"))); GetRecordsResponse response = dynamoDbStreamsAsyncClient.getRecords(r -> r.shardIterator("test")).join(); assertThat(response.records()).hasSize(1); StreamRecord record = response.records().get(0).dynamodb(); assertThat(record.oldImage()).containsEntry("stringAttribute", EMPTY_STRING); assertThat(record.newImage()).containsEntry("stringAttribute", EMPTY_STRING); } @Test public void syncClient_getRecords_emptyBinary() { stubFor(any(urlEqualTo("/")) .willReturn(aResponse().withStatus(200).withBody( "{" + " \"NextShardIterator\": \"arn:aws:dynamodb:us-west-2:111122223333:table/Forum/stream/2015-05-20T20:51:10.252|1|AAAAAAAAAAGQBYshYDEe\",\n" + " \"Records\": [\n" + " {\n" + " \"awsRegion\": \"us-west-2\",\n" + " \"dynamodb\": {\n" + " \"ApproximateCreationDateTime\": 1.46480431E9,\n" + " \"Keys\": {\n" + " \"stringKey\": {\"S\": \"DynamoDB\"}\n" + " },\n" + " \"NewImage\": {\n" + " \"binaryAttribute\": {\"B\": \"\"}\n" + " },\n" + " \"OldImage\": {\n" + " \"binaryAttribute\": {\"B\": \"\"}\n" + " },\n" + " \"SequenceNumber\": \"300000000000000499659\",\n" + " \"SizeBytes\": 41,\n" + " \"StreamViewType\": \"NEW_AND_OLD_IMAGES\"\n" + " },\n" + " \"eventID\": \"e2fd9c34eff2d779b297b26f5fef4206\",\n" + " \"eventName\": \"INSERT\",\n" + " \"eventSource\": \"aws:dynamodb\",\n" + " \"eventVersion\": \"1.0\"\n" + " }\n" + " ]\n" + "}"))); GetRecordsResponse response = dynamoDbStreamsClient.getRecords(r -> r.shardIterator("test")); assertThat(response.records()).hasSize(1); StreamRecord record = response.records().get(0).dynamodb(); assertThat(record.oldImage()).containsEntry("binaryAttribute", EMPTY_BINARY); assertThat(record.newImage()).containsEntry("binaryAttribute", EMPTY_BINARY); } @Test public void asyncClient_getRecords_emptyBinary() { stubFor(any(urlEqualTo("/")) .willReturn(aResponse().withStatus(200).withBody( "{" + " \"NextShardIterator\": \"arn:aws:dynamodb:us-west-2:111122223333:table/Forum/stream/2015-05-20T20:51:10.252|1|AAAAAAAAAAGQBYshYDEe\",\n" + " \"Records\": [\n" + " {\n" + " \"awsRegion\": \"us-west-2\",\n" + " \"dynamodb\": {\n" + " \"ApproximateCreationDateTime\": 1.46480431E9,\n" + " \"Keys\": {\n" + " \"stringKey\": {\"S\": \"DynamoDB\"}\n" + " },\n" + " \"NewImage\": {\n" + " \"binaryAttribute\": {\"B\": \"\"}\n" + " },\n" + " \"OldImage\": {\n" + " \"binaryAttribute\": {\"B\": \"\"}\n" + " },\n" + " \"SequenceNumber\": \"300000000000000499659\",\n" + " \"SizeBytes\": 41,\n" + " \"StreamViewType\": \"NEW_AND_OLD_IMAGES\"\n" + " },\n" + " \"eventID\": \"e2fd9c34eff2d779b297b26f5fef4206\",\n" + " \"eventName\": \"INSERT\",\n" + " \"eventSource\": \"aws:dynamodb\",\n" + " \"eventVersion\": \"1.0\"\n" + " }\n" + " ]\n" + "}"))); GetRecordsResponse response = dynamoDbStreamsAsyncClient.getRecords(r -> r.shardIterator("test")).join(); assertThat(response.records()).hasSize(1); StreamRecord record = response.records().get(0).dynamodb(); assertThat(record.oldImage()).containsEntry("binaryAttribute", EMPTY_BINARY); assertThat(record.newImage()).containsEntry("binaryAttribute", EMPTY_BINARY); } }
4,738
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/PaginatorInUserAgentTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; 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.containing; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URI; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.util.VersionInfo; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.paginators.QueryPublisher; public class PaginatorInUserAgentTest { @Rule public WireMockRule mockServer = new WireMockRule(0); private DynamoDbClient dynamoDbClient; private DynamoDbAsyncClient dynamoDbAsyncClient; @Before public void setup() { dynamoDbClient = DynamoDbClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) .region(Region.US_WEST_2).endpointOverride(URI.create("http://localhost:" + mockServer .port())) .build(); dynamoDbAsyncClient = DynamoDbAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials .create("test", "test"))) .region(Region.US_WEST_2).endpointOverride(URI.create("http://localhost:" + mockServer.port())) .build(); } @Test public void syncPaginator_shouldHavePaginatorUserAgent() throws IOException { stubFor(any(urlEqualTo("/")) .willReturn(aResponse() .withStatus(500))); try { dynamoDbClient.queryPaginator(b -> b.tableName("test")).items().iterator().next(); } catch (Exception e) { //expected } verify(postRequestedFor(urlEqualTo("/")).withHeader("User-Agent", containing("PAGINATED/" + VersionInfo.SDK_VERSION))); } @Test public void asyncPaginator_shouldHavePaginatorUserAgent() throws IOException { stubFor(any(urlEqualTo("/")) .willReturn(aResponse() .withStatus(500))); try { QueryPublisher queryPublisher = dynamoDbAsyncClient.queryPaginator(b -> b.tableName("test")); queryPublisher.items().subscribe(a -> a.get("")).get(); } catch (Exception e) { //expected } verify(postRequestedFor(urlEqualTo("/")).withHeader("User-Agent", containing("PAGINATED/" + VersionInfo.SDK_VERSION))); } }
4,739
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/EndpointDiscoveryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.StringInputStream; public class EndpointDiscoveryTest { @Test(timeout = 10_000) public void canBeEnabledViaProfileOnOverrideConfiguration() throws InterruptedException { ExecutionInterceptor interceptor = Mockito.spy(AbstractExecutionInterceptor.class); String profileFileContent = "[default]\n" + "aws_endpoint_discovery_enabled = true"; ProfileFile profileFile = ProfileFile.builder() .type(ProfileFile.Type.CONFIGURATION) .content(new StringInputStream(profileFileContent)) .build(); DynamoDbClient dynamoDb = DynamoDbClient.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(c -> c.defaultProfileFile(profileFile) .defaultProfileName("default") .addExecutionInterceptor(interceptor) .retryPolicy(r -> r.numRetries(0))) .build(); assertThatThrownBy(dynamoDb::listTables).isInstanceOf(SdkException.class); ArgumentCaptor<Context.BeforeTransmission> context; do { Thread.sleep(1); context = ArgumentCaptor.forClass(Context.BeforeTransmission.class); Mockito.verify(interceptor, atLeastOnce()).beforeTransmission(context.capture(), any()); } while (context.getAllValues().size() < 2); assertThat(context.getAllValues() .stream() .anyMatch(v -> v.httpRequest() .firstMatchingHeader("X-Amz-Target") .map(h -> h.equals("DynamoDB_20120810.DescribeEndpoints")) .orElse(false))) .isTrue(); } public static abstract class AbstractExecutionInterceptor implements ExecutionInterceptor {} }
4,740
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/software/amazon/awssdk/services/dynamodb/DynamoDbRetryPolicyTest.java
package software.amazon.awssdk.services.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FullJitterBackoffStrategy; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.StringInputStream; class DynamoDbRetryPolicyTest { private EnvironmentVariableHelper environmentVariableHelper; @BeforeEach public void setup() { environmentVariableHelper = new EnvironmentVariableHelper(); } @AfterEach public void reset() { environmentVariableHelper.reset(); } @Test void test_numRetries_with_standardRetryPolicy() { environmentVariableHelper.set(SdkSystemSetting.AWS_RETRY_MODE.environmentVariable(), "standard"); final SdkClientConfiguration sdkClientConfiguration = SdkClientConfiguration.builder().build(); final RetryPolicy retryPolicy = DynamoDbRetryPolicy.resolveRetryPolicy(sdkClientConfiguration); assertThat(retryPolicy.numRetries()).isEqualTo(8); } @Test void test_numRetries_with_legacyRetryPolicy() { environmentVariableHelper.set(SdkSystemSetting.AWS_RETRY_MODE.environmentVariable(), "legacy"); final SdkClientConfiguration sdkClientConfiguration = SdkClientConfiguration.builder().build(); final RetryPolicy retryPolicy = DynamoDbRetryPolicy.resolveRetryPolicy(sdkClientConfiguration); assertThat(retryPolicy.numRetries()).isEqualTo(8); } @Test void test_backoffBaseDelay_with_standardRetryPolicy() { environmentVariableHelper.set(SdkSystemSetting.AWS_RETRY_MODE.environmentVariable(), "standard"); SdkClientConfiguration sdkClientConfiguration = SdkClientConfiguration.builder().build(); RetryPolicy retryPolicy = DynamoDbRetryPolicy.resolveRetryPolicy(sdkClientConfiguration); BackoffStrategy backoffStrategy = retryPolicy.backoffStrategy(); assertThat(backoffStrategy).isInstanceOfSatisfying(FullJitterBackoffStrategy.class, fjbs -> { assertThat(fjbs.toBuilder().baseDelay()).isEqualTo(Duration.ofMillis(25)); }); } @Test void resolve_retryModeSetInEnv_doesNotCallSupplier() { environmentVariableHelper.set(SdkSystemSetting.AWS_RETRY_MODE.environmentVariable(), "standard"); SdkClientConfiguration sdkClientConfiguration = SdkClientConfiguration.builder().build(); RetryPolicy retryPolicy = DynamoDbRetryPolicy.resolveRetryPolicy(sdkClientConfiguration); RetryMode retryMode = retryPolicy.retryMode(); assertThat(retryMode).isEqualTo(RetryMode.STANDARD); } @Test void resolve_retryModeSetWithEnvAndSupplier_resolvesFromEnv() { environmentVariableHelper.set(SdkSystemSetting.AWS_RETRY_MODE.environmentVariable(), "standard"); ProfileFile profileFile = ProfileFile.builder() .content(new StringInputStream("[profile default]\n" + "retry_mode = adaptive")) .type(ProfileFile.Type.CONFIGURATION) .build(); SdkClientConfiguration sdkClientConfiguration = SdkClientConfiguration .builder() .option(SdkClientOption.PROFILE_FILE_SUPPLIER, () -> profileFile) .option(SdkClientOption.PROFILE_NAME, "default") .build(); RetryPolicy retryPolicy = DynamoDbRetryPolicy.resolveRetryPolicy(sdkClientConfiguration); RetryMode retryMode = retryPolicy.retryMode(); assertThat(retryMode).isEqualTo(RetryMode.STANDARD); } @Test void resolve_retryModeSetWithSupplier_resolvesFromSupplier() { ProfileFile profileFile = ProfileFile.builder() .content(new StringInputStream("[profile default]\n" + "retry_mode = adaptive")) .type(ProfileFile.Type.CONFIGURATION) .build(); SdkClientConfiguration sdkClientConfiguration = SdkClientConfiguration .builder() .option(SdkClientOption.PROFILE_FILE_SUPPLIER, () -> profileFile) .option(SdkClientOption.PROFILE_NAME, "default") .build(); RetryPolicy retryPolicy = DynamoDbRetryPolicy.resolveRetryPolicy(sdkClientConfiguration); RetryMode retryMode = retryPolicy.retryMode(); assertThat(retryMode).isEqualTo(RetryMode.ADAPTIVE); } @Test void resolve_retryModeSetWithSdkClientOption_resolvesFromSdkClientOption() { ProfileFile profileFile = ProfileFile.builder() .content(new StringInputStream("[profile default]\n")) .type(ProfileFile.Type.CONFIGURATION) .build(); SdkClientConfiguration sdkClientConfiguration = SdkClientConfiguration .builder() .option(SdkClientOption.PROFILE_FILE_SUPPLIER, () -> profileFile) .option(SdkClientOption.PROFILE_NAME, "default") .option(SdkClientOption.DEFAULT_RETRY_MODE, RetryMode.STANDARD) .build(); RetryPolicy retryPolicy = DynamoDbRetryPolicy.resolveRetryPolicy(sdkClientConfiguration); RetryMode retryMode = retryPolicy.retryMode(); assertThat(retryMode).isEqualTo(RetryMode.STANDARD); } @Test void resolve_retryModeNotSetWithEnvNorSupplier_resolvesFromSdkDefault() { ProfileFile profileFile = ProfileFile.builder() .content(new StringInputStream("[profile default]\n")) .type(ProfileFile.Type.CONFIGURATION) .build(); SdkClientConfiguration sdkClientConfiguration = SdkClientConfiguration .builder() .option(SdkClientOption.PROFILE_FILE_SUPPLIER, () -> profileFile) .option(SdkClientOption.PROFILE_NAME, "default") .build(); RetryPolicy retryPolicy = DynamoDbRetryPolicy.resolveRetryPolicy(sdkClientConfiguration); RetryMode retryMode = retryPolicy.retryMode(); assertThat(retryMode).isEqualTo(RetryMode.LEGACY); } }
4,741
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/SignersIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import static org.junit.Assert.assertEquals; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER; import com.fasterxml.jackson.core.JsonProcessingException; import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.auth.signer.params.Aws4SignerParams; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Logger; import utils.resources.tables.BasicTempTable; import utils.test.util.DynamoDBTestBase; import utils.test.util.TableUtils; public class SignersIntegrationTest extends DynamoDBTestBase { private static final Logger log = Logger.loggerFor(SignersIntegrationTest.class); private static final String TABLE_NAME = BasicTempTable.TEMP_TABLE_NAME; private static final String HASH_KEY_NAME = BasicTempTable.HASH_KEY_NAME; private static final String HASH_KEY_VALUE = "123789"; private static final String ATTRIBUTE_FOO = "foo"; private static final String ATTRIBUTE_FOO_VALUE = "bar"; private static final AwsCredentials awsCredentials = CREDENTIALS_PROVIDER_CHAIN.resolveCredentials(); private static final String SIGNING_NAME = "dynamodb"; @BeforeClass public static void setUpFixture() throws Exception { DynamoDBTestBase.setUpTestBase(); dynamo.createTable(CreateTableRequest.builder().tableName(TABLE_NAME) .keySchema(KeySchemaElement.builder().keyType(KeyType.HASH) .attributeName(HASH_KEY_NAME) .build()) .attributeDefinitions(AttributeDefinition.builder() .attributeType(ScalarAttributeType.S) .attributeName(HASH_KEY_NAME) .build()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(5L) .writeCapacityUnits(5L) .build()) .build()); TableUtils.waitUntilActive(dynamo, TABLE_NAME); putTestData(); } private static void putTestData() { Map<String, AttributeValue> item = new HashMap(); item.put(HASH_KEY_NAME, AttributeValue.builder().s(HASH_KEY_VALUE).build()); item.put(ATTRIBUTE_FOO, AttributeValue.builder().s(ATTRIBUTE_FOO_VALUE).build()); dynamo.putItem(PutItemRequest.builder().tableName(TABLE_NAME).item(item).build()); } @AfterClass public static void cleanUpFixture() { boolean deleteWorked = Waiter.run(() -> dynamo.deleteTable(r -> r.tableName(TABLE_NAME))) .ignoringException(DynamoDbException.class) .orReturnFalse(); if (!deleteWorked) { log.warn(() -> "Ignoring failure to delete table: " + TABLE_NAME); } } @Test public void test_UsingSdkDefaultClient() throws JsonProcessingException { getItemAndAssertValues(dynamo); } @Test public void test_UsingSdkClient_WithSignerSetInConfig() { DynamoDbClient client = getClientBuilder() .overrideConfiguration(ClientOverrideConfiguration.builder() .putAdvancedOption(SIGNER, Aws4Signer.create()) .build()) .build(); getItemAndAssertValues(client); } @Test public void sign_WithoutUsingSdkClient_ThroughExecutionAttributes() throws Exception { Aws4Signer signer = Aws4Signer.create(); SdkHttpFullRequest httpFullRequest = generateBasicRequest(); // sign the request SdkHttpFullRequest signedRequest = signer.sign(httpFullRequest, constructExecutionAttributes()); SdkHttpClient httpClient = ApacheHttpClient.builder().build(); HttpExecuteRequest request = HttpExecuteRequest.builder() .request(signedRequest) .contentStreamProvider(signedRequest.contentStreamProvider().orElse(null)) .build(); HttpExecuteResponse response = httpClient.prepareRequest(request) .call(); assertEquals("Non success http status code", 200, response.httpResponse().statusCode()); String actualResult = IoUtils.toUtf8String(response.responseBody().get()); assertEquals(getExpectedResult(), actualResult); } @Test public void test_SignMethod_WithModeledParam_And_WithoutUsingSdkClient() throws Exception { Aws4Signer signer = Aws4Signer.create(); SdkHttpFullRequest httpFullRequest = generateBasicRequest(); // sign the request SdkHttpFullRequest signedRequest = signer.sign(httpFullRequest, constructSignerParams()); SdkHttpClient httpClient = ApacheHttpClient.builder().build(); HttpExecuteRequest request = HttpExecuteRequest.builder() .request(signedRequest) .contentStreamProvider(signedRequest.contentStreamProvider().orElse(null)) .build(); HttpExecuteResponse response = httpClient.prepareRequest(request) .call(); assertEquals("Non success http status code", 200, response.httpResponse().statusCode()); String actualResult = IoUtils.toUtf8String(response.responseBody().get()); assertEquals(getExpectedResult(), actualResult); } private SdkHttpFullRequest generateBasicRequest() { final String content = getInputContent(); return SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream(content.getBytes())) .method(SdkHttpMethod.POST) .putHeader("Content-Length", Integer.toString(content.length())) .putHeader("Content-Type", "application/x-amz-json-1.0") .putHeader("X-Amz-Target", "DynamoDB_20120810.GetItem") .encodedPath("/") .protocol("https") .host(getHost()) .build(); } private String getHost() { return String.format("dynamodb.%s.amazonaws.com", REGION.id()); } private String getInputContent() { return "{ \n" + " \"TableName\":\"" + TABLE_NAME + "\",\n" + " \"Key\":{ \n" + " \"" + HASH_KEY_NAME + "\":{ \n" + " \"S\":\"" + HASH_KEY_VALUE + "\"\n" + " }\n" + " },\n" + " \"ConsistentRead\": true" + "}".trim(); } private String getExpectedResult() { String result = "{" + " \"Item\":{" + " \"" + HASH_KEY_NAME + "\":{" + " \"S\":\"" + HASH_KEY_VALUE + "\"" + " }," + " \"" + ATTRIBUTE_FOO + "\":{" + " \"S\":\"" + ATTRIBUTE_FOO_VALUE + "\"" + " }" + " }" + "}"; return result.replaceAll("\\s", ""); } private void getItemAndAssertValues(DynamoDbClient client) { Map<String, AttributeValue> item = client.getItem(GetItemRequest.builder() .tableName(TABLE_NAME) .consistentRead(true) .key(Collections.singletonMap(HASH_KEY_NAME, AttributeValue.builder() .s(HASH_KEY_VALUE) .build())) .build()) .item(); assertEquals(HASH_KEY_VALUE, item.get(HASH_KEY_NAME).s()); assertEquals(ATTRIBUTE_FOO_VALUE, item.get(ATTRIBUTE_FOO).s()); } private Aws4SignerParams constructSignerParams() { return Aws4SignerParams.builder() .awsCredentials(awsCredentials) .signingName(SIGNING_NAME) .signingRegion(REGION) .build(); } private ExecutionAttributes constructExecutionAttributes() { return new ExecutionAttributes() .putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, awsCredentials) .putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, SIGNING_NAME) .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, REGION) .putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, Boolean.TRUE); } private static DynamoDbClientBuilder getClientBuilder() { return DynamoDbClient.builder() .region(REGION) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN); } }
4,742
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/ParallelScanIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import static org.junit.Assert.assertEquals; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ComparisonOperator; import software.amazon.awssdk.services.dynamodb.model.Condition; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; import utils.resources.RequiredResources; import utils.resources.RequiredResources.RequiredResource; import utils.resources.RequiredResources.ResourceCreationPolicy; import utils.resources.RequiredResources.ResourceRetentionPolicy; import utils.resources.ResourceCentricBlockJUnit4ClassRunner; import utils.resources.tables.TestTableForParallelScan; import utils.test.util.DynamoDBTestBase; /** * DynamoDB integration tests on the low-level parallel scan operation. */ @RunWith(ResourceCentricBlockJUnit4ClassRunner.class) @RequiredResources({ @RequiredResource(resource = TestTableForParallelScan.class, creationPolicy = ResourceCreationPolicy.REUSE_EXISTING, retentionPolicy = ResourceRetentionPolicy.KEEP) }) public class ParallelScanIntegrationTest extends DynamoDBTestBase { private static final String tableName = TestTableForParallelScan.TABLE_NAME; private static final String HASH_KEY_NAME = TestTableForParallelScan.HASH_KEY_NAME; private static final String ATTRIBUTE_FOO = "attribute_foo"; private static final String ATTRIBUTE_BAR = "attribute_bar"; private static final String ATTRIBUTE_RANDOM = "attribute_random"; private static final int itemNumber = 200; /** * Creates a test table with a local secondary index */ @BeforeClass public static void setUp() { DynamoDBTestBase.setUpTestBase(); } private static void putTestData() { Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); Random random = new Random(); for (int hashKeyValue = 0; hashKeyValue < itemNumber; hashKeyValue++) { item.put(HASH_KEY_NAME, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build()); item.put(ATTRIBUTE_RANDOM, AttributeValue.builder().n(Integer.toString(random.nextInt(itemNumber))).build()); if (hashKeyValue < itemNumber / 2) { item.put(ATTRIBUTE_FOO, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build()); } else { item.put(ATTRIBUTE_BAR, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build()); } dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).build()); item.clear(); } } /** * Tests making parallel scan on DynamoDB table. */ @Test public void testParallelScan() { putTestData(); /** * Only one segment. */ ScanRequest scanRequest = ScanRequest.builder() .tableName(tableName) .scanFilter(Collections.singletonMap( ATTRIBUTE_RANDOM, Condition.builder() .attributeValueList( AttributeValue.builder().n("" + itemNumber / 2).build()) .comparisonOperator( ComparisonOperator.LT.toString()).build())) .totalSegments(1).segment(0).build(); ScanResponse scanResult = dynamo.scan(scanRequest); assertEquals((Object) itemNumber, (Object) scanResult.scannedCount()); int filteredItems = scanResult.count(); /** * Multiple segments. */ int totalSegments = 10; int filteredItemsInsegments = 0; for (int segment = 0; segment < totalSegments; segment++) { scanRequest = ScanRequest.builder() .tableName(tableName) .scanFilter( Collections.singletonMap( ATTRIBUTE_RANDOM, Condition.builder().attributeValueList( AttributeValue.builder().n("" + itemNumber / 2).build()) .comparisonOperator( ComparisonOperator.LT .toString()).build())) .totalSegments(totalSegments).segment(segment).build(); scanResult = dynamo.scan(scanRequest); filteredItemsInsegments += scanResult.count(); } assertEquals(filteredItems, filteredItemsInsegments); } }
4,743
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/DynamoDbJavaClientExceptionIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import java.util.UUID; import junit.framework.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Simple smoke test to make sure the new JSON error unmarshaller works as expected. */ public class DynamoDbJavaClientExceptionIntegrationTest extends AwsTestBase { private static DynamoDbClient ddb; @BeforeClass public static void setup() throws Exception { setUpCredentials(); ddb = DynamoDbClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } @Test public void testResourceNotFoundException() { try { ddb.describeTable(DescribeTableRequest.builder().tableName(UUID.randomUUID().toString()).build()); Assert.fail("ResourceNotFoundException is expected."); } catch (ResourceNotFoundException e) { Assert.assertNotNull(e.awsErrorDetails().errorCode()); Assert.assertNotNull(e.awsErrorDetails().errorMessage()); Assert.assertNotNull(e.awsErrorDetails().rawResponse()); } } }
4,744
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/DynamoDbJavaClientRetryOnTimeoutIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import org.junit.Test; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.retry.conditions.OrRetryCondition; import software.amazon.awssdk.core.retry.conditions.RetryCondition; import software.amazon.awssdk.testutils.service.AwsTestBase; import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Simple test to check all the retries are made when all the API calls timeouts. */ public class DynamoDbJavaClientRetryOnTimeoutIntegrationTest extends AwsTestBase { private static DynamoDbClient ddb; private final Integer RETRY_ATTEMPTS = 3; public static void setupWithRetryPolicy(RetryPolicy retryPolicy, Integer attemptTimeOutMillis) throws Exception { ddb = DynamoDbClient.builder() .overrideConfiguration(ClientOverrideConfiguration.builder() .retryPolicy(retryPolicy) .apiCallAttemptTimeout(Duration.ofMillis(attemptTimeOutMillis)) //forces really quick api call timeout .build()) .build(); } public static RetryPolicy createRetryPolicyWithCounter(AtomicInteger counter, Integer numOfAttempts) { final RetryPolicy retryPolicy = RetryPolicy.defaultRetryPolicy().toBuilder() .numRetries(numOfAttempts) .retryCondition(OrRetryCondition.create( context -> { counter.incrementAndGet(); return false; }, RetryCondition.defaultRetryCondition())).build(); return retryPolicy; } @Test public void testRetryAttemptsOnTimeOut() throws Exception { AtomicInteger atomicInteger = new AtomicInteger(0); Boolean apiTimeOutExceptionOccurred = Boolean.FALSE; setupWithRetryPolicy(createRetryPolicyWithCounter(atomicInteger, RETRY_ATTEMPTS), 2); try { ddb.listTables(); } catch (ApiCallAttemptTimeoutException e) { apiTimeOutExceptionOccurred = true; } assertEquals(RETRY_ATTEMPTS.intValue(), atomicInteger.get()); assertTrue(apiTimeOutExceptionOccurred); } }
4,745
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/WaitersIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CompletableFuture; import org.assertj.core.api.Condition; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbAsyncWaiter; import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter; import utils.resources.tables.BasicTempTable; import utils.test.util.DynamoDBTestBase; public class WaitersIntegrationTest extends DynamoDBTestBase { private static final String TABLE_NAME = "java-sdk-waiter-test" + System.currentTimeMillis(); private static final String HASH_KEY_NAME = BasicTempTable.HASH_KEY_NAME; private static DynamoDbAsyncClient dynamoAsync; @BeforeClass public static void setUp() { DynamoDBTestBase.setUpTestBase(); dynamoAsync = DynamoDbAsyncClient.builder().region(REGION).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); dynamo.createTable(CreateTableRequest.builder().tableName(TABLE_NAME) .keySchema(KeySchemaElement.builder().keyType(KeyType.HASH) .attributeName(HASH_KEY_NAME) .build()) .attributeDefinitions(AttributeDefinition.builder() .attributeType(ScalarAttributeType.N) .attributeName(HASH_KEY_NAME) .build()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(5L) .writeCapacityUnits(5L) .build()) .build()); } @AfterClass public static void cleanUp() { dynamoAsync.deleteTable(DeleteTableRequest.builder().tableName(TABLE_NAME).build()); WaiterResponse<DescribeTableResponse> waiterResponse = dynamoAsync.waiter().waitUntilTableNotExists(b -> b.tableName(TABLE_NAME)).join(); assertThat(waiterResponse.matched().response()).isEmpty(); assertThat(waiterResponse.matched().exception()).hasValueSatisfying( new Condition<>(t -> t instanceof ResourceNotFoundException, "ResourceNotFoundException")); dynamo.close(); dynamoAsync.close(); } @Test public void checkTableExist_withSyncWaiter() { DynamoDbWaiter syncWaiter = dynamo.waiter(); WaiterResponse<DescribeTableResponse> response = syncWaiter.waitUntilTableExists( DescribeTableRequest.builder().tableName(TABLE_NAME).build()); assertThat(response.attemptsExecuted()).isGreaterThanOrEqualTo(1); assertThat(response.matched().response()).hasValueSatisfying(b -> assertThat(b.table().tableName()).isEqualTo(TABLE_NAME)); assertThat(response.matched().exception()).isEmpty(); } @Test public void checkTableExist_withAsyncWaiter() { DynamoDbAsyncWaiter asyncWaiter = dynamoAsync.waiter(); CompletableFuture<WaiterResponse<DescribeTableResponse>> responseFuture = asyncWaiter.waitUntilTableExists( DescribeTableRequest.builder().tableName(TABLE_NAME).build()); WaiterResponse<DescribeTableResponse> response = responseFuture.join(); assertThat(response.attemptsExecuted()).isGreaterThanOrEqualTo(1); assertThat(response.matched().response()).hasValueSatisfying(b -> assertThat(b.table().tableName()).isEqualTo(TABLE_NAME)); assertThat(response.matched().exception()).isEmpty(); } }
4,746
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/DynamoServiceIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static software.amazon.awssdk.testutils.SdkAsserts.assertNotEmpty; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.util.SdkAutoConstructMap; import software.amazon.awssdk.services.dynamodb.model.AttributeAction; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate; import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest; import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemRequest; import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse; import software.amazon.awssdk.services.dynamodb.model.ComparisonOperator; import software.amazon.awssdk.services.dynamodb.model.Condition; import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse; import software.amazon.awssdk.services.dynamodb.model.DeleteRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableResponse; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes; import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest; import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; import software.amazon.awssdk.services.dynamodb.model.TableDescription; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; import software.amazon.awssdk.services.dynamodb.model.WriteRequest; import utils.resources.RequiredResources; import utils.resources.RequiredResources.RequiredResource; import utils.resources.RequiredResources.ResourceCreationPolicy; import utils.resources.RequiredResources.ResourceRetentionPolicy; import utils.resources.ResourceCentricBlockJUnit4ClassRunner; import utils.resources.tables.BasicTempTable; import utils.resources.tables.TempTableWithBinaryKey; import utils.test.util.DynamoDBTestBase; @RunWith(ResourceCentricBlockJUnit4ClassRunner.class) @RequiredResources({ @RequiredResource(resource = BasicTempTable.class, creationPolicy = ResourceCreationPolicy.ALWAYS_RECREATE, retentionPolicy = ResourceRetentionPolicy.DESTROY_AFTER_ALL_TESTS), @RequiredResource(resource = TempTableWithBinaryKey.class, creationPolicy = ResourceCreationPolicy.ALWAYS_RECREATE, retentionPolicy = ResourceRetentionPolicy.DESTROY_AFTER_ALL_TESTS) }) public class DynamoServiceIntegrationTest extends DynamoDBTestBase { private static final String HASH_KEY_NAME = BasicTempTable.HASH_KEY_NAME; private static final String tableName = BasicTempTable.TEMP_TABLE_NAME; private static final String binaryKeyTableName = TempTableWithBinaryKey.TEMP_BINARY_TABLE_NAME; private static final Long READ_CAPACITY = BasicTempTable.READ_CAPACITY; private static final Long WRITE_CAPACITY = BasicTempTable.WRITE_CAPACITY; /** * The only @BeforeClass method. */ @BeforeClass public static void setUp() { DynamoDBTestBase.setUpTestBase(); } @Test @SuppressWarnings("unchecked") public void testNullQueryKeyErrorHandling() { Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); // Put a valid item first item.put(HASH_KEY_NAME, AttributeValue.builder().s("bar").build()); item.put("age", AttributeValue.builder().s("30").build()); PutItemRequest putItemRequest = PutItemRequest.builder().tableName(tableName).item(item).returnValues(ReturnValue.ALL_OLD .toString()).build(); dynamo.putItem(putItemRequest); Map<String, KeysAndAttributes> items = new HashMap<String, KeysAndAttributes>(); // Put a valid key and a null one items.put(tableName, KeysAndAttributes.builder().keys(mapKey(HASH_KEY_NAME, AttributeValue.builder().s("bar").build()), null).build()); BatchGetItemRequest request =BatchGetItemRequest.builder() .requestItems(items) .build(); try { dynamo.batchGetItem(request); } catch (AwsServiceException exception) { assertEquals("ValidationException", exception.awsErrorDetails().errorCode()); } Map<String, List<WriteRequest>> requestItems = new HashMap<String, List<WriteRequest>>(); List<WriteRequest> writeRequests = new ArrayList<WriteRequest>(); Map<String, AttributeValue> writeAttributes = new HashMap<String, AttributeValue>(); writeAttributes.put(HASH_KEY_NAME, AttributeValue.builder().s("" + System.currentTimeMillis()).build()); writeAttributes.put("bar", AttributeValue.builder().s("" + System.currentTimeMillis()).build()); writeRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(writeAttributes).build()).build()); writeRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(null).build()).build()); requestItems.put(tableName, writeRequests); try { dynamo.batchWriteItem(BatchWriteItemRequest.builder().requestItems(requestItems).build()); } catch (AwsServiceException exception) { assertEquals("ValidationException", exception.awsErrorDetails().errorCode()); } } /** * Tests that we correctly parse JSON error responses into SdkServiceException. */ @Test public void testErrorHandling() throws Exception { DeleteTableRequest request = DeleteTableRequest.builder().tableName("non-existent-table").build(); try { dynamo.deleteTable(request); fail("Expected an exception to be thrown"); } catch (AwsServiceException exception) { assertNotEmpty(exception.awsErrorDetails().errorCode()); assertNotEmpty(exception.awsErrorDetails().errorMessage()); assertNotEmpty(exception.requestId()); assertNotEmpty(exception.awsErrorDetails().serviceName()); assertTrue(exception.statusCode() >= 400); assertTrue(exception.statusCode() < 600); } } /** * Tests that we properly handle error responses for request entities that * are too large. */ // DISABLED because DynamoDB apparently upped their max request size; we // should be hitting this with a unit test that simulates an appropriate // SdkServiceException. // @Test public void testRequestEntityTooLargeErrorHandling() throws Exception { Map<String, KeysAndAttributes> items = new HashMap<String, KeysAndAttributes>(); for (int i = 0; i < 1024; i++) { KeysAndAttributes kaa = KeysAndAttributes.builder().build(); StringBuilder bigString = new StringBuilder(); for (int j = 0; j < 1024; j++) { bigString.append("a"); } bigString.append(i); items.put(bigString.toString(), kaa); } BatchGetItemRequest request = BatchGetItemRequest.builder().requestItems(items).build(); try { dynamo.batchGetItem(request); } catch (AwsServiceException exception) { assertNotNull(exception.getMessage()); assertEquals("Request entity too large", exception.awsErrorDetails().errorCode()); assertEquals(413, exception.statusCode()); } } @Test public void testBatchWriteTooManyItemsErrorHandling() throws Exception { int itemNumber = 26; HashMap<String, List<WriteRequest>> requestItems = new HashMap<String, List<WriteRequest>>(); List<WriteRequest> writeRequests = new ArrayList<WriteRequest>(); for (int i = 0; i < itemNumber; i++) { HashMap<String, AttributeValue> writeAttributes = new HashMap<String, AttributeValue>(); writeAttributes.put(HASH_KEY_NAME, AttributeValue.builder().s("" + System.currentTimeMillis()).build()); writeAttributes.put("bar", AttributeValue.builder().s("" + System.currentTimeMillis()).build()); writeRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(writeAttributes).build()).build()); } requestItems.put(tableName, writeRequests); try { dynamo.batchWriteItem(BatchWriteItemRequest.builder().requestItems(requestItems).build()); } catch (AwsServiceException exception) { assertEquals("ValidationException", exception.awsErrorDetails().errorCode()); assertNotEmpty(exception.awsErrorDetails().errorMessage()); assertNotEmpty(exception.requestId()); assertNotEmpty(exception.awsErrorDetails().serviceName()); assertEquals(400, exception.statusCode()); } } /** * Tests that we can call each service operation to create and describe * tables, put, update and delete data, and query. */ @Test public void testServiceOperations() throws Exception { // Describe all tables ListTablesResponse describeTablesResult = dynamo.listTables(ListTablesRequest.builder().build()); // Describe our new table DescribeTableRequest describeTablesRequest = DescribeTableRequest.builder().tableName(tableName).build(); TableDescription tableDescription = dynamo.describeTable(describeTablesRequest).table(); assertEquals(tableName, tableDescription.tableName()); assertNotNull(tableDescription.tableStatus()); assertEquals(HASH_KEY_NAME, tableDescription.keySchema().get(0).attributeName()); assertEquals(KeyType.HASH, tableDescription.keySchema().get(0).keyType()); assertNotNull(tableDescription.provisionedThroughput().numberOfDecreasesToday()); assertEquals(READ_CAPACITY, tableDescription.provisionedThroughput().readCapacityUnits()); assertEquals(WRITE_CAPACITY, tableDescription.provisionedThroughput().writeCapacityUnits()); // Add some data int contentLength = 1 * 1024; Set<SdkBytes> byteBufferSet = new HashSet<SdkBytes>(); byteBufferSet.add(SdkBytes.fromByteArray(generateByteArray(contentLength))); byteBufferSet.add(SdkBytes.fromByteArray(generateByteArray(contentLength + 1))); Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put(HASH_KEY_NAME, AttributeValue.builder().s("bar").build()); item.put("age", AttributeValue.builder().n("30").build()); item.put("bar", AttributeValue.builder().s("" + System.currentTimeMillis()).build()); item.put("foos", AttributeValue.builder().ss("bleh", "blah").build()); item.put("S", AttributeValue.builder().ss("ONE", "TWO").build()); item.put("blob", AttributeValue.builder().b(SdkBytes.fromByteArray(generateByteArray(contentLength))).build()); item.put("blobs", AttributeValue.builder().bs(SdkBytes.fromByteArray(generateByteArray(contentLength)), SdkBytes.fromByteArray(generateByteArray(contentLength + 1))).build()); item.put("BS", AttributeValue.builder().bs(byteBufferSet).build()); PutItemRequest putItemRequest = PutItemRequest.builder().tableName(tableName).item(item).returnValues(ReturnValue.ALL_OLD.toString()).build(); PutItemResponse putItemResult = dynamo.putItem(putItemRequest); // Get our new item GetItemResponse itemResult = dynamo.getItem(GetItemRequest.builder().tableName(tableName).key(mapKey(HASH_KEY_NAME, AttributeValue.builder().s("bar").build())) .consistentRead(true).build()); assertNotNull(itemResult.item().get("S").ss()); assertEquals(2, itemResult.item().get("S").ss().size()); assertTrue(itemResult.item().get("S").ss().contains("ONE")); assertTrue(itemResult.item().get("S").ss().contains("TWO")); assertEquals("30", itemResult.item().get("age").n()); assertNotNull(itemResult.item().get("bar").s()); assertNotNull(itemResult.item().get("blob").b()); assertTrue(itemResult.item().get("blob").b().equals(SdkBytes.fromByteArray(generateByteArray(contentLength)))); assertNotNull(itemResult.item().get("blobs").bs()); assertEquals(2, itemResult.item().get("blobs").bs().size()); assertTrue(itemResult.item().get("blobs").bs().contains(SdkBytes.fromByteArray(generateByteArray(contentLength)))); assertTrue(itemResult.item().get("blobs").bs().contains(SdkBytes.fromByteArray(generateByteArray(contentLength + 1)))); assertNotNull(itemResult.item().get("BS").bs()); assertEquals(2, itemResult.item().get("BS").bs().size()); assertTrue(itemResult.item().get("BS").bs().contains(SdkBytes.fromByteArray(generateByteArray(contentLength)))); assertTrue(itemResult.item().get("BS").bs().contains(SdkBytes.fromByteArray(generateByteArray(contentLength + 1)))); // Pause to try and deal with ProvisionedThroughputExceededExceptions Thread.sleep(1000 * 5); // Add some data into the table with binary hash key ByteBuffer byteBuffer = ByteBuffer.allocate(contentLength * 2); byteBuffer.put(generateByteArray(contentLength)); byteBuffer.flip(); item = new HashMap<String, AttributeValue>(); item.put(HASH_KEY_NAME, AttributeValue.builder().b(SdkBytes.fromByteBuffer(byteBuffer)).build()); // Reuse the byteBuffer item.put("blob", AttributeValue.builder().b(SdkBytes.fromByteBuffer(byteBuffer)).build()); item.put("blobs", AttributeValue.builder().bs(SdkBytes.fromByteArray(generateByteArray(contentLength)), SdkBytes.fromByteArray(generateByteArray(contentLength + 1))).build()); // Reuse the byteBufferSet item.put("BS", AttributeValue.builder().bs(byteBufferSet).build()); putItemRequest = PutItemRequest.builder().tableName(binaryKeyTableName).item(item).returnValues(ReturnValue.ALL_OLD.toString()).build(); dynamo.putItem(putItemRequest); // Get our new item itemResult = dynamo.getItem(GetItemRequest.builder().tableName(binaryKeyTableName).key(mapKey(HASH_KEY_NAME, AttributeValue.builder().b(SdkBytes.fromByteBuffer(byteBuffer)).build())) .consistentRead(true).build()); assertNotNull(itemResult.item().get("blob").b()); assertEquals(itemResult.item().get("blob").b(), SdkBytes.fromByteArray(generateByteArray(contentLength))); assertNotNull(itemResult.item().get("blobs").bs()); assertEquals(2, itemResult.item().get("blobs").bs().size()); assertTrue(itemResult.item().get("blobs").bs().contains(SdkBytes.fromByteArray(generateByteArray(contentLength)))); assertTrue(itemResult.item().get("blobs").bs().contains(SdkBytes.fromByteArray(generateByteArray(contentLength + 1)))); assertNotNull(itemResult.item().get("BS").bs()); assertEquals(2, itemResult.item().get("BS").bs().size()); assertTrue(itemResult.item().get("BS").bs().contains(SdkBytes.fromByteArray(generateByteArray(contentLength)))); assertTrue(itemResult.item().get("BS").bs().contains(SdkBytes.fromByteArray(generateByteArray(contentLength + 1)))); // Pause to try and deal with ProvisionedThroughputExceededExceptions Thread.sleep(1000 * 5); // Load some random data System.out.println("Loading data..."); Random random = new Random(); for (int i = 0; i < 50; i++) { item = new HashMap<String, AttributeValue>(); item.put(HASH_KEY_NAME, AttributeValue.builder().s("bar-" + System.currentTimeMillis()).build()); item.put("age", AttributeValue.builder().n(Integer.toString(random.nextInt(100) + 30)).build()); item.put("bar", AttributeValue.builder().s("" + System.currentTimeMillis()).build()); item.put("foos", AttributeValue.builder().ss("bleh", "blah").build()); dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).returnValues(ReturnValue.ALL_OLD.toString()).build()); } // Update an item Map<String, AttributeValueUpdate> itemUpdates = new HashMap<String, AttributeValueUpdate>(); itemUpdates.put("1", AttributeValueUpdate.builder().value(AttributeValue.builder().s("¢").build()).action(AttributeAction.PUT.toString()).build()); itemUpdates.put("foos", AttributeValueUpdate.builder().value(AttributeValue.builder().ss("foo").build()).action(AttributeAction.PUT.toString()).build()); itemUpdates.put("S", AttributeValueUpdate.builder().value(AttributeValue.builder().ss("THREE").build()).action(AttributeAction.ADD.toString()).build()); itemUpdates.put("age", AttributeValueUpdate.builder().value(AttributeValue.builder().n("10").build()).action(AttributeAction.ADD.toString()).build()); itemUpdates.put("blob", AttributeValueUpdate.builder().value( AttributeValue.builder().b(SdkBytes.fromByteArray(generateByteArray(contentLength + 1))).build()).action( AttributeAction.PUT.toString()).build()); itemUpdates.put("blobs", AttributeValueUpdate.builder().value(AttributeValue.builder().bs(SdkBytes.fromByteArray(generateByteArray(contentLength))).build()).action( AttributeAction.PUT.toString()).build()); UpdateItemRequest updateItemRequest = UpdateItemRequest.builder().tableName(tableName).key( mapKey(HASH_KEY_NAME, AttributeValue.builder().s("bar").build())).attributeUpdates( itemUpdates).returnValues("ALL_NEW").build(); UpdateItemResponse updateItemResult = dynamo.updateItem(updateItemRequest); assertEquals("¢", updateItemResult.attributes().get("1").s()); assertEquals(1, updateItemResult.attributes().get("foos").ss().size()); assertTrue(updateItemResult.attributes().get("foos").ss().contains("foo")); assertEquals(3, updateItemResult.attributes().get("S").ss().size()); assertTrue(updateItemResult.attributes().get("S").ss().contains("ONE")); assertTrue(updateItemResult.attributes().get("S").ss().contains("TWO")); assertTrue(updateItemResult.attributes().get("S").ss().contains("THREE")); assertEquals(Integer.toString(30 + 10), updateItemResult.attributes().get("age").n()); assertEquals(updateItemResult.attributes().get("blob").b(), SdkBytes.fromByteArray(generateByteArray(contentLength + 1))); assertEquals(1, updateItemResult.attributes().get("blobs").bs().size()); assertTrue(updateItemResult.attributes().get("blobs").bs() .contains(SdkBytes.fromByteArray(generateByteArray(contentLength)))); itemUpdates.clear(); itemUpdates.put("age", AttributeValueUpdate.builder().value(AttributeValue.builder().n("30").build()).action(AttributeAction.PUT.toString()).build()); itemUpdates.put("blobs", AttributeValueUpdate.builder() .value(AttributeValue.builder().bs(SdkBytes.fromByteArray(generateByteArray(contentLength + 1))).build()) .action(AttributeAction.ADD.toString()) .build()); updateItemRequest = UpdateItemRequest.builder() .tableName(tableName) .key(mapKey(HASH_KEY_NAME, AttributeValue.builder().s("bar").build())) .attributeUpdates(itemUpdates) .returnValues("ALL_NEW") .build(); updateItemResult = dynamo.updateItem(updateItemRequest); assertEquals("30", updateItemResult.attributes().get("age").n()); assertEquals(2, updateItemResult.attributes().get("blobs").bs().size()); assertTrue(updateItemResult.attributes().get("blobs").bs() .contains(SdkBytes.fromByteArray(generateByteArray(contentLength)))); assertTrue(updateItemResult.attributes().get("blobs").bs() .contains(SdkBytes.fromByteArray(generateByteArray(contentLength + 1)))); // Get an item that doesn't exist. GetItemRequest itemsRequest = GetItemRequest.builder().tableName(tableName).key(mapKey(HASH_KEY_NAME, AttributeValue.builder().s("3").build())) .consistentRead(true).build(); GetItemResponse itemsResult = dynamo.getItem(itemsRequest); assertTrue(itemsResult.item() instanceof SdkAutoConstructMap); // Get an item that doesn't have any attributes, itemsRequest = GetItemRequest.builder().tableName(tableName).key(mapKey(HASH_KEY_NAME, AttributeValue.builder().s("bar").build())) .consistentRead(true).attributesToGet("non-existent-attribute").build(); itemsResult = dynamo.getItem(itemsRequest); assertEquals(0, itemsResult.item().size()); // Scan data ScanRequest scanRequest = ScanRequest.builder().tableName(tableName).attributesToGet(HASH_KEY_NAME).build(); ScanResponse scanResult = dynamo.scan(scanRequest); assertTrue(scanResult.count() > 0); assertTrue(scanResult.scannedCount() > 0); // Try a more advanced Scan query and run it a few times for performance metrics System.out.println("Testing Scan..."); for (int i = 0; i < 10; i++) { HashMap<String, Condition> scanFilter = new HashMap<String, Condition>(); scanFilter.put("age", Condition.builder() .attributeValueList(AttributeValue.builder().n("40").build()) .comparisonOperator(ComparisonOperator.GT.toString()) .build()); scanRequest = ScanRequest.builder().tableName(tableName).scanFilter(scanFilter).build(); scanResult = dynamo.scan(scanRequest); } // Batch write HashMap<String, List<WriteRequest>> requestItems = new HashMap<String, List<WriteRequest>>(); List<WriteRequest> writeRequests = new ArrayList<WriteRequest>(); HashMap<String, AttributeValue> writeAttributes = new HashMap<String, AttributeValue>(); writeAttributes.put(HASH_KEY_NAME, AttributeValue.builder().s("" + System.currentTimeMillis()).build()); writeAttributes.put("bar", AttributeValue.builder().s("" + System.currentTimeMillis()).build()); writeRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(writeAttributes).build()).build()); writeRequests.add(WriteRequest.builder() .deleteRequest(DeleteRequest.builder() .key(mapKey(HASH_KEY_NAME, AttributeValue.builder().s("toDelete").build())) .build()) .build()); requestItems.put(tableName, writeRequests); BatchWriteItemResponse batchWriteItem = dynamo.batchWriteItem(BatchWriteItemRequest.builder().requestItems(requestItems).build()); // assertNotNull(batchWriteItem.itemCollectionMetrics()); // assertEquals(1, batchWriteItem.itemCollectionMetrics().size()); // assertEquals(tableName, batchWriteItem.itemCollectionMetrics().entrySet().iterator().next().get); // assertNotNull(tableName, batchWriteItem.getResponses().iterator().next().getCapacityUnits()); assertNotNull(batchWriteItem.unprocessedItems()); assertTrue(batchWriteItem.unprocessedItems().isEmpty()); // Delete some data DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder() .tableName(tableName) .key(mapKey(HASH_KEY_NAME, AttributeValue.builder().s("jeep").build())) .returnValues(ReturnValue.ALL_OLD.toString()) .build(); DeleteItemResponse deleteItemResult = dynamo.deleteItem(deleteItemRequest); // Delete our table DeleteTableResponse deleteTable = dynamo.deleteTable(DeleteTableRequest.builder().tableName(tableName).build()); } }
4,747
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/BaseResultIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest; import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class BaseResultIntegrationTest extends AwsIntegrationTestBase { private DynamoDbClient dynamoDB; @Before public void setup() { dynamoDB = DynamoDbClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); } @Test public void responseMetadataInBaseResultIsSameAsMetadataCache() { ListTablesRequest request = ListTablesRequest.builder().build(); ListTablesResponse result = dynamoDB.listTables(request); assertThat(result.sdkHttpResponse().headers()).isNotNull(); } @Test public void httpMetadataInBaseResultIsValid() { ListTablesResponse result = dynamoDB.listTables(ListTablesRequest.builder().build()); assertThat(result.sdkHttpResponse().statusCode()).isEqualTo(200); assertThat(result.sdkHttpResponse().headers()).containsKey("x-amz-crc32"); } }
4,748
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/ProvisionedThroughputThrottlingIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import java.util.Collections; import java.util.Map; import java.util.UUID; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import utils.resources.RequiredResources; import utils.resources.RequiredResources.RequiredResource; import utils.resources.RequiredResources.ResourceCreationPolicy; import utils.resources.RequiredResources.ResourceRetentionPolicy; import utils.resources.ResourceCentricBlockJUnit4ClassRunner; import utils.resources.tables.BasicTempTableWithLowThroughput; import utils.test.util.DynamoDBTestBase; /** * DynamoDB integration tests around ProvisionedThroughput/throttling errors. */ @RunWith(ResourceCentricBlockJUnit4ClassRunner.class) @RequiredResources({ @RequiredResource(resource = BasicTempTableWithLowThroughput.class, creationPolicy = ResourceCreationPolicy.ALWAYS_RECREATE, retentionPolicy = ResourceRetentionPolicy.DESTROY_AFTER_ALL_TESTS) }) public class ProvisionedThroughputThrottlingIntegrationTest extends DynamoDBTestBase { private static final String tableName = BasicTempTableWithLowThroughput.TEMP_TABLE_NAME; private static final String HASH_KEY_NAME = BasicTempTableWithLowThroughput.HASH_KEY_NAME; @BeforeClass public static void setUp() throws Exception { DynamoDBTestBase.setUpTestBase(); } /** * Tests that throttling errors and delayed retries are automatically * handled for users. * * We trigger ProvisionedThroughputExceededExceptions here because of the * low throughput on our test table, but users shouldn't see any problems * because of the backoff and retry strategy. */ @Test public void testProvisionedThroughputExceededRetryHandling() throws Exception { for (int i = 0; i < 20; i++) { Map<String, AttributeValue> item = Collections .singletonMap(HASH_KEY_NAME, AttributeValue.builder().s(UUID.randomUUID().toString()).build()); dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).build()); } } }
4,749
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/PaginatorIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiFunction; import java.util.stream.Stream; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; import software.amazon.awssdk.services.dynamodb.paginators.ScanIterable; import software.amazon.awssdk.services.dynamodb.paginators.ScanPublisher; import utils.resources.tables.BasicTempTable; import utils.test.util.DynamoDBTestBase; import utils.test.util.TableUtils; public class PaginatorIntegrationTest extends DynamoDBTestBase { private static final String TABLE_NAME = "java-sdk-scan-paginator-test" + System.currentTimeMillis(); private static final String HASH_KEY_NAME = BasicTempTable.HASH_KEY_NAME; private static final String ATTRIBUTE_FOO = "attribute_foo"; private static final int ITEM_COUNT = 19; @BeforeClass public static void setUpFixture() throws Exception { DynamoDBTestBase.setUpTestBase(); dynamo.createTable(CreateTableRequest.builder().tableName(TABLE_NAME) .keySchema(KeySchemaElement.builder().keyType(KeyType.HASH) .attributeName(HASH_KEY_NAME) .build()) .attributeDefinitions(AttributeDefinition.builder() .attributeType(ScalarAttributeType.N) .attributeName(HASH_KEY_NAME) .build()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(5L) .writeCapacityUnits(5L) .build()) .build()); TableUtils.waitUntilActive(dynamo, TABLE_NAME); putTestData(); } @AfterClass public static void cleanUpFixture() { dynamo.deleteTable(DeleteTableRequest.builder().tableName(TABLE_NAME).build()); } @Test public void batchGetItem_allProcessed_shouldNotHaveNextPage() { Map<String, KeysAndAttributes> attributes = new HashMap<>(); Map<String, AttributeValue> keys; KeysAndAttributes keysAndAttributes; List<Map<String, AttributeValue>> keysList = new ArrayList<>(); for (int i = 0; i < ITEM_COUNT; i++) { keys = new HashMap<>(); keys.put(HASH_KEY_NAME, AttributeValue.builder().n(String.valueOf(i)).build()); keysList.add(keys); } keysAndAttributes = KeysAndAttributes.builder().keys(keysList).build(); attributes.put(TABLE_NAME, keysAndAttributes); Iterator<BatchGetItemResponse> iterator = dynamo.batchGetItemPaginator(b -> b.requestItems(attributes)).iterator(); assertThat(iterator.next().unprocessedKeys().isEmpty()).isTrue(); assertThat(iterator.hasNext()).isFalse(); } @Test public void test_MultipleIteration_On_Responses_Iterable() { ScanRequest request = scanRequest(2); ScanIterable scanResponses = dynamo.scanPaginator(request); int count = 0; // Iterate once for (ScanResponse response : scanResponses) { count += response.count(); } assertEquals(ITEM_COUNT, count); // Iterate second time count = 0; for (ScanResponse response : scanResponses) { count += response.count(); } assertEquals(ITEM_COUNT, count); } @Test public void test_MultipleIteration_On_PaginatedMember_Iterable() { ScanRequest request = scanRequest(2); SdkIterable<Map<String, AttributeValue>> items = dynamo.scanPaginator(request).items(); int count = 0; // Iterate once for (Map<String, AttributeValue> item : items) { count++; } assertEquals(ITEM_COUNT, count); // Iterate second time count = 0; for (Map<String, AttributeValue> item : items) { count++; } assertEquals(ITEM_COUNT, count); } @Test public void test_MultipleIteration_On_Responses_Stream() { int results_per_page = 2; ScanRequest request = scanRequest(results_per_page); ScanIterable scanResponses = dynamo.scanPaginator(request); // Iterate once assertEquals(ITEM_COUNT, scanResponses.stream() .mapToInt(response -> response.count()) .sum()); // Iterate second time assertEquals(ITEM_COUNT, scanResponses.stream() .mapToInt(response -> response.count()) .sum()); // Number of pages assertEquals(Math.ceil((double) ITEM_COUNT / results_per_page), scanResponses.stream().count(), 0); } @Test public void test_MultipleIteration_On_PaginatedMember_Stream() { ScanRequest request = scanRequest(2); SdkIterable<Map<String, AttributeValue>> items = dynamo.scanPaginator(request).items(); // Iterate once assertEquals(ITEM_COUNT, items.stream().distinct().count()); // Iterate second time assertEquals(ITEM_COUNT, items.stream().distinct().count()); } @Test(expected = IllegalStateException.class) public void iteration_On_SameStream_ThrowsError() { int results_per_page = 2; ScanRequest request = ScanRequest.builder().tableName(TABLE_NAME).limit(results_per_page).build(); Stream<Map<String, AttributeValue>> itemsStream = dynamo.scanPaginator(request).items().stream(); // Iterate once assertEquals(ITEM_COUNT, itemsStream.distinct().count()); // Iterate second time assertEquals(ITEM_COUNT, itemsStream.distinct().count()); } @Test public void mix_Iterator_And_Stream_Calls() { ScanRequest request = scanRequest(2); ScanIterable scanResponses = dynamo.scanPaginator(request); assertEquals(ITEM_COUNT, scanResponses.stream().flatMap(r -> r.items().stream()) .distinct() .count()); assertEquals(ITEM_COUNT, scanResponses.stream().mapToInt(response -> response.count()).sum()); int count = 0; for (ScanResponse response : scanResponses) { count += response.count(); } assertEquals(ITEM_COUNT, count); } @Test public void sdkPublisher_subscribe_handlesExceptions() throws Exception { RuntimeException innerException = new RuntimeException(); ScanRequest request = scanRequest(2); try { dynamoAsync.scanPaginator(request).subscribe(r -> { throw innerException; }).get(5, TimeUnit.SECONDS); } catch (ExecutionException executionException) { assertThat(executionException.getCause()).isSameAs(innerException); } } @Test public void sdkPublisher_filter_handlesExceptions() { sdkPublisherFunctionHandlesException((p, t) -> p.filter(f -> { throw t; })); } @Test public void sdkPublisher_map_handlesExceptions() { sdkPublisherFunctionHandlesException((p, t) -> p.map(f -> { throw t; })); } @Test public void sdkPublisher_flatMapIterable_handlesExceptions() { sdkPublisherFunctionHandlesException((p, t) -> p.flatMapIterable(f -> { throw t; })); } public void sdkPublisherFunctionHandlesException(BiFunction<ScanPublisher, RuntimeException, SdkPublisher<?>> function) { RuntimeException innerException = new RuntimeException(); ScanRequest request = scanRequest(2); try { function.apply(dynamoAsync.scanPaginator(request), innerException).subscribe(r -> {}).get(5, TimeUnit.SECONDS); } catch (ExecutionException executionException) { assertThat(executionException.getCause()).isSameAs(innerException); } catch (InterruptedException | TimeoutException e) { throw new AssertionError("SDK Publisher function did not handle exceptions correctly.", e); } } private static void putTestData() { Map<String, AttributeValue> item = new HashMap(); Random random = new Random(); for (int hashKeyValue = 0; hashKeyValue < ITEM_COUNT; hashKeyValue++) { item.put(HASH_KEY_NAME, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build()); item.put(ATTRIBUTE_FOO, AttributeValue.builder().n(Integer.toString(random.nextInt(ITEM_COUNT))).build()); dynamo.putItem(PutItemRequest.builder().tableName(TABLE_NAME).item(item).build()); item.clear(); } } private ScanRequest scanRequest(int limit) { return ScanRequest.builder().tableName(TABLE_NAME).consistentRead(true).limit(limit).build(); } }
4,750
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/SecondaryIndexesIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; 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.Collections; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.UUID; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.util.SdkAutoConstructList; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ComparisonOperator; import software.amazon.awssdk.services.dynamodb.model.Condition; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import software.amazon.awssdk.services.dynamodb.model.Select; import software.amazon.awssdk.services.dynamodb.model.TableDescription; import utils.resources.RequiredResources; import utils.resources.RequiredResources.RequiredResource; import utils.resources.RequiredResources.ResourceCreationPolicy; import utils.resources.RequiredResources.ResourceRetentionPolicy; import utils.resources.ResourceCentricBlockJUnit4ClassRunner; import utils.resources.tables.TempTableWithSecondaryIndexes; import utils.test.util.DynamoDBTestBase; /** * DynamoDB integration tests for LSI & GSI. */ @RunWith(ResourceCentricBlockJUnit4ClassRunner.class) @RequiredResources({ @RequiredResource(resource = TempTableWithSecondaryIndexes.class, creationPolicy = ResourceCreationPolicy.ALWAYS_RECREATE, retentionPolicy = ResourceRetentionPolicy.DESTROY_AFTER_ALL_TESTS) }) public class SecondaryIndexesIntegrationTest extends DynamoDBTestBase { private static final int MAX_RETRIES = 5; private static final int SLEEP_TIME = 20000; private static final String tableName = TempTableWithSecondaryIndexes.TEMP_TABLE_NAME; private static final String HASH_KEY_NAME = TempTableWithSecondaryIndexes.HASH_KEY_NAME; private static final String RANGE_KEY_NAME = TempTableWithSecondaryIndexes.RANGE_KEY_NAME; private static final String LSI_NAME = TempTableWithSecondaryIndexes.LSI_NAME; private static final String LSI_RANGE_KEY_NAME = TempTableWithSecondaryIndexes.LSI_RANGE_KEY_NAME; private static final String GSI_NAME = TempTableWithSecondaryIndexes.GSI_NAME; private static final String GSI_HASH_KEY_NAME = TempTableWithSecondaryIndexes.GSI_HASH_KEY_NAME; private static final String GSI_RANGE_KEY_NAME = TempTableWithSecondaryIndexes.GSI_RANGE_KEY_NAME; @BeforeClass public static void setUp() throws Exception { DynamoDBTestBase.setUpTestBase(); } /** * Assert the tableDescription is as expected */ @Test public void testDescribeTempTableWithIndexes() { TableDescription tableDescription = dynamo.describeTable(DescribeTableRequest.builder().tableName(tableName).build()).table(); assertEquals(tableName, tableDescription.tableName()); assertNotNull(tableDescription.tableStatus()); assertEquals(2, tableDescription.keySchema().size()); assertEquals(HASH_KEY_NAME, tableDescription.keySchema().get(0) .attributeName()); assertEquals(KeyType.HASH, tableDescription .keySchema().get(0).keyType()); assertEquals(RANGE_KEY_NAME, tableDescription.keySchema() .get(1).attributeName()); assertEquals(KeyType.RANGE, tableDescription .keySchema().get(1).keyType()); assertEquals(1, tableDescription.localSecondaryIndexes().size()); assertEquals(LSI_NAME, tableDescription .localSecondaryIndexes().get(0).indexName()); assertEquals(2, tableDescription .localSecondaryIndexes().get(0).keySchema().size()); assertEquals(HASH_KEY_NAME, tableDescription .localSecondaryIndexes().get(0).keySchema().get(0).attributeName()); assertEquals(KeyType.HASH, tableDescription .localSecondaryIndexes().get(0).keySchema().get(0).keyType()); assertEquals(LSI_RANGE_KEY_NAME, tableDescription .localSecondaryIndexes().get(0).keySchema().get(1).attributeName()); assertEquals(KeyType.RANGE, tableDescription .localSecondaryIndexes().get(0).keySchema().get(1).keyType()); assertEquals(ProjectionType.KEYS_ONLY, tableDescription.localSecondaryIndexes().get(0) .projection().projectionType()); assertTrue(tableDescription.localSecondaryIndexes().get(0) .projection().nonKeyAttributes() instanceof SdkAutoConstructList); assertEquals(1, tableDescription.globalSecondaryIndexes().size()); assertEquals(GSI_NAME, tableDescription .globalSecondaryIndexes().get(0).indexName()); assertEquals(2, tableDescription .globalSecondaryIndexes().get(0).keySchema().size()); assertEquals(GSI_HASH_KEY_NAME, tableDescription .globalSecondaryIndexes().get(0).keySchema().get(0).attributeName()); assertEquals(KeyType.HASH, tableDescription .globalSecondaryIndexes().get(0).keySchema().get(0).keyType()); assertEquals(GSI_RANGE_KEY_NAME, tableDescription .globalSecondaryIndexes().get(0).keySchema().get(1).attributeName()); assertEquals(KeyType.RANGE, tableDescription .globalSecondaryIndexes().get(0).keySchema().get(1).keyType()); assertEquals(ProjectionType.KEYS_ONLY, tableDescription.globalSecondaryIndexes().get(0) .projection().projectionType()); assertTrue(tableDescription.globalSecondaryIndexes().get(0) .projection().nonKeyAttributes() instanceof SdkAutoConstructList); } /** * Tests making queries with global secondary index. */ @Test public void testQueryWithGlobalSecondaryIndex() throws InterruptedException { // GSI attributes don't have to be unique // so items with the same GSI keys but different primary keys // could co-exist in the table. int totalDuplicateGSIKeys = 10; Random random = new Random(); String duplicateGSIHashValue = UUID.randomUUID().toString(); int duplicateGSIRangeValue = random.nextInt(); for (int i = 0; i < totalDuplicateGSIKeys; i++) { Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put(HASH_KEY_NAME, AttributeValue.builder().s(UUID.randomUUID().toString()).build()); item.put(RANGE_KEY_NAME, AttributeValue.builder().n(Integer.toString(i)).build()); item.put(GSI_HASH_KEY_NAME, AttributeValue.builder().s(duplicateGSIHashValue).build()); item.put(GSI_RANGE_KEY_NAME, AttributeValue.builder().n(Integer.toString(duplicateGSIRangeValue)).build()); dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).build()); } // Query the duplicate GSI key values should return all the items Map<String, Condition> keyConditions = new HashMap<String, Condition>(); keyConditions.put( GSI_HASH_KEY_NAME, Condition.builder().attributeValueList( AttributeValue.builder().s((duplicateGSIHashValue)).build()) .comparisonOperator(ComparisonOperator.EQ).build()); keyConditions.put( GSI_RANGE_KEY_NAME, Condition.builder().attributeValueList( AttributeValue.builder().n(Integer .toString(duplicateGSIRangeValue)).build()) .comparisonOperator(ComparisonOperator.EQ).build()); // All the items with the GSI keys should be returned assertQueryResponseCount(totalDuplicateGSIKeys, QueryRequest.builder() .tableName(tableName) .indexName(GSI_NAME) .keyConditions(keyConditions).build()); // Other than this, the behavior of GSI query should be the similar // as LSI query. So following code is similar to that used for // LSI query test. String randomPrimaryHashKeyValue = UUID.randomUUID().toString(); String randomGSIHashKeyValue = UUID.randomUUID().toString(); int totalItemsPerHash = 10; int totalIndexedItemsPerHash = 5; Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put(HASH_KEY_NAME, AttributeValue.builder().s(randomPrimaryHashKeyValue).build()); item.put(GSI_HASH_KEY_NAME, AttributeValue.builder().s(randomGSIHashKeyValue).build()); // Items with GSI keys for (int i = 0; i < totalIndexedItemsPerHash; i++) { item.put(RANGE_KEY_NAME, AttributeValue.builder().n(Integer.toString(i)).build()); item.put(GSI_RANGE_KEY_NAME, AttributeValue.builder().n(Integer.toString(i)).build()); item.put("attribute_" + i, AttributeValue.builder().s(UUID.randomUUID().toString()).build()); dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).build()); item.remove("attribute_" + i); } item.remove(GSI_RANGE_KEY_NAME); // Items with incomplete GSI keys (no GSI range key) for (int i = totalIndexedItemsPerHash; i < totalItemsPerHash; i++) { item.put(RANGE_KEY_NAME, AttributeValue.builder().n(Integer.toString(i)).build()); item.put("attribute_" + i, AttributeValue.builder().s(UUID.randomUUID().toString()).build()); dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).build()); item.remove("attribute_" + i); } /** * 1) Query-with-GSI (only by GSI hash key) */ QueryResponse result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(GSI_NAME) .keyConditions( Collections.singletonMap( GSI_HASH_KEY_NAME, Condition.builder() .attributeValueList(AttributeValue.builder() .s(randomGSIHashKeyValue).build()) .comparisonOperator( ComparisonOperator.EQ).build())).build()); // Only the indexed items should be returned assertEquals((Object) totalIndexedItemsPerHash, (Object) result.count()); // By default, the result includes all the key attributes (2 primary + 2 GSI). assertEquals(4, result.items().get(0).size()); /** * 2) Query-with-GSI (by GSI hash + range) */ int rangeKeyConditionRange = 2; keyConditions = new HashMap<String, Condition>(); keyConditions.put( GSI_HASH_KEY_NAME, Condition.builder() .attributeValueList(AttributeValue.builder() .s(randomGSIHashKeyValue) .build()) .comparisonOperator(ComparisonOperator.EQ) .build()); keyConditions.put( GSI_RANGE_KEY_NAME, Condition.builder() .attributeValueList(AttributeValue.builder() .n(Integer.toString(rangeKeyConditionRange)) .build()) .comparisonOperator(ComparisonOperator.LT) .build()); result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(GSI_NAME) .keyConditions(keyConditions) .build()); assertEquals((Object) rangeKeyConditionRange, (Object) result.count()); /** * 3) Query-with-GSI does not support Select.ALL_ATTRIBUTES if the index * was not created with this projection type. */ try { result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(GSI_NAME) .keyConditions( Collections.singletonMap( GSI_HASH_KEY_NAME, Condition.builder() .attributeValueList(AttributeValue.builder() .s(randomGSIHashKeyValue) .build()) .comparisonOperator(ComparisonOperator.EQ) .build())) .select(Select.ALL_ATTRIBUTES).build()); fail("SdkServiceException is expected"); } catch (SdkServiceException exception) { assertTrue(exception.getMessage().contains("Select type ALL_ATTRIBUTES is not supported for global secondary")); } /** * 4) Query-with-GSI on selected attributes (by AttributesToGet) */ result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(GSI_NAME) .keyConditions( Collections.singletonMap( GSI_HASH_KEY_NAME, Condition.builder() .attributeValueList(AttributeValue.builder() .s(randomGSIHashKeyValue).build()) .comparisonOperator(ComparisonOperator.EQ).build())) .attributesToGet(HASH_KEY_NAME, RANGE_KEY_NAME).build()); // Only the indexed items should be returned assertEquals((Object) totalIndexedItemsPerHash, (Object) result.count()); // Two attributes as specified in AttributesToGet assertEquals(2, result.items().get(0).size()); /** * 5) Exception when using both Selection and AttributeToGet */ try { result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(GSI_NAME) .keyConditions( Collections.singletonMap( GSI_HASH_KEY_NAME, Condition.builder().attributeValueList( AttributeValue.builder() .s(randomGSIHashKeyValue).build()) .comparisonOperator(ComparisonOperator.EQ).build())) .attributesToGet(HASH_KEY_NAME, RANGE_KEY_NAME, LSI_RANGE_KEY_NAME) .select(Select.ALL_PROJECTED_ATTRIBUTES).build()); fail("Should trigger exception when using both Select and AttributeToGet."); } catch (SdkServiceException exception) { // Ignored or expected. } /** * 6) Query-with-GSI on selected attributes (by Select.SPECIFIC_ATTRIBUTES) */ result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(GSI_NAME) .keyConditions( Collections.singletonMap( GSI_HASH_KEY_NAME, Condition.builder().attributeValueList( AttributeValue.builder() .s(randomGSIHashKeyValue).build()) .comparisonOperator( ComparisonOperator.EQ).build())) .attributesToGet(HASH_KEY_NAME) .select(Select.SPECIFIC_ATTRIBUTES).build()); // Only the indexed items should be returned assertEquals((Object) totalIndexedItemsPerHash, (Object) result.count()); // Only one attribute as specified in AttributesToGet assertEquals(1, result.items().get(0).size()); } /** * Tests making queries with local secondary index. */ @Test public void testQueryWithLocalSecondaryIndex() throws Exception { String randomHashKeyValue = UUID.randomUUID().toString(); int totalItemsPerHash = 10; int totalIndexedItemsPerHash = 5; Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put(HASH_KEY_NAME, AttributeValue.builder().s(randomHashKeyValue).build()); // Items with LSI range key for (int i = 0; i < totalIndexedItemsPerHash; i++) { item.put(RANGE_KEY_NAME, AttributeValue.builder().n(Integer.toString(i)).build()); item.put(LSI_RANGE_KEY_NAME, AttributeValue.builder().n(Integer.toString(i)).build()); item.put("attribute_" + i, AttributeValue.builder().s(UUID.randomUUID().toString()).build()); dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).build()); item.remove("attribute_" + i); } item.remove(LSI_RANGE_KEY_NAME); // Items without LSI range key for (int i = totalIndexedItemsPerHash; i < totalItemsPerHash; i++) { item.put(RANGE_KEY_NAME, AttributeValue.builder().n(Integer.toString(i)).build()); item.put("attribute_" + i, AttributeValue.builder().s(UUID.randomUUID().toString()).build()); dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).build()); item.remove("attribute_" + i); } /** * 1) Query-with-LSI (only by hash key) */ QueryResponse result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(LSI_NAME) .keyConditions( Collections.singletonMap( HASH_KEY_NAME, Condition.builder().attributeValueList( AttributeValue.builder() .s(randomHashKeyValue).build()) .comparisonOperator( ComparisonOperator.EQ).build())).build()); // Only the indexed items should be returned assertEquals((Object) totalIndexedItemsPerHash, (Object) result.count()); // By default, the result includes all the projected attributes. assertEquals(3, result.items().get(0).size()); /** * 2) Query-with-LSI (by hash + LSI range) */ int rangeKeyConditionRange = 2; Map<String, Condition> keyConditions = new HashMap<String, Condition>(); keyConditions.put( HASH_KEY_NAME, Condition.builder().attributeValueList( AttributeValue.builder().s(randomHashKeyValue).build()) .comparisonOperator(ComparisonOperator.EQ).build()); keyConditions.put( LSI_RANGE_KEY_NAME, Condition.builder().attributeValueList(AttributeValue.builder() .n(Integer.toString(rangeKeyConditionRange)).build()) .comparisonOperator(ComparisonOperator.LT).build()); result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(LSI_NAME) .keyConditions(keyConditions).build()); assertEquals((Object) rangeKeyConditionRange, (Object) result.count()); /** * 3) Query-with-LSI on selected attributes (by Select) */ result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(LSI_NAME) .keyConditions( Collections.singletonMap( HASH_KEY_NAME, Condition.builder().attributeValueList( AttributeValue.builder() .s(randomHashKeyValue).build()) .comparisonOperator(ComparisonOperator.EQ).build())) .select(Select.ALL_ATTRIBUTES).build()); // Only the indexed items should be returned assertEquals((Object) totalIndexedItemsPerHash, (Object) result.count()); // By setting Select.ALL_ATTRIBUTES, all attributes in the item will be returned assertEquals(4, result.items().get(0).size()); /** * 4) Query-with-LSI on selected attributes (by AttributesToGet) */ result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(LSI_NAME) .keyConditions( Collections.singletonMap( HASH_KEY_NAME, Condition.builder().attributeValueList( AttributeValue.builder() .s(randomHashKeyValue).build()) .comparisonOperator(ComparisonOperator.EQ).build())) .attributesToGet(HASH_KEY_NAME, RANGE_KEY_NAME).build()); // Only the indexed items should be returned assertEquals((Object) totalIndexedItemsPerHash, (Object) result.count()); // Two attributes as specified in AttributesToGet assertEquals(2, result.items().get(0).size()); /** * 5) Exception when using both Selection and AttributeToGet */ try { result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(LSI_NAME) .keyConditions( Collections.singletonMap( HASH_KEY_NAME, Condition.builder().attributeValueList( AttributeValue.builder() .s(randomHashKeyValue).build()) .comparisonOperator(ComparisonOperator.EQ).build())) .attributesToGet(HASH_KEY_NAME, RANGE_KEY_NAME, LSI_RANGE_KEY_NAME) .select(Select.ALL_PROJECTED_ATTRIBUTES).build()); fail("Should trigger exception when using both Select and AttributeToGet."); } catch (SdkServiceException exception) { // Ignored or expected. } /** * 6) Query-with-LSI on selected attributes (by Select.SPECIFIC_ATTRIBUTES) */ result = dynamo.query(QueryRequest.builder() .tableName(tableName) .indexName(LSI_NAME) .keyConditions( Collections.singletonMap( HASH_KEY_NAME, Condition.builder().attributeValueList( AttributeValue.builder() .s(randomHashKeyValue).build()) .comparisonOperator( ComparisonOperator.EQ).build())) .attributesToGet(HASH_KEY_NAME) .select(Select.SPECIFIC_ATTRIBUTES).build()); // Only the indexed items should be returned assertEquals((Object) totalIndexedItemsPerHash, (Object) result.count()); // Only one attribute as specified in AttributesToGet assertEquals(1, result.items().get(0).size()); } private void assertQueryResponseCount(Integer expected, QueryRequest request) throws InterruptedException { int retries = 0; QueryResponse result = null; do { result = dynamo.query(request); if (expected == result.count()) { return; } // Handling eventual consistency. Thread.sleep(SLEEP_TIME); retries++; } while (retries <= MAX_RETRIES); Assert.fail("Failed to assert query count. Expected : " + expected + " actual : " + result.count()); } }
4,751
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/SecurityManagerIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import static org.junit.Assert.assertNotNull; import org.junit.AfterClass; import org.junit.Test; import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class SecurityManagerIntegrationTest extends AwsIntegrationTestBase { private static final String JAVA_SECURITY_POLICY_PROPERTY = "java.security.policy"; @AfterClass public static void tearDownFixture() { System.setSecurityManager(null); System.clearProperty(JAVA_SECURITY_POLICY_PROPERTY); } /** * Basic smoke test that the SDK works with a security manager when given appropriate * permissions */ @Test public void securityManagerEnabled() { System.setProperty(JAVA_SECURITY_POLICY_PROPERTY, getPolicyUrl()); SecurityManager securityManager = new SecurityManager(); System.setSecurityManager(securityManager); DynamoDbClient ddb = DynamoDbClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); assertNotNull(ddb.listTables(ListTablesRequest.builder().build())); } private String getPolicyUrl() { return getClass().getResource("security-manager-integ-test.policy").toExternalForm(); } }
4,752
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb
Create_ds/aws-sdk-java-v2/services/dynamodb/src/it/java/software/amazon/awssdk/services/dynamodb/streams/StreamsIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb.streams; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.services.dynamodb.model.ListStreamsRequest; import software.amazon.awssdk.testutils.service.AwsTestBase; public class StreamsIntegrationTest extends AwsTestBase { private DynamoDbStreamsClient streams; @Before public void setup() throws Exception { setUpCredentials(); streams = DynamoDbStreamsClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } @Test public void testDefaultEndpoint() { streams.listStreams(ListStreamsRequest.builder().tableName("foo").build()); } }
4,753
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/dynamodb/src/main/java/software/amazon/awssdk/services/dynamodb/DynamoDbRetryPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.dynamodb; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.retry.AwsRetryPolicy; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FullJitterBackoffStrategy; /** * Default retry policy for DynamoDB Client. */ @SdkInternalApi final class DynamoDbRetryPolicy { /** * Default max retry count for DynamoDB client, regardless of retry mode. **/ private static final int MAX_ERROR_RETRY = 8; /** * Default base sleep time for DynamoDB, regardless of retry mode. **/ private static final Duration BASE_DELAY = Duration.ofMillis(25); /** * The default back-off strategy for DynamoDB client, which increases * exponentially up to a max amount of delay. Compared to the SDK default * back-off strategy, it applies a smaller scale factor. */ private static final BackoffStrategy BACKOFF_STRATEGY = FullJitterBackoffStrategy.builder() .baseDelay(BASE_DELAY) .maxBackoffTime(SdkDefaultRetrySetting.MAX_BACKOFF) .build(); private DynamoDbRetryPolicy() { } public static RetryPolicy resolveRetryPolicy(SdkClientConfiguration config) { RetryPolicy configuredRetryPolicy = config.option(SdkClientOption.RETRY_POLICY); if (configuredRetryPolicy != null) { return configuredRetryPolicy; } RetryMode retryMode = RetryMode.resolver() .profileFile(config.option(SdkClientOption.PROFILE_FILE_SUPPLIER)) .profileName(config.option(SdkClientOption.PROFILE_NAME)) .defaultRetryMode(config.option(SdkClientOption.DEFAULT_RETRY_MODE)) .resolve(); return AwsRetryPolicy.forRetryMode(retryMode) .toBuilder() .additionalRetryConditionsAllowed(false) .numRetries(MAX_ERROR_RETRY) .backoffStrategy(BACKOFF_STRATEGY) .build(); } }
4,754
0
Create_ds/aws-sdk-java-v2/services/applicationautoscaling/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/applicationautoscaling/src/it/java/software/amazon/awssdk/services/applicationautoscaling/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.applicationautoscaling; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesRequest; import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesResponse; import software.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class ServiceIntegrationTest extends AwsIntegrationTestBase { private static ApplicationAutoScalingClient autoscaling; @BeforeClass public static void setUp() { autoscaling = ApplicationAutoScalingClient.builder() .credentialsProvider(StaticCredentialsProvider.create(getCredentials())) .build(); } @Test public void testScalingPolicy() { DescribeScalingPoliciesResponse res = autoscaling.describeScalingPolicies(DescribeScalingPoliciesRequest.builder() .serviceNamespace(ServiceNamespace.ECS).build()); Assert.assertNotNull(res); Assert.assertNotNull(res.scalingPolicies()); } }
4,755
0
Create_ds/aws-sdk-java-v2/services/storagegateway/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/storagegateway/src/it/java/software/amazon/awssdk/services/storagegateway/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.storagegateway; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; 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.storagegateway.model.DeleteGatewayRequest; import software.amazon.awssdk.services.storagegateway.model.InvalidGatewayRequestException; import software.amazon.awssdk.services.storagegateway.model.ListGatewaysRequest; import software.amazon.awssdk.services.storagegateway.model.ListGatewaysResponse; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Tests service methods in storage gateway. Because of the non-trivial amount of set-up required, * this is more of a spot check than an exhaustive test. */ public class ServiceIntegrationTest extends AwsTestBase { private static StorageGatewayClient sg; @BeforeClass public static void setUp() throws Exception { setUpCredentials(); sg = StorageGatewayClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).region(Region.US_EAST_1).build(); } @Test public void testListGateways() { ListGatewaysResponse listGateways = sg.listGateways(ListGatewaysRequest.builder().build()); assertNotNull(listGateways); assertThat(listGateways.gateways().size(), greaterThanOrEqualTo(0)); } @Test(expected = InvalidGatewayRequestException.class) public void deleteGateway_InvalidArn_ThrowsException() { sg.deleteGateway(DeleteGatewayRequest.builder().gatewayARN("arn:aws:storagegateway:us-west-2:111122223333:gateway/sgw-12A3456B/volume/vol-1122AABBCCDDEEFFG").build()); } @Test(expected = SdkServiceException.class) public void deleteGateway_NullArn_ThrowsSdkServiceException() { sg.deleteGateway(DeleteGatewayRequest.builder().build()); } }
4,756
0
Create_ds/aws-sdk-java-v2/services/ecs/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ecs/src/it/java/software/amazon/awssdk/services/ecs/EC2ContainerServiceIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ecs; import java.util.Arrays; import java.util.List; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.ecs.model.ContainerDefinition; import software.amazon.awssdk.services.ecs.model.CreateClusterRequest; import software.amazon.awssdk.services.ecs.model.CreateClusterResponse; import software.amazon.awssdk.services.ecs.model.DeleteClusterRequest; import software.amazon.awssdk.services.ecs.model.ListClustersRequest; import software.amazon.awssdk.services.ecs.model.ListTaskDefinitionsRequest; import software.amazon.awssdk.services.ecs.model.PortMapping; import software.amazon.awssdk.services.ecs.model.RegisterTaskDefinitionRequest; import software.amazon.awssdk.services.ecs.model.RegisterTaskDefinitionResponse; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.testutils.service.AwsTestBase; public class EC2ContainerServiceIntegrationTest extends AwsTestBase { private static final String CLUSTER_NAME = "java-sdk-test-cluster-" + System.currentTimeMillis(); private static EcsClient client; private static String clusterArn; @BeforeClass public static void setup() throws Exception { setUpCredentials(); client = EcsClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); CreateClusterResponse result = client.createCluster(CreateClusterRequest.builder() .clusterName(CLUSTER_NAME) .build()); Assert.assertEquals(CLUSTER_NAME, result.cluster().clusterName()); Assert.assertNotNull(result.cluster().clusterArn()); Assert.assertNotNull(result.cluster().status()); clusterArn = result.cluster().clusterArn(); Waiter.run(() -> client.describeClusters(r -> r.clusters(CLUSTER_NAME))) .until(resp -> resp.clusters().stream().findFirst().filter(c -> c.status().equals("ACTIVE")).isPresent()) .orFail(); } @AfterClass public static void cleanup() { if (client != null) { client.deleteCluster(DeleteClusterRequest.builder().cluster(CLUSTER_NAME).build()); } } @Test public void basicTest() { List<String> arns = client.listClusters(ListClustersRequest.builder().build()).clusterArns(); Assert.assertNotNull(arns); Assert.assertTrue(arns.contains(clusterArn)); RegisterTaskDefinitionResponse result = client.registerTaskDefinition(RegisterTaskDefinitionRequest.builder() .family("test") .containerDefinitions(ContainerDefinition.builder() .command("command", "command", "command") .cpu(1) .entryPoint("entryPoint", "entryPoint") .image("image") .memory(1) .name("test") .portMappings(PortMapping.builder() .hostPort(12345) .containerPort(6789).build() ).build() ).build() ); Assert.assertEquals("test", result.taskDefinition().family()); Assert.assertNotNull(result.taskDefinition().revision()); Assert.assertNotNull(result.taskDefinition().taskDefinitionArn()); ContainerDefinition def = result.taskDefinition() .containerDefinitions() .get(0); Assert.assertEquals("image", def.image()); Assert.assertEquals( Arrays.asList("entryPoint", "entryPoint"), def.entryPoint()); Assert.assertEquals( Arrays.asList("command", "command", "command"), def.command()); // Can't deregister task definitions yet... :( List<String> taskArns = client.listTaskDefinitions(ListTaskDefinitionsRequest.builder().build()) .taskDefinitionArns(); Assert.assertNotNull(taskArns); Assert.assertFalse(taskArns.isEmpty()); } }
4,757
0
Create_ds/aws-sdk-java-v2/services/ecs/src/it/java/software/amazon/awssdk/services/ecs
Create_ds/aws-sdk-java-v2/services/ecs/src/it/java/software/amazon/awssdk/services/ecs/waiters/EcsWaiterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ecs.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.Deployment; import software.amazon.awssdk.services.ecs.model.DescribeServicesRequest; import software.amazon.awssdk.services.ecs.model.DescribeServicesResponse; public class EcsWaiterTest { private EcsClient client; @Before public void setup() { client = mock(EcsClient.class); } @Test(timeout = 30_000) @SuppressWarnings("unchecked") public void waitUntilServicesStableWorks() { DescribeServicesRequest request = DescribeServicesRequest.builder().build(); DescribeServicesResponse response1 = DescribeServicesResponse.builder() .services(s -> s.deployments(Deployment.builder().build()) .desiredCount(2) .runningCount(1)) .build(); DescribeServicesResponse response2 = DescribeServicesResponse.builder() .services(s -> s.deployments(Deployment.builder().build()) .desiredCount(2) .runningCount(2)) .build(); when(client.describeServices(any(DescribeServicesRequest.class))).thenReturn(response1, response2); EcsWaiter waiter = EcsWaiter.builder() .overrideConfiguration(WaiterOverrideConfiguration.builder() .maxAttempts(3) .backoffStrategy(BackoffStrategy.none()) .build()) .client(client) .build(); WaiterResponse<DescribeServicesResponse> response = waiter.waitUntilServicesStable(request); assertThat(response.attemptsExecuted()).isEqualTo(2); assertThat(response.matched().response()).hasValueSatisfying(r -> assertThat(r).isEqualTo(response2)); } }
4,758
0
Create_ds/aws-sdk-java-v2/services/cloudsearch/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudsearch/src/it/java/software/amazon/awssdk/services/cloudsearch/CloudSearchv2IntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudsearch; 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 java.time.Duration; import java.time.Instant; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.services.cloudsearch.model.AccessPoliciesStatus; import software.amazon.awssdk.services.cloudsearch.model.AnalysisScheme; import software.amazon.awssdk.services.cloudsearch.model.AnalysisSchemeLanguage; import software.amazon.awssdk.services.cloudsearch.model.AnalysisSchemeStatus; import software.amazon.awssdk.services.cloudsearch.model.BuildSuggestersRequest; import software.amazon.awssdk.services.cloudsearch.model.CreateDomainRequest; import software.amazon.awssdk.services.cloudsearch.model.CreateDomainResponse; import software.amazon.awssdk.services.cloudsearch.model.DefineAnalysisSchemeRequest; import software.amazon.awssdk.services.cloudsearch.model.DefineExpressionRequest; import software.amazon.awssdk.services.cloudsearch.model.DefineIndexFieldRequest; import software.amazon.awssdk.services.cloudsearch.model.DefineSuggesterRequest; import software.amazon.awssdk.services.cloudsearch.model.DefineSuggesterResponse; import software.amazon.awssdk.services.cloudsearch.model.DeleteDomainRequest; import software.amazon.awssdk.services.cloudsearch.model.DescribeAnalysisSchemesRequest; import software.amazon.awssdk.services.cloudsearch.model.DescribeAnalysisSchemesResponse; import software.amazon.awssdk.services.cloudsearch.model.DescribeDomainsRequest; import software.amazon.awssdk.services.cloudsearch.model.DescribeDomainsResponse; import software.amazon.awssdk.services.cloudsearch.model.DescribeExpressionsRequest; import software.amazon.awssdk.services.cloudsearch.model.DescribeExpressionsResponse; import software.amazon.awssdk.services.cloudsearch.model.DescribeIndexFieldsRequest; import software.amazon.awssdk.services.cloudsearch.model.DescribeIndexFieldsResponse; import software.amazon.awssdk.services.cloudsearch.model.DescribeScalingParametersRequest; import software.amazon.awssdk.services.cloudsearch.model.DescribeScalingParametersResponse; import software.amazon.awssdk.services.cloudsearch.model.DescribeServiceAccessPoliciesRequest; import software.amazon.awssdk.services.cloudsearch.model.DescribeServiceAccessPoliciesResponse; import software.amazon.awssdk.services.cloudsearch.model.DescribeSuggestersRequest; import software.amazon.awssdk.services.cloudsearch.model.DescribeSuggestersResponse; import software.amazon.awssdk.services.cloudsearch.model.DocumentSuggesterOptions; import software.amazon.awssdk.services.cloudsearch.model.DomainStatus; import software.amazon.awssdk.services.cloudsearch.model.Expression; import software.amazon.awssdk.services.cloudsearch.model.ExpressionStatus; import software.amazon.awssdk.services.cloudsearch.model.IndexDocumentsRequest; import software.amazon.awssdk.services.cloudsearch.model.IndexField; import software.amazon.awssdk.services.cloudsearch.model.IndexFieldStatus; import software.amazon.awssdk.services.cloudsearch.model.IndexFieldType; import software.amazon.awssdk.services.cloudsearch.model.ListDomainNamesRequest; import software.amazon.awssdk.services.cloudsearch.model.ListDomainNamesResponse; import software.amazon.awssdk.services.cloudsearch.model.PartitionInstanceType; import software.amazon.awssdk.services.cloudsearch.model.ScalingParameters; import software.amazon.awssdk.services.cloudsearch.model.Suggester; import software.amazon.awssdk.services.cloudsearch.model.SuggesterStatus; import software.amazon.awssdk.services.cloudsearch.model.TextOptions; import software.amazon.awssdk.services.cloudsearch.model.UpdateScalingParametersRequest; import software.amazon.awssdk.services.cloudsearch.model.UpdateServiceAccessPoliciesRequest; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class CloudSearchv2IntegrationTest extends AwsIntegrationTestBase { /** Name Prefix of the domains being created for test cases. */ private static final String testDomainNamePrefix = "sdk-domain-"; /** Name of the expression being created in the domain. */ private static final String testExpressionName = "sdkexp" + System.currentTimeMillis(); /** Name of the test index being created in the domain. */ private static final String testIndexName = "sdkindex" + System.currentTimeMillis(); /** Name of the test suggester being created in the domain. */ private static final String testSuggesterName = "sdksug" + System.currentTimeMillis(); /** Name of the test analysis scheme being created in the domain. */ private static final String testAnalysisSchemeName = "analysis" + System.currentTimeMillis(); public static String POLICY = "{\n" + " \"Statement\":[\n" + " {\n" + " \"Effect\":\"Allow\",\n" + " \"Principal\":\"*\",\n" + " \"Action\":[\"cloudsearch:search\"],\n" + " \"Condition\":{\"IpAddress\":{\"aws:SourceIp\":\"203.0.113.1/32\"}}\n" + " }\n" + " ]\n" + "}"; /** Reference to the cloud search client during the testing process. */ private static CloudSearchClient cloudSearch = null; /** * Holds the name of the domain name at any point of time during test case * execution. */ private static String testDomainName = null; /** * Sets up the credenitals and creates an instance of the Amazon Cloud * Search client used for different test case executions. */ @BeforeClass public static void setUp() throws Exception { cloudSearch = CloudSearchClient.builder().credentialsProvider(StaticCredentialsProvider.create(getCredentials())).build(); } /** * Creates a new Amazon Cloud Search domain before every test case * execution. This is done to ensure that the state of domain is in * consistent state before and after the test case execution. */ @Before public void createDomain() { testDomainName = testDomainNamePrefix + System.currentTimeMillis(); cloudSearch.createDomain(CreateDomainRequest.builder() .domainName(testDomainName).build()); } /** * Deletes the Amazon Cloud Search domain after every test case execution. */ @After public void deleteDomain() { cloudSearch.deleteDomain(DeleteDomainRequest.builder() .domainName(testDomainName).build()); } /** * Tests the create domain functionality. Checks if there are any existing * domains by querying using describe domains or list domain names API. * Creates a new domain using create domain API. Checks if the domain id, * name is set in the result and the domain name matches the name used * during creation. Also checks if the state of the domain in Created State. * Since this domain is created locally for this test case, it is deleted in * the finally block. */ @Test public void testCreateDomains() { CreateDomainResponse createDomainResult = null; String domainName = "test-" + System.currentTimeMillis(); try { DescribeDomainsResponse describeDomainResult = cloudSearch .describeDomains(DescribeDomainsRequest.builder().build()); ListDomainNamesResponse listDomainNamesResult = cloudSearch .listDomainNames(ListDomainNamesRequest.builder().build()); assertTrue(describeDomainResult.domainStatusList().size() >= 0); assertTrue(listDomainNamesResult.domainNames().size() >= 0); createDomainResult = cloudSearch .createDomain(CreateDomainRequest.builder() .domainName(domainName).build()); describeDomainResult = cloudSearch .describeDomains(DescribeDomainsRequest.builder() .domainNames(domainName).build()); DomainStatus domainStatus = describeDomainResult .domainStatusList().get(0); assertTrue(domainStatus.created()); assertFalse(domainStatus.deleted()); assertNotNull(domainStatus.arn()); assertEquals(domainStatus.domainName(), domainName); assertNotNull(domainStatus.domainId()); assertTrue(domainStatus.processing()); } finally { if (createDomainResult != null) { cloudSearch.deleteDomain(DeleteDomainRequest.builder() .domainName(domainName).build()); } } } /** * Tests the Index Documents API. Asserts that the status of the domain is * initially in the "RequiresIndexDocuments" state. After an index document * request is initiated, the status must be updated to "Processing" state. * Status is retrieved using the Describe Domains API */ @Test public void testIndexDocuments() { IndexField indexField = IndexField.builder().indexFieldName( testIndexName).indexFieldType(IndexFieldType.LITERAL).build(); cloudSearch.defineIndexField(DefineIndexFieldRequest.builder() .domainName(testDomainName).indexField(indexField).build()); DescribeDomainsResponse describeDomainResult = cloudSearch .describeDomains(DescribeDomainsRequest.builder() .domainNames(testDomainName).build()); DomainStatus status = describeDomainResult.domainStatusList().get(0); assertTrue(status.requiresIndexDocuments()); cloudSearch.indexDocuments(IndexDocumentsRequest.builder() .domainName(testDomainName).build()); status = describeDomainResult.domainStatusList().get(0); assertTrue(status.processing()); } /** * Tests the Access Policies API. Updates an Access Policy for the domain. * Retrieves the access policy and checks if the access policy retrieved is * same as the one updated. */ @Test public void testAccessPolicies() { AccessPoliciesStatus accessPoliciesStatus = null; Instant yesterday = Instant.now().minus(Duration.ofDays(1)); DescribeDomainsResponse describeDomainResult = cloudSearch .describeDomains(DescribeDomainsRequest.builder() .domainNames(testDomainName).build()); POLICY = POLICY.replaceAll("ARN", describeDomainResult .domainStatusList().get(0).arn()); cloudSearch .updateServiceAccessPolicies(UpdateServiceAccessPoliciesRequest.builder() .domainName(testDomainName).accessPolicies( POLICY).build()); DescribeServiceAccessPoliciesResponse accessPolicyResult = cloudSearch .describeServiceAccessPolicies(DescribeServiceAccessPoliciesRequest.builder() .domainName(testDomainName).build()); accessPoliciesStatus = accessPolicyResult.accessPolicies(); assertNotNull(accessPoliciesStatus); assertTrue(yesterday.isBefore( accessPoliciesStatus.status().creationDate())); assertTrue(yesterday.isBefore( accessPoliciesStatus.status().updateDate())); assertTrue(accessPoliciesStatus.options().length() > 0); assertNotNull(accessPoliciesStatus.status().state()); } /** * Test the Define Index Fields API. Asserts that the list of index fields * initially in the domain is ZERO. Creates a new index field for every * index field type mentioned in the enum * <code>com.amazonaws.services.cloudsearch.model.IndexFieldType<code>. * * Asserts that the number of index fields created is same as the number of the enum type mentioned. */ @Test public void testIndexFields() { String indexFieldName = null; DescribeIndexFieldsRequest describeIndexFieldRequest = DescribeIndexFieldsRequest.builder() .domainName(testDomainName).build(); DescribeIndexFieldsResponse result = cloudSearch.describeIndexFields(describeIndexFieldRequest); assertTrue(result.indexFields().size() == 0); IndexField field = null; DefineIndexFieldRequest.Builder defineIndexFieldRequest = DefineIndexFieldRequest.builder() .domainName(testDomainName); for (IndexFieldType type : IndexFieldType.knownValues()) { indexFieldName = type.toString(); indexFieldName = indexFieldName.replaceAll("-", ""); field = IndexField.builder().indexFieldType(type) .indexFieldName(indexFieldName + "indexfield").build(); defineIndexFieldRequest.indexField(field); cloudSearch.defineIndexField(defineIndexFieldRequest.build()); } result = cloudSearch.describeIndexFields(describeIndexFieldRequest.toBuilder().deployed(false).build()); List<IndexFieldStatus> indexFieldStatusList = result.indexFields(); assertTrue(indexFieldStatusList.size() == IndexFieldType.knownValues().size()); } /** * Tests the Define Expressions API. Asserts that the list of expressions in * the domain is ZERO. Creates a new Expression. Asserts that the Describe * Expression API returns the Expression created. */ @Test public void testExpressions() { DescribeExpressionsRequest describeExpressionRequest = DescribeExpressionsRequest.builder() .domainName(testDomainName).build(); DescribeExpressionsResponse describeExpressionResult = cloudSearch .describeExpressions(describeExpressionRequest); assertTrue(describeExpressionResult.expressions().size() == 0); Expression expression = Expression.builder().expressionName( testExpressionName).expressionValue("1").build(); cloudSearch.defineExpression(DefineExpressionRequest.builder() .domainName(testDomainName).expression(expression).build()); describeExpressionResult = cloudSearch .describeExpressions(describeExpressionRequest); List<ExpressionStatus> expressionStatus = describeExpressionResult .expressions(); assertTrue(expressionStatus.size() == 1); Expression expressionRetrieved = expressionStatus.get(0).options(); assertEquals(expression.expressionName(), expressionRetrieved.expressionName()); assertEquals(expression.expressionValue(), expressionRetrieved.expressionValue()); } /** * Tests the Define Suggesters API. Asserts that the number of suggesters is * ZERO initially in the domain. Creates a suggester for an text field and * asserts if the number of suggesters is 1 after creation. Builds the * suggesters into the domain and asserts that the domain status is in * "Processing" state. */ @Test public void testSuggestors() { DescribeSuggestersRequest describeSuggesterRequest = DescribeSuggestersRequest.builder() .domainName(testDomainName).build(); DescribeSuggestersResponse describeSuggesterResult = cloudSearch .describeSuggesters(describeSuggesterRequest); assertTrue(describeSuggesterResult.suggesters().size() == 0); DefineIndexFieldRequest defineIndexFieldRequest = DefineIndexFieldRequest.builder() .domainName(testDomainName) .indexField( IndexField.builder() .indexFieldName(testIndexName) .indexFieldType( IndexFieldType.TEXT) .textOptions( TextOptions.builder() .analysisScheme( "_en_default_") .build()) .build()).build(); cloudSearch.defineIndexField(defineIndexFieldRequest); DocumentSuggesterOptions suggesterOptions = DocumentSuggesterOptions.builder() .sourceField(testIndexName).sortExpression("1") .build(); Suggester suggester = Suggester.builder().suggesterName( testSuggesterName).documentSuggesterOptions( suggesterOptions).build(); DefineSuggesterRequest defineSuggesterRequest = DefineSuggesterRequest.builder() .domainName(testDomainName).suggester(suggester) .build(); DefineSuggesterResponse defineSuggesterResult = cloudSearch .defineSuggester(defineSuggesterRequest); SuggesterStatus status = defineSuggesterResult.suggester(); assertNotNull(status); assertNotNull(status.options()); assertEquals(status.options().suggesterName(), testSuggesterName); describeSuggesterResult = cloudSearch .describeSuggesters(describeSuggesterRequest); assertTrue(describeSuggesterResult.suggesters().size() == 1); cloudSearch.buildSuggesters(BuildSuggestersRequest.builder() .domainName(testDomainName).build()); DescribeDomainsResponse describeDomainsResult = cloudSearch .describeDomains(DescribeDomainsRequest.builder() .domainNames(testDomainName).build()); DomainStatus domainStatus = describeDomainsResult.domainStatusList() .get(0); assertTrue(domainStatus.processing()); } /** * Tests the Define Analysis Scheme API. Asserts that the number of analysis * scheme in a newly created domain is ZERO. Creates an new analysis scheme * for the domain. Creates a new index field and associates the analysis * scheme with the field. Asserts that the number of analysis scheme is ONE * and the matches the analysis scheme retrieved with the one created. Also * asserts if the describe index field API returns the index field that has * the analysis scheme linked. */ @Test public void testAnalysisSchemes() { DescribeAnalysisSchemesRequest describeAnalysisSchemesRequest = DescribeAnalysisSchemesRequest.builder() .domainName(testDomainName) .build(); DescribeAnalysisSchemesResponse describeAnalysisSchemesResult = cloudSearch .describeAnalysisSchemes(describeAnalysisSchemesRequest); assertTrue(describeAnalysisSchemesResult.analysisSchemes().size() == 0); AnalysisScheme analysisScheme = AnalysisScheme.builder() .analysisSchemeName(testAnalysisSchemeName) .analysisSchemeLanguage(AnalysisSchemeLanguage.AR).build(); cloudSearch.defineAnalysisScheme(DefineAnalysisSchemeRequest.builder() .domainName(testDomainName).analysisScheme( analysisScheme).build()); ; DefineIndexFieldRequest defineIndexFieldRequest = DefineIndexFieldRequest.builder() .domainName(testDomainName) .indexField(IndexField.builder() .indexFieldName(testIndexName) .indexFieldType(IndexFieldType.TEXT) .textOptions(TextOptions.builder() .analysisScheme(testAnalysisSchemeName) .build()).build()).build(); cloudSearch.defineIndexField(defineIndexFieldRequest); describeAnalysisSchemesResult = cloudSearch.describeAnalysisSchemes(describeAnalysisSchemesRequest); assertTrue(describeAnalysisSchemesResult.analysisSchemes().size() == 1); AnalysisSchemeStatus schemeStatus = describeAnalysisSchemesResult .analysisSchemes().get(0); assertEquals(schemeStatus.options().analysisSchemeName(), testAnalysisSchemeName); assertEquals(schemeStatus.options().analysisSchemeLanguage(), AnalysisSchemeLanguage.AR); DescribeIndexFieldsResponse describeIndexFieldsResult = cloudSearch .describeIndexFields(DescribeIndexFieldsRequest.builder() .domainName(testDomainName).fieldNames( testIndexName).build()); IndexFieldStatus status = describeIndexFieldsResult.indexFields() .get(0); TextOptions textOptions = status.options().textOptions(); assertEquals(textOptions.analysisScheme(), testAnalysisSchemeName); } }
4,759
0
Create_ds/aws-sdk-java-v2/services/cloudwatchlogs/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudwatchlogs/src/it/java/software/amazon/awssdk/services/cloudwatchlogs/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.cloudwatchlogs; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogGroupsRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogGroupsResponse; import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse; import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeMetricFiltersRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeMetricFiltersResponse; import software.amazon.awssdk.services.cloudwatchlogs.model.LogGroup; import software.amazon.awssdk.services.cloudwatchlogs.model.LogStream; import software.amazon.awssdk.services.cloudwatchlogs.model.MetricFilter; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; /** * Base class for CloudWatch Logs integration tests. */ public abstract class IntegrationTestBase extends AwsIntegrationTestBase { /** Shared CloudWatch Logs client for all tests to use. */ protected static CloudWatchLogsClient awsLogs; /** * Loads the AWS account info for the integration tests and creates an CloudWatch Logs client * for tests to use. */ @BeforeClass public static void setupFixture() throws FileNotFoundException, IOException { awsLogs = CloudWatchLogsClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } /* * Test helper functions */ /** * @return The LogGroup object included in the DescribeLogGroups response, or null if such group * is not found. */ protected static LogGroup findLogGroupByName(final CloudWatchLogsClient awsLogs, final String groupName) { String nextToken = null; do { DescribeLogGroupsResponse result = awsLogs .describeLogGroups(DescribeLogGroupsRequest.builder().nextToken(nextToken).build()); for (LogGroup group : result.logGroups()) { if (group.logGroupName().equals(groupName)) { return group; } } nextToken = result.nextToken(); } while (nextToken != null); return null; } /** * @return The LogStream object included in the DescribeLogStreams response, or null if such * stream is not found in the specified group. */ protected static LogStream findLogStreamByName(final CloudWatchLogsClient awsLogs, final String logGroupName, final String logStreamName) { String nextToken = null; do { DescribeLogStreamsResponse result = awsLogs .describeLogStreams(DescribeLogStreamsRequest.builder() .logGroupName(logGroupName) .nextToken(nextToken) .build()); for (LogStream stream : result.logStreams()) { if (stream.logStreamName().equals(logStreamName)) { return stream; } } nextToken = result.nextToken(); } while (nextToken != null); return null; } /** * @return The MetricFilter object included in the DescribeMetricFilters response, or null if * such filter is not found in the specified group. */ protected static MetricFilter findMetricFilterByName(final CloudWatchLogsClient awsLogs, final String logGroupName, final String filterName) { String nextToken = null; do { DescribeMetricFiltersResponse result = awsLogs .describeMetricFilters(DescribeMetricFiltersRequest.builder() .logGroupName(logGroupName) .nextToken(nextToken) .build()); for (MetricFilter mf : result.metricFilters()) { if (mf.filterName().equals(filterName)) { return mf; } } nextToken = result.nextToken(); } while (nextToken != null); return null; } }
4,760
0
Create_ds/aws-sdk-java-v2/services/cloudwatchlogs/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudwatchlogs/src/it/java/software/amazon/awssdk/services/cloudwatchlogs/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.cloudwatchlogs; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.util.Map; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogGroupRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.CreateLogStreamRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.DeleteLogGroupRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.DeleteLogStreamRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.DeleteMetricFilterRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.DeleteRetentionPolicyRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsResponse; import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent; import software.amazon.awssdk.services.cloudwatchlogs.model.InvalidSequenceTokenException; import software.amazon.awssdk.services.cloudwatchlogs.model.LogGroup; import software.amazon.awssdk.services.cloudwatchlogs.model.LogStream; import software.amazon.awssdk.services.cloudwatchlogs.model.MetricFilter; import software.amazon.awssdk.services.cloudwatchlogs.model.MetricFilterMatchRecord; import software.amazon.awssdk.services.cloudwatchlogs.model.MetricTransformation; import software.amazon.awssdk.services.cloudwatchlogs.model.OutputLogEvent; import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsResponse; import software.amazon.awssdk.services.cloudwatchlogs.model.PutMetricFilterRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.PutRetentionPolicyRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.ResourceAlreadyExistsException; import software.amazon.awssdk.services.cloudwatchlogs.model.TestMetricFilterRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.TestMetricFilterResponse; /** * Integration tests for the CloudWatch Logs service. */ public class ServiceIntegrationTest extends IntegrationTestBase { /* Components of the message body. */ private static final long LOG_MESSAGE_TIMESTAMP = System.currentTimeMillis(); private static final String LOG_MESSAGE_PREFIX = "java-integ-test"; private static final String LOG_MESSAGE_CONTENT = "boom"; /* The log message body and the pattern that we use to filter out such message. */ private static final String LOG_MESSAGE = String.format("%s [%d] %s", LOG_MESSAGE_PREFIX, LOG_MESSAGE_TIMESTAMP, LOG_MESSAGE_CONTENT); private static final String LOG_METRIC_FILTER_PATTERN = "[prefix=java-integ-test, timestamp, content]"; private static final String CLOUDWATCH_METRIC_NAME = "java-integ-test-transformed-metric-name"; private static final String CLOUDWATCH_METRIC_NAMESPACE = "java-integ-test-transformed-metric-namespace"; private static final int LOG_RETENTION_DAYS = 5; private final String nameSuffix = String.valueOf(System.currentTimeMillis()); private final String logGroupName = "java-integ-test-log-group-name-" + nameSuffix; private final String logStreamName = "java-integ-test-log-stream-name-" + nameSuffix; private final String logMetricFilterName = "java-integ-test-log-metric-filter-" + nameSuffix; /** * Test creating a log group using the specified group name. */ public static void testCreateLogGroup(final String groupName) { awsLogs.createLogGroup(CreateLogGroupRequest.builder().logGroupName(groupName).build()); try { awsLogs.createLogGroup(CreateLogGroupRequest.builder().logGroupName(groupName).build()); Assert.fail("ResourceAlreadyExistsException is expected."); } catch (ResourceAlreadyExistsException expected) { // Ignored or expected. } final LogGroup createdGroup = findLogGroupByName(awsLogs, groupName); Assert.assertNotNull(String.format("Log group [%s] is not found in the DescribeLogGroups response.", groupName), createdGroup); Assert.assertEquals(groupName, createdGroup.logGroupName()); Assert.assertNotNull(createdGroup.creationTime()); Assert.assertNotNull(createdGroup.arn()); /* The log group should have no filter and no stored bytes. */ Assert.assertEquals(0, createdGroup.metricFilterCount().intValue()); Assert.assertEquals(0, createdGroup.storedBytes().longValue()); /* Retention policy is still unspecified. */ Assert.assertNull(createdGroup.retentionInDays()); } /** * Test creating a log stream for the specified group. */ public static void testCreateLogStream(final String groupName, final String logStreamName) { awsLogs.createLogStream(CreateLogStreamRequest.builder().logGroupName(groupName).logStreamName(logStreamName).build()); try { awsLogs.createLogStream(CreateLogStreamRequest.builder().logGroupName(groupName).logStreamName(logStreamName).build()); Assert.fail("ResourceAlreadyExistsException is expected."); } catch (ResourceAlreadyExistsException expected) { // Ignored or expected. } final LogStream createdStream = findLogStreamByName(awsLogs, groupName, logStreamName); Assert.assertNotNull( String.format("Log stream [%s] is not found in the [%s] log group.", logStreamName, groupName), createdStream); Assert.assertEquals(logStreamName, createdStream.logStreamName()); Assert.assertNotNull(createdStream.creationTime()); Assert.assertNotNull(createdStream.arn()); /* The log stream should have no stored bytes. */ Assert.assertEquals(0, createdStream.storedBytes().longValue()); /* No log event is pushed yet. */ Assert.assertNull(createdStream.firstEventTimestamp()); Assert.assertNull(createdStream.lastEventTimestamp()); Assert.assertNull(createdStream.lastIngestionTime()); } @Before public void setup() throws IOException { testCreateLogGroup(logGroupName); testCreateLogStream(logGroupName, logStreamName); testCreateMetricFilter(logGroupName, logMetricFilterName); } @After public void tearDown() { try { awsLogs.deleteLogStream(DeleteLogStreamRequest.builder().logGroupName(logGroupName).logStreamName(logStreamName).build()); } catch (SdkServiceException exception) { System.err.println("Unable to delete log stream " + logStreamName); } try { awsLogs.deleteMetricFilter(DeleteMetricFilterRequest.builder().logGroupName(logGroupName).filterName(logMetricFilterName).build()); } catch (SdkServiceException exception) { System.err.println("Unable to delete metric filter " + logMetricFilterName); } try { awsLogs.deleteLogGroup(DeleteLogGroupRequest.builder().logGroupName(logGroupName).build()); } catch (SdkServiceException exception) { System.err.println("Unable to delete log group " + logGroupName); } } /** * Use the TestMetricFilter API to verify the correctness of the metric filter pattern we have * been using in this integration test. */ @Test public void testMetricFilter() { TestMetricFilterRequest request = TestMetricFilterRequest.builder() .filterPattern(LOG_METRIC_FILTER_PATTERN) .logEventMessages(LOG_MESSAGE, "Another message with some content that does not match the filter pattern...") .build(); TestMetricFilterResponse testResult = awsLogs.testMetricFilter(request); Assert.assertEquals(1, testResult.matches().size()); MetricFilterMatchRecord match = testResult.matches().get(0); // Event numbers starts from 1 Assert.assertEquals(1, match.eventNumber().longValue()); Assert.assertEquals(LOG_MESSAGE, match.eventMessage()); // Verify the extracted values Map<String, String> extractedValues = match.extractedValues(); Assert.assertEquals(3, extractedValues.size()); Assert.assertEquals(LOG_MESSAGE_PREFIX, extractedValues.get("$prefix")); Assert.assertEquals(LOG_MESSAGE_TIMESTAMP, Long.parseLong(extractedValues.get("$timestamp"))); Assert.assertEquals(LOG_MESSAGE_CONTENT, extractedValues.get("$content")); } /** * Tests that we have deserialized the exception response correctly. See TT0064111680 */ @Test public void putLogEvents_InvalidSequenceNumber_HasExpectedSequenceNumberInException() { // First call to PutLogEvents does not need a sequence number, subsequent calls do awsLogs.putLogEvents(PutLogEventsRequest.builder() .logGroupName(logGroupName) .logStreamName(logStreamName) .logEvents(InputLogEvent.builder().message(LOG_MESSAGE).timestamp(LOG_MESSAGE_TIMESTAMP).build()) .build()); try { // This call requires a sequence number, if we provide an invalid one the service should // throw an exception with the expected sequence number awsLogs.putLogEvents( PutLogEventsRequest.builder() .logGroupName(logGroupName) .logStreamName(logStreamName) .logEvents(InputLogEvent.builder().message(LOG_MESSAGE).timestamp(LOG_MESSAGE_TIMESTAMP).build()) .sequenceToken("invalid") .build()); } catch (InvalidSequenceTokenException e) { assertNotNull(e.expectedSequenceToken()); } } @Test public void testRetentionPolicy() { awsLogs.putRetentionPolicy(PutRetentionPolicyRequest.builder() .logGroupName(logGroupName) .retentionInDays(LOG_RETENTION_DAYS) .build()); // Use DescribeLogGroup to verify the updated retention policy LogGroup group = findLogGroupByName(awsLogs, logGroupName); Assert.assertNotNull(group); Assert.assertEquals(LOG_RETENTION_DAYS, group.retentionInDays().intValue()); awsLogs.deleteRetentionPolicy(DeleteRetentionPolicyRequest.builder().logGroupName(logGroupName).build()); // Again, use DescribeLogGroup to verify that the retention policy has been deleted group = findLogGroupByName(awsLogs, logGroupName); Assert.assertNotNull(group); Assert.assertNull(group.retentionInDays()); } /** * Test creating a log metric filter for the specified group. */ public void testCreateMetricFilter(final String groupName, final String filterName) { awsLogs.putMetricFilter(PutMetricFilterRequest.builder() .logGroupName(groupName) .filterName(filterName) .filterPattern(LOG_METRIC_FILTER_PATTERN) .metricTransformations(MetricTransformation.builder() .metricName(CLOUDWATCH_METRIC_NAME) .metricNamespace(CLOUDWATCH_METRIC_NAMESPACE) .metricValue("$content") .build()) .build()); final MetricFilter mf = findMetricFilterByName(awsLogs, groupName, filterName); Assert.assertNotNull( String.format("Metric filter [%s] is not found in the [%s] log group.", filterName, groupName), mf); Assert.assertEquals(filterName, mf.filterName()); Assert.assertEquals(LOG_METRIC_FILTER_PATTERN, mf.filterPattern()); Assert.assertNotNull(mf.creationTime()); Assert.assertNotNull(mf.metricTransformations()); // Use DescribeLogGroups to verify that LogGroup.metricFilterCount is updated final LogGroup group = findLogGroupByName(awsLogs, logGroupName); Assert.assertEquals(1, group.metricFilterCount().intValue()); } }
4,761
0
Create_ds/aws-sdk-java-v2/services/workspaces/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/workspaces/src/it/java/software/amazon/awssdk/services/workspaces/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.workspaces; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.testutils.service.AwsTestBase; public class IntegrationTestBase extends AwsTestBase { protected static WorkSpacesClient client; @BeforeClass public static void setup() throws IOException { setUpCredentials(); client = WorkSpacesClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } }
4,762
0
Create_ds/aws-sdk-java-v2/services/workspaces/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/workspaces/src/it/java/software/amazon/awssdk/services/workspaces/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.workspaces; import static org.junit.Assert.assertTrue; import org.junit.Test; import software.amazon.awssdk.services.workspaces.model.CreateWorkspacesRequest; import software.amazon.awssdk.services.workspaces.model.CreateWorkspacesResponse; import software.amazon.awssdk.services.workspaces.model.DescribeWorkspaceBundlesRequest; import software.amazon.awssdk.services.workspaces.model.DescribeWorkspaceBundlesResponse; import software.amazon.awssdk.services.workspaces.model.DescribeWorkspaceDirectoriesRequest; import software.amazon.awssdk.services.workspaces.model.DescribeWorkspaceDirectoriesResponse; import software.amazon.awssdk.services.workspaces.model.DescribeWorkspacesRequest; import software.amazon.awssdk.services.workspaces.model.DescribeWorkspacesResponse; import software.amazon.awssdk.services.workspaces.model.WorkspaceRequest; public class ServiceIntegrationTest extends IntegrationTestBase { @Test public void describeWorkspaces() { DescribeWorkspacesResponse result = client.describeWorkspaces(DescribeWorkspacesRequest.builder().build()); assertTrue(result.workspaces().isEmpty()); } @Test public void describeWorkspaceBundles() { DescribeWorkspaceBundlesResponse result = client.describeWorkspaceBundles(DescribeWorkspaceBundlesRequest.builder().build()); assertTrue(result.bundles().isEmpty()); } @Test public void describeWorkspaceDirectories() { DescribeWorkspaceDirectoriesResponse result = client.describeWorkspaceDirectories(DescribeWorkspaceDirectoriesRequest.builder().build()); assertTrue(result.directories().isEmpty()); } @Test public void createWorkspaces() { CreateWorkspacesResponse result = client.createWorkspaces(CreateWorkspacesRequest.builder() .workspaces(WorkspaceRequest.builder() .userName("hchar") .bundleId("wsb-12345678") .directoryId("d-12345678") .build()) .build()); assertTrue(result.failedRequests().size() == 1); } }
4,763
0
Create_ds/aws-sdk-java-v2/services/machinelearning/src/main/java/software/amazon/awssdk/services/machinelearning
Create_ds/aws-sdk-java-v2/services/machinelearning/src/main/java/software/amazon/awssdk/services/machinelearning/internal/PredictEndpointInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.machinelearning.internal; import java.net.URI; import java.net.URISyntaxException; import software.amazon.awssdk.annotations.SdkInternalApi; 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.SdkHttpRequest; import software.amazon.awssdk.services.machinelearning.model.PredictRequest; /** * Predict calls are sent to a predictor-specific endpoint. This handler * extracts the PredictRequest's PredictEndpoint "parameter" and swaps it in as * the endpoint to send the request to. */ @SdkInternalApi public final class PredictEndpointInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); Object originalRequest = context.request(); if (originalRequest instanceof PredictRequest) { PredictRequest pr = (PredictRequest) originalRequest; if (pr.predictEndpoint() == null) { throw SdkClientException.builder().message("PredictRequest.PredictEndpoint is required!").build(); } try { URI endpoint = new URI(pr.predictEndpoint()); return request.toBuilder().uri(endpoint).build(); } catch (URISyntaxException e) { throw SdkClientException.builder() .message("Unable to parse PredictRequest.PredictEndpoint") .cause(e) .build(); } } return request; } }
4,764
0
Create_ds/aws-sdk-java-v2/services/machinelearning/src/main/java/software/amazon/awssdk/services/machinelearning
Create_ds/aws-sdk-java-v2/services/machinelearning/src/main/java/software/amazon/awssdk/services/machinelearning/internal/RandomIdInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.machinelearning.internal; import java.util.UUID; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.services.machinelearning.model.CreateBatchPredictionRequest; import software.amazon.awssdk.services.machinelearning.model.CreateDataSourceFromRdsRequest; import software.amazon.awssdk.services.machinelearning.model.CreateDataSourceFromRedshiftRequest; import software.amazon.awssdk.services.machinelearning.model.CreateDataSourceFromS3Request; import software.amazon.awssdk.services.machinelearning.model.CreateEvaluationRequest; import software.amazon.awssdk.services.machinelearning.model.CreateMlModelRequest; /** * CreateXxx API calls require a unique (for all time!) ID parameter for * idempotency. If the user doesn't specify one, fill in a GUID. */ @SdkInternalApi //TODO: They should be using the idempotency trait public final class RandomIdInterceptor implements ExecutionInterceptor { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { SdkRequest request = context.request(); if (request instanceof CreateBatchPredictionRequest) { CreateBatchPredictionRequest copy = (CreateBatchPredictionRequest) request; if (copy.batchPredictionDataSourceId() == null) { return copy.toBuilder().batchPredictionDataSourceId(UUID.randomUUID().toString()).build(); } return copy; } else if (request instanceof CreateDataSourceFromRdsRequest) { CreateDataSourceFromRdsRequest copy = (CreateDataSourceFromRdsRequest) request; if (copy.dataSourceId() == null) { copy = copy.toBuilder().dataSourceId(UUID.randomUUID().toString()).build(); } return copy; } else if (request instanceof CreateDataSourceFromRedshiftRequest) { CreateDataSourceFromRedshiftRequest copy = (CreateDataSourceFromRedshiftRequest) request; if (copy.dataSourceId() == null) { copy = copy.toBuilder().dataSourceId(UUID.randomUUID().toString()).build(); } return copy; } else if (request instanceof CreateDataSourceFromS3Request) { CreateDataSourceFromS3Request copy = (CreateDataSourceFromS3Request) request; if (copy.dataSourceId() == null) { copy = copy.toBuilder().dataSourceId(UUID.randomUUID().toString()).build(); } return copy; } else if (request instanceof CreateEvaluationRequest) { CreateEvaluationRequest copy = (CreateEvaluationRequest) request; if (copy.evaluationId() == null) { copy = copy.toBuilder().evaluationId(UUID.randomUUID().toString()).build(); } return copy; } else if (request instanceof CreateMlModelRequest) { CreateMlModelRequest copy = (CreateMlModelRequest) request; if (copy.mlModelId() == null) { copy = copy.toBuilder().mlModelId(UUID.randomUUID().toString()).build(); } return copy; } return request; } }
4,765
0
Create_ds/aws-sdk-java-v2/services/codepipeline/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/codepipeline/src/it/java/software/amazon/awssdk/services/codepipeline/AwsCodePipelineClientIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.codepipeline; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.codepipeline.model.ActionCategory; import software.amazon.awssdk.services.codepipeline.model.ActionOwner; import software.amazon.awssdk.services.codepipeline.model.ActionType; import software.amazon.awssdk.services.codepipeline.model.ActionTypeId; import software.amazon.awssdk.services.codepipeline.model.ArtifactDetails; import software.amazon.awssdk.services.codepipeline.model.CreateCustomActionTypeRequest; import software.amazon.awssdk.services.codepipeline.model.DeleteCustomActionTypeRequest; import software.amazon.awssdk.services.codepipeline.model.InvalidNextTokenException; import software.amazon.awssdk.services.codepipeline.model.ListActionTypesRequest; import software.amazon.awssdk.services.codepipeline.model.ListActionTypesResponse; import software.amazon.awssdk.services.codepipeline.model.ListPipelinesRequest; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Smoke tests for the {@link CodePipelineClient}. */ public class AwsCodePipelineClientIntegrationTest extends AwsTestBase { private static CodePipelineClient client; @BeforeClass public static void setup() throws Exception { setUpCredentials(); client = CodePipelineClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } /** * Determine whether the requested action type is in the provided list. * * @param actionTypes * List of {@link ActionType}s to search * @param actionTypeId * {@link ActionType} to search for * @return True if actionTypeId is in actionTypes, false otherwise */ private static boolean containsActionTypeId(List<ActionType> actionTypes, ActionTypeId actionTypeId) { for (ActionType actionType : actionTypes) { if (actionType.id().equals(actionTypeId)) { return true; } } return false; } @Test public void listActionTypes_WithNoFilter_ReturnsNonEmptyList() { assertThat(client.listActionTypes(ListActionTypesRequest.builder().build()).actionTypes().size(), greaterThan(0)); } /** * Simple smoke test to create a custom action, make sure it was persisted, and then * subsequently delete it. */ @Test public void createFindDelete_ActionType() { ActionTypeId actionTypeId = ActionTypeId.builder() .category(ActionCategory.BUILD) .provider("test-provider") .version("1") .owner(ActionOwner.CUSTOM) .build(); ArtifactDetails artifactDetails = ArtifactDetails.builder() .maximumCount(1) .minimumCount(1) .build(); client.createCustomActionType(CreateCustomActionTypeRequest.builder() .category(actionTypeId.category()) .provider(actionTypeId.provider()) .version(actionTypeId.version()) .inputArtifactDetails(artifactDetails) .outputArtifactDetails(artifactDetails) .build()); final ListActionTypesResponse actionTypes = client.listActionTypes(ListActionTypesRequest.builder().build()); assertTrue(containsActionTypeId(actionTypes.actionTypes(), actionTypeId)); client.deleteCustomActionType(DeleteCustomActionTypeRequest.builder() .category(actionTypeId.category()) .provider(actionTypeId.provider()) .version(actionTypeId.version()).build()); } }
4,766
0
Create_ds/aws-sdk-java-v2/services/directory/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/directory/src/it/java/software/amazon/awssdk/services/directory/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.directory; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class IntegrationTestBase extends AwsIntegrationTestBase { protected static DirectoryClient dsClient; protected static Ec2Client ec2Client; @BeforeClass public static void baseSetupFixture() { dsClient = DirectoryClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.US_EAST_1) .build(); ec2Client = Ec2Client.builder() .region(Region.US_EAST_1) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); } }
4,767
0
Create_ds/aws-sdk-java-v2/services/directory/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/directory/src/it/java/software/amazon/awssdk/services/directory/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.directory; import static org.junit.Assert.assertNotNull; import java.util.List; import junit.framework.Assert; import org.junit.Test; import software.amazon.awssdk.services.directory.model.CreateDirectoryRequest; import software.amazon.awssdk.services.directory.model.DeleteDirectoryRequest; import software.amazon.awssdk.services.directory.model.DescribeDirectoriesRequest; import software.amazon.awssdk.services.directory.model.DirectorySize; import software.amazon.awssdk.services.directory.model.DirectoryVpcSettings; import software.amazon.awssdk.services.directory.model.InvalidNextTokenException; import software.amazon.awssdk.services.ec2.model.DescribeSubnetsRequest; import software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest; import software.amazon.awssdk.services.ec2.model.Filter; import software.amazon.awssdk.services.ec2.model.Subnet; import software.amazon.awssdk.services.ec2.model.Vpc; public class ServiceIntegrationTest extends IntegrationTestBase { private static final String US_EAST_1A = "us-east-1a"; private static final String US_EAST_1B = "us-east-1b"; @Test public void testDirectories() { String vpcId = getVpcId(); // Creating a directory requires at least two subnets located in // different availability zones String subnetId_0 = getSubnetIdInVpc(vpcId, US_EAST_1A); String subnetId_1 = getSubnetIdInVpc(vpcId, US_EAST_1B); String dsId = dsClient .createDirectory(CreateDirectoryRequest.builder().description("This is my directory!") .name("AWS.Java.SDK.Directory").shortName("md").password("My.Awesome.Password.2015") .size(DirectorySize.SMALL).vpcSettings( DirectoryVpcSettings.builder().vpcId(vpcId).subnetIds(subnetId_0, subnetId_1).build()).build()) .directoryId(); dsClient.deleteDirectory(DeleteDirectoryRequest.builder().directoryId(dsId).build()); } private String getVpcId() { List<Vpc> vpcs = ec2Client.describeVpcs(DescribeVpcsRequest.builder().build()).vpcs(); if (vpcs.isEmpty()) { Assert.fail("No VPC found in this account."); } return vpcs.get(0).vpcId(); } private String getSubnetIdInVpc(String vpcId, String az) { List<Subnet> subnets = ec2Client.describeSubnets(DescribeSubnetsRequest.builder() .filters( Filter.builder() .name("vpc-id") .values(vpcId) .build(), Filter.builder() .name("availabilityZone") .values(az) .build()) .build()) .subnets(); if (subnets.isEmpty()) { Assert.fail("No Subnet found in VPC " + vpcId + " AvailabilityZone: " + az); } return subnets.get(0).subnetId(); } /** * Tests that an exception with a member in it is serialized properly. See TT0064111680 */ @Test public void describeDirectories_InvalidNextToken_ThrowsExceptionWithRequestIdPresent() { try { dsClient.describeDirectories(DescribeDirectoriesRequest.builder().nextToken("invalid").build()); } catch (InvalidNextTokenException e) { assertNotNull(e.requestId()); } } }
4,768
0
Create_ds/aws-sdk-java-v2/services/sqs/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sqs/src/test/java/software/amazon/awssdk/services/sqs/MessageMD5ChecksumInterceptorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sqs; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.services.sqs.internal.MessageMD5ChecksumInterceptor; import software.amazon.awssdk.services.sqs.model.Message; import software.amazon.awssdk.services.sqs.model.MessageAttributeValue; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry; import software.amazon.awssdk.services.sqs.model.SendMessageBatchResponse; import software.amazon.awssdk.services.sqs.model.SendMessageBatchResultEntry; import software.amazon.awssdk.services.sqs.model.SendMessageRequest; import software.amazon.awssdk.services.sqs.model.SendMessageResponse; /** * Verifies the functionality of {@link MessageMD5ChecksumInterceptor}. */ public class MessageMD5ChecksumInterceptorTest { @Test public void sendMessagePassesValidChecksums() { SendMessageRequest request = SendMessageRequest.builder() .messageBody(messageBody()) .messageAttributes(messageAttributes()) .build(); SendMessageResponse response = SendMessageResponse.builder() .md5OfMessageBody(messageBodyChecksum()) .md5OfMessageAttributes(messageAttributesChecksum()) .build(); assertSuccess(request, response); } @Test public void sendMessageFailsInvalidBodyChecksum() { SendMessageRequest request = SendMessageRequest.builder() .messageBody(messageBody()) .messageAttributes(messageAttributes()) .build(); SendMessageResponse response = SendMessageResponse.builder() .md5OfMessageBody("bad") .md5OfMessageAttributes(messageAttributesChecksum()) .build(); assertFailure(request, response); } @Test public void sendMessageFailsInvalidAttributeChecksum() { SendMessageRequest request = SendMessageRequest.builder() .messageBody(messageBody()) .messageAttributes(messageAttributes()) .build(); SendMessageResponse response = SendMessageResponse.builder() .md5OfMessageBody(messageBodyChecksum()) .md5OfMessageAttributes("bad") .build(); assertFailure(request, response); } @Test public void sendMessageBatchPassesValidChecksums() { SendMessageBatchRequestEntry requestEntry = SendMessageBatchRequestEntry.builder() .messageBody(messageBody()) .messageAttributes(messageAttributes()) .build(); SendMessageBatchResultEntry resultEntry = SendMessageBatchResultEntry.builder() .md5OfMessageBody(messageBodyChecksum()) .md5OfMessageAttributes(messageAttributesChecksum()) .build(); SendMessageBatchRequest request = SendMessageBatchRequest.builder() .entries(requestEntry, requestEntry) .build(); SendMessageBatchResponse response = SendMessageBatchResponse.builder() .successful(resultEntry, resultEntry) .build(); assertSuccess(request, response); } @Test public void sendMessageBatchFailsInvalidBodyChecksums() { SendMessageBatchRequestEntry requestEntry = SendMessageBatchRequestEntry.builder() .messageBody(messageBody()) .messageAttributes(messageAttributes()) .build(); SendMessageBatchResultEntry resultEntry = SendMessageBatchResultEntry.builder() .md5OfMessageBody(messageBodyChecksum()) .md5OfMessageAttributes(messageAttributesChecksum()) .build(); SendMessageBatchResultEntry badResultEntry = SendMessageBatchResultEntry.builder() .md5OfMessageBody("bad") .md5OfMessageAttributes(messageAttributesChecksum()) .build(); SendMessageBatchRequest request = SendMessageBatchRequest.builder() .entries(requestEntry, requestEntry) .build(); SendMessageBatchResponse response = SendMessageBatchResponse.builder() .successful(resultEntry, badResultEntry) .build(); assertFailure(request, response); } @Test public void sendMessageBatchFailsInvalidAttributeChecksums() { SendMessageBatchRequestEntry requestEntry = SendMessageBatchRequestEntry.builder() .messageBody(messageBody()) .messageAttributes(messageAttributes()) .build(); SendMessageBatchResultEntry resultEntry = SendMessageBatchResultEntry.builder() .md5OfMessageBody(messageBodyChecksum()) .md5OfMessageAttributes(messageAttributesChecksum()) .build(); SendMessageBatchResultEntry badResultEntry = SendMessageBatchResultEntry.builder() .md5OfMessageBody(messageBodyChecksum()) .md5OfMessageAttributes("bad") .build(); SendMessageBatchRequest request = SendMessageBatchRequest.builder() .entries(requestEntry, requestEntry) .build(); SendMessageBatchResponse response = SendMessageBatchResponse.builder() .successful(resultEntry, badResultEntry) .build(); assertFailure(request, response); } @Test public void receiveMessagePassesValidChecksums() { Message message = Message.builder() .body(messageBody()) .messageAttributes(messageAttributes()) .md5OfBody(messageBodyChecksum()) .md5OfMessageAttributes(messageAttributesChecksum()) .build(); ReceiveMessageResponse response = ReceiveMessageResponse.builder() .messages(message, message) .build(); assertSuccess(ReceiveMessageRequest.builder().build(), response); } @Test public void receiveMessageFailsInvalidBodyChecksum() { Message message = Message.builder() .body(messageBody()) .messageAttributes(messageAttributes()) .md5OfBody(messageBodyChecksum()) .md5OfMessageAttributes(messageAttributesChecksum()) .build(); Message badMessage = Message.builder() .body(messageBody()) .messageAttributes(messageAttributes()) .md5OfBody("bad") .md5OfMessageAttributes(messageAttributesChecksum()) .build(); ReceiveMessageResponse response = ReceiveMessageResponse.builder() .messages(message, badMessage) .build(); assertFailure(ReceiveMessageRequest.builder().build(), response); } @Test public void receiveMessageFailsInvalidAttributeChecksum() { Message message = Message.builder() .body(messageBody()) .messageAttributes(messageAttributes()) .md5OfBody(messageBodyChecksum()) .md5OfMessageAttributes(messageAttributesChecksum()) .build(); Message badMessage = Message.builder() .body(messageBody()) .messageAttributes(messageAttributes()) .md5OfBody(messageBodyChecksum()) .md5OfMessageAttributes("bad") .build(); ReceiveMessageResponse response = ReceiveMessageResponse.builder() .messages(message, badMessage) .build(); assertFailure(ReceiveMessageRequest.builder().build(), response); } private void assertSuccess(SdkRequest request, SdkResponse response) { callInterceptor(request, response); } private void assertFailure(SdkRequest request, SdkResponse response) { assertThatThrownBy(() -> callInterceptor(request, response)) .isInstanceOf(SdkClientException.class); } private void callInterceptor(SdkRequest request, SdkResponse response) { new MessageMD5ChecksumInterceptor().afterExecution(InterceptorContext.builder() .request(request) .response(response) .build(), new ExecutionAttributes()); } private String messageBody() { return "Body"; } private String messageBodyChecksum() { return "ac101b32dda4448cf13a93fe283dddd8"; } private Map<String, MessageAttributeValue> messageAttributes() { Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("String", MessageAttributeValue.builder() .stringValue("Value") .dataType("String") .build()); messageAttributes.put("Binary", MessageAttributeValue.builder() .binaryValue(SdkBytes.fromByteArray(new byte[] { 5 })) .dataType("Binary") .build()); messageAttributes.put("StringList", MessageAttributeValue.builder() .stringListValues("ListValue") .dataType("String") .build()); messageAttributes.put("ByteList", MessageAttributeValue.builder() .binaryListValues(SdkBytes.fromByteArray(new byte[] { 3 })) .dataType("Binary") .build()); return messageAttributes; } private String messageAttributesChecksum() { return "4b6959cf7735fdade89bc099b85b3234"; } }
4,769
0
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services/sqs/SqsQueueResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sqs; import software.amazon.awssdk.core.auth.policy.Resource; /** * AWS access control policy resource that identifies an Amazon SQS queue. * <p> * This is an older style of referencing an Amazon SQS queue. You can also use the queue's Amazon * Resource Name (ARN), which you can obtain by calling * {@link software.amazon.awssdk.services.sqs.SqsClient#getQueueAttributes( * software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest)} * and requesting the "QueueArn" attribute. */ public class SqsQueueResource extends Resource { /** * Constructs a new SQS queue resource for an access control policy. A policy statement using * this resource will allow or deny actions on the specified queue. * * @param accountId The AWS account ID of the queue owner. * @param queueName The name of the Amazon SQS queue. */ public SqsQueueResource(String accountId, String queueName) { super("/" + formatAccountId(accountId) + "/" + queueName); } private static String formatAccountId(String accountId) { if (accountId == null) { throw new IllegalArgumentException("Account ID cannot be null"); } return accountId.trim().replaceAll("-", ""); } }
4,770
0
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services/sqs/MessageAttributesIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sqs; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static software.amazon.awssdk.testutils.SdkAsserts.assertNotEmpty; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; 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.services.sqs.model.DeleteQueueRequest; import software.amazon.awssdk.services.sqs.model.Message; import software.amazon.awssdk.services.sqs.model.MessageAttributeValue; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry; import software.amazon.awssdk.services.sqs.model.SendMessageBatchResponse; import software.amazon.awssdk.services.sqs.model.SendMessageRequest; import software.amazon.awssdk.services.sqs.model.SendMessageResponse; import software.amazon.awssdk.utils.ImmutableMap; /** * Integration tests for the SQS message attributes. */ public class MessageAttributesIntegrationTest extends IntegrationTestBase { private static final String MESSAGE_BODY = "message-body-" + System.currentTimeMillis(); private String queueUrl; @Before public void setup() { queueUrl = createQueue(sqsAsync); } @After public void tearDown() throws Exception { sqsAsync.deleteQueue(DeleteQueueRequest.builder().queueUrl(queueUrl).build()); } @Test public void sendMessage_InvalidMd5_ThrowsException() { try (SqsClient tamperingClient = SqsClient.builder() .credentialsProvider(getCredentialsProvider()) .overrideConfiguration(ClientOverrideConfiguration .builder() .addExecutionInterceptor( new TamperingInterceptor()) .build()) .build()) { tamperingClient.sendMessage( SendMessageRequest.builder() .queueUrl(queueUrl) .messageBody(MESSAGE_BODY) .messageAttributes(createRandomAttributeValues(10)) .build()); fail("Expected SdkClientException"); } catch (SdkClientException e) { assertThat(e.getMessage(), containsString("MD5 returned by SQS does not match")); } } public static class TamperingInterceptor implements ExecutionInterceptor { @Override public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) { if (context.response() instanceof SendMessageResponse) { return ((SendMessageResponse) context.response()).toBuilder() .md5OfMessageBody("invalid-md5") .build(); } return context.response(); } } @Test public void sendMessage_WithMessageAttributes_ResultHasMd5OfMessageAttributes() { SendMessageResponse sendMessageResult = sendTestMessage(); assertNotEmpty(sendMessageResult.md5OfMessageBody()); assertNotEmpty(sendMessageResult.md5OfMessageAttributes()); } /** * Makes sure we don't modify the state of ByteBuffer backed attributes in anyway internally * before returning the result to the customer. See https://github.com/aws/aws-sdk-java/pull/459 * for reference */ @Test public void receiveMessage_WithBinaryAttributeValue_DoesNotChangeStateOfByteBuffer() { byte[] bytes = new byte[]{1, 1, 1, 0, 0, 0}; String byteBufferAttrName = "byte-buffer-attr"; Map<String, MessageAttributeValue> attrs = ImmutableMap.of(byteBufferAttrName, MessageAttributeValue.builder().dataType("Binary").binaryValue(SdkBytes.fromByteArray(bytes)).build()); sqsAsync.sendMessage(SendMessageRequest.builder().queueUrl(queueUrl).messageBody("test") .messageAttributes(attrs) .build()); // Long poll to make sure we get the message back List<Message> messages = sqsAsync.receiveMessage( ReceiveMessageRequest.builder().queueUrl(queueUrl).messageAttributeNames("All").waitTimeSeconds(20).build()).join() .messages(); ByteBuffer actualByteBuffer = messages.get(0).messageAttributes().get(byteBufferAttrName).binaryValue().asByteBuffer(); assertEquals(bytes.length, actualByteBuffer.remaining()); } @Test public void receiveMessage_WithAllAttributesRequested_ReturnsAttributes() throws Exception { sendTestMessage(); ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder().queueUrl(queueUrl).waitTimeSeconds(5) .visibilityTimeout(0).messageAttributeNames("All").build(); ReceiveMessageResponse receiveMessageResult = sqsAsync.receiveMessage(receiveMessageRequest).join(); assertFalse(receiveMessageResult.messages().isEmpty()); Message message = receiveMessageResult.messages().get(0); assertEquals(MESSAGE_BODY, message.body()); assertNotEmpty(message.md5OfBody()); assertNotEmpty(message.md5OfMessageAttributes()); } /** * Tests SQS operations that involve message attributes checksum. */ @Test public void receiveMessage_WithNoAttributesRequested_DoesNotReturnAttributes() throws Exception { sendTestMessage(); ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder().queueUrl(queueUrl).waitTimeSeconds(5) .visibilityTimeout(0).build(); ReceiveMessageResponse receiveMessageResult = sqsAsync.receiveMessage(receiveMessageRequest).join(); assertFalse(receiveMessageResult.messages().isEmpty()); Message message = receiveMessageResult.messages().get(0); assertEquals(MESSAGE_BODY, message.body()); assertNotEmpty(message.md5OfBody()); assertNull(message.md5OfMessageAttributes()); } @Test public void sendMessageBatch_WithMessageAttributes_ResultHasMd5OfMessageAttributes() { SendMessageBatchResponse sendMessageBatchResult = sqsAsync.sendMessageBatch(SendMessageBatchRequest.builder() .queueUrl(queueUrl) .entries( SendMessageBatchRequestEntry.builder().id("1").messageBody(MESSAGE_BODY) .messageAttributes(createRandomAttributeValues(1)).build(), SendMessageBatchRequestEntry.builder().id("2").messageBody(MESSAGE_BODY) .messageAttributes(createRandomAttributeValues(2)).build(), SendMessageBatchRequestEntry.builder().id("3").messageBody(MESSAGE_BODY) .messageAttributes(createRandomAttributeValues(3)).build(), SendMessageBatchRequestEntry.builder().id("4").messageBody(MESSAGE_BODY) .messageAttributes(createRandomAttributeValues(4)).build(), SendMessageBatchRequestEntry.builder().id("5").messageBody(MESSAGE_BODY) .messageAttributes(createRandomAttributeValues(5)).build()) .build()) .join(); assertThat(sendMessageBatchResult.successful().size(), greaterThan(0)); assertNotEmpty(sendMessageBatchResult.successful().get(0).id()); assertNotEmpty(sendMessageBatchResult.successful().get(0).md5OfMessageBody()); assertNotEmpty(sendMessageBatchResult.successful().get(0).md5OfMessageAttributes()); } private SendMessageResponse sendTestMessage() { SendMessageResponse sendMessageResult = sqsAsync.sendMessage(SendMessageRequest.builder().queueUrl(queueUrl).messageBody(MESSAGE_BODY) .messageAttributes(createRandomAttributeValues(10)).build()).join(); return sendMessageResult; } }
4,771
0
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services/sqs/SqsConcurrentPerformanceIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sqs; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.junit.Ignore; import org.junit.Test; import software.amazon.awssdk.services.sqs.model.ListQueuesRequest; /** * This is a manually run test that can be run to test idle connection reaping in the SDK. * Connections sitting around in the connection pool for too long will eventually be terminated by * the AWS end of the connection, and will go into CLOSE_WAIT. If this happens, sockets will sit * around in CLOSE_WAIT, still using resources on the client side to manage that socket. At its * worse, this can cause the client to be unable to create any new connections until the CLOSE_WAIT * sockets are eventually expired and released. */ public class SqsConcurrentPerformanceIntegrationTest extends IntegrationTestBase { /** Total number of worker threads to hit SQS. */ private static final int TOTAL_WORKER_THREADS = 30; private SqsAsyncClient sqs; /** * Spins up a pool of threads to make concurrent requests and thus grow the runtime's HTTP * connection pool, then sits idle. * <p> * You can use the netstat command to look at the current sockets connected to SQS and verify * that they don't sit around in CLOSE_WAIT, and are correctly being reaped. */ // CHECKSTYLE:OFF - Allowing @Ignore for this manual test @Test @Ignore // CHECKSTYLE:ON public void testIdleConnectionReaping() throws Exception { sqs = SqsAsyncClient.builder().credentialsProvider(getCredentialsProvider()).build(); sqs = SqsAsyncClient.builder().credentialsProvider(getCredentialsProvider()).build(); List<WorkerThread> workers = new ArrayList<WorkerThread>(); for (int i = 0; i < TOTAL_WORKER_THREADS; i++) { workers.add(new WorkerThread()); } for (WorkerThread worker : workers) { worker.start(); } // Sleep for five minutes to let the sockets go idle Thread.sleep(1000 * 60 * 5); // Wait for the user to acknowledge test before we exit the JVM System.out.println("Test complete"); waitForUserInput(); } private class WorkerThread extends Thread { @Override public void run() { sqs.listQueues(ListQueuesRequest.builder().build()); sqs.listQueues(ListQueuesRequest.builder().build()); } } private void waitForUserInput() throws IOException { new BufferedReader(new InputStreamReader(System.in)).readLine(); } }
4,772
0
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services/sqs/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.sqs; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.UUID; import org.junit.Before; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.iam.model.GetUserRequest; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.CreateQueueResponse; import software.amazon.awssdk.services.sqs.model.MessageAttributeValue; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; import software.amazon.awssdk.utils.StringUtils; /** * Base class for SQS integration tests. Provides convenience methods for creating test data, and * automatically loads AWS credentials from a properties file on disk and instantiates clients for * the individual tests to use. */ public class IntegrationTestBase extends AwsIntegrationTestBase { /** * Random number used for naming message attributes. */ private static final Random random = new Random(System.currentTimeMillis()); /** * The Async SQS client for all tests to use. */ protected SqsAsyncClient sqsAsync; /** * The Sync SQS client for all tests to use. */ protected SqsClient sqsSync; /** * Account ID of the AWS Account identified by the credentials provider setup in AWSTestBase. * Cached for performance **/ private static String accountId; /** * Loads the AWS account info for the integration tests and creates an SQS client for tests to * use. */ @Before public void setUp() { sqsAsync = createSqsAyncClient(); sqsSync = createSqsSyncClient(); } public static SqsAsyncClient createSqsAyncClient() { return SqsAsyncClient.builder() .credentialsProvider(getCredentialsProvider()) .build(); } public static SqsClient createSqsSyncClient() { return SqsClient.builder() .credentialsProvider(getCredentialsProvider()) .build(); } protected static MessageAttributeValue createRandomStringAttributeValue() { return MessageAttributeValue.builder().dataType("String").stringValue(UUID.randomUUID().toString()).build(); } protected static MessageAttributeValue createRandomNumberAttributeValue() { return MessageAttributeValue.builder().dataType("Number").stringValue(Integer.toString(random.nextInt())).build(); } protected static MessageAttributeValue createRandomBinaryAttributeValue() { byte[] randomBytes = new byte[10]; random.nextBytes(randomBytes); return MessageAttributeValue.builder().dataType("Binary").binaryValue(SdkBytes.fromByteArray(randomBytes)).build(); } protected static Map<String, MessageAttributeValue> createRandomAttributeValues(int attrNumber) { Map<String, MessageAttributeValue> attrs = new HashMap<String, MessageAttributeValue>(); for (int i = 0; i < attrNumber; i++) { int randomeAttributeType = random.nextInt(3); MessageAttributeValue randomAttrValue = null; switch (randomeAttributeType) { case 0: randomAttrValue = createRandomStringAttributeValue(); break; case 1: randomAttrValue = createRandomNumberAttributeValue(); break; case 2: randomAttrValue = createRandomBinaryAttributeValue(); break; default: break; } attrs.put("attribute-" + UUID.randomUUID(), randomAttrValue); } return Collections.unmodifiableMap(attrs); } /** * Helper method to create a SQS queue with a unique name * * @return The queue url for the created queue */ protected String createQueue(SqsAsyncClient sqsClient) { CreateQueueResponse res = sqsClient.createQueue(CreateQueueRequest.builder().queueName(getUniqueQueueName()).build()).join(); return res.queueUrl(); } /** * Generate a unique queue name to use in tests */ protected String getUniqueQueueName() { return String.format("%s-%s", getClass().getSimpleName(), System.currentTimeMillis()); } /** * Get the account id of the AWS account used in the tests */ protected String getAccountId() { if (accountId == null) { IamClient iamClient = IamClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.AWS_GLOBAL) .build(); accountId = parseAccountIdFromArn(iamClient.getUser(GetUserRequest.builder().build()).user().arn()); } return accountId; } /** * Parse the account ID out of the IAM user arn * * @param arn IAM user ARN * @return Account ID if it can be extracted * @throws IllegalArgumentException If ARN is not in a valid format */ private String parseAccountIdFromArn(String arn) throws IllegalArgumentException { String[] arnComponents = arn.split(":"); if (arnComponents.length < 5 || StringUtils.isEmpty(arnComponents[4])) { throw new IllegalArgumentException(String.format("%s is not a valid ARN", arn)); } return arnComponents[4]; } }
4,773
0
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services/sqs/SqsIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sqs; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import org.junit.Test; import software.amazon.awssdk.core.SdkGlobalTime; import software.amazon.awssdk.services.sqs.model.ListQueuesRequest; /** * Integration tests for the SQS Java client. */ public class SqsIntegrationTest extends IntegrationTestBase { /** * 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 clockSkewFailure_CorrectsGlobalTimeOffset() throws Exception { final int originalOffset = SdkGlobalTime.getGlobalTimeOffset(); final int skew = 3600; SdkGlobalTime.setGlobalTimeOffset(skew); assertEquals(skew, SdkGlobalTime.getGlobalTimeOffset()); SqsAsyncClient sqsClient = createSqsAyncClient(); sqsClient.listQueues(ListQueuesRequest.builder().build()).thenCompose( __ -> { assertThat("Clockskew is fixed!", SdkGlobalTime.getGlobalTimeOffset(), lessThan(skew)); // subsequent changes to the global time offset won't affect existing client SdkGlobalTime.setGlobalTimeOffset(skew); return sqsClient.listQueues(ListQueuesRequest.builder().build()); }).thenAccept( __ -> { assertEquals(skew, SdkGlobalTime.getGlobalTimeOffset()); }).join(); sqsClient.close(); SdkGlobalTime.setGlobalTimeOffset(originalOffset); } }
4,774
0
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services/sqs/auth
Create_ds/aws-sdk-java-v2/services/sqs/src/it/java/software/amazon/awssdk/services/sqs/auth/policy/SqsPolicyIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sqs.auth.policy; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Test; import software.amazon.awssdk.core.auth.policy.Action; import software.amazon.awssdk.core.auth.policy.Policy; import software.amazon.awssdk.core.auth.policy.Principal; import software.amazon.awssdk.core.auth.policy.Statement; import software.amazon.awssdk.core.auth.policy.Statement.Effect; import software.amazon.awssdk.core.auth.policy.conditions.DateCondition; import software.amazon.awssdk.core.auth.policy.conditions.DateCondition.DateComparisonType; import software.amazon.awssdk.services.sqs.IntegrationTestBase; import software.amazon.awssdk.services.sqs.SqsQueueResource; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest; import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest; /** * Integration tests for the service specific access control policy code provided by the SQS client. */ public class SqsPolicyIntegrationTest extends IntegrationTestBase { /** * Doesn't have to be a valid account id, just has to have a value **/ private static final String ACCOUNT_ID = "123456789"; private String queueUrl; /** * Releases all test resources */ @After public void tearDown() throws Exception { sqsSync.deleteQueue(DeleteQueueRequest.builder().queueUrl(queueUrl).build()); } /** * Tests that the SQS specific access control policy code works as expected. */ @Test public void testPolicies() throws Exception { String queueName = getUniqueQueueName(); queueUrl = sqsSync.createQueue(CreateQueueRequest.builder().queueName(queueName).build()).queueUrl(); Policy policy = new Policy().withStatements(new Statement(Effect.Allow).withPrincipals(Principal.ALL_USERS) .withActions(new Action("sqs:SendMessage"), new Action("sqs:ReceiveMessage")) .withResources(new SqsQueueResource(ACCOUNT_ID, queueName)) .withConditions(new DateCondition(DateComparisonType.DateLessThan, new Date()))); setQueuePolicy(policy); } private void setQueuePolicy(Policy policy) { Map<String, String> attributes = new HashMap<String, String>(); attributes.put("Policy", policy.toJson()); sqsSync.setQueueAttributes(SetQueueAttributesRequest.builder() .queueUrl(queueUrl) .attributesWithStrings(attributes) .build()); } }
4,775
0
Create_ds/aws-sdk-java-v2/services/sqs/src/main/java/software/amazon/awssdk/services/sqs
Create_ds/aws-sdk-java-v2/services/sqs/src/main/java/software/amazon/awssdk/services/sqs/internal/MessageMD5ChecksumInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sqs.internal; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; 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.services.sqs.model.Message; import software.amazon.awssdk.services.sqs.model.MessageAttributeValue; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry; import software.amazon.awssdk.services.sqs.model.SendMessageBatchResponse; import software.amazon.awssdk.services.sqs.model.SendMessageBatchResultEntry; import software.amazon.awssdk.services.sqs.model.SendMessageRequest; import software.amazon.awssdk.services.sqs.model.SendMessageResponse; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Md5Utils; /** * SQS operations on sending and receiving messages will return the MD5 digest of the message body. * This custom request handler will verify that the message is correctly received by SQS, by * comparing the returned MD5 with the calculation according to the original request. */ @SdkInternalApi public final class MessageMD5ChecksumInterceptor implements ExecutionInterceptor { private static final int INTEGER_SIZE_IN_BYTES = 4; private static final byte STRING_TYPE_FIELD_INDEX = 1; private static final byte BINARY_TYPE_FIELD_INDEX = 2; private static final byte STRING_LIST_TYPE_FIELD_INDEX = 3; private static final byte BINARY_LIST_TYPE_FIELD_INDEX = 4; /* * Constant strings for composing error message. */ private static final String MD5_MISMATCH_ERROR_MESSAGE = "MD5 returned by SQS does not match the calculation on the original request. " + "(MD5 calculated by the %s: \"%s\", MD5 checksum returned: \"%s\")"; private static final String MD5_MISMATCH_ERROR_MESSAGE_WITH_ID = "MD5 returned by SQS does not match the calculation on the original request. " + "(Message ID: %s, MD5 calculated by the %s: \"%s\", MD5 checksum returned: \"%s\")"; private static final String MESSAGE_BODY = "message body"; private static final String MESSAGE_ATTRIBUTES = "message attributes"; private static final Logger log = Logger.loggerFor(MessageMD5ChecksumInterceptor.class); @Override public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) { SdkResponse response = context.response(); SdkRequest originalRequest = context.request(); if (response != null) { if (originalRequest instanceof SendMessageRequest) { SendMessageRequest sendMessageRequest = (SendMessageRequest) originalRequest; SendMessageResponse sendMessageResult = (SendMessageResponse) response; sendMessageOperationMd5Check(sendMessageRequest, sendMessageResult); } else if (originalRequest instanceof ReceiveMessageRequest) { ReceiveMessageResponse receiveMessageResult = (ReceiveMessageResponse) response; receiveMessageResultMd5Check(receiveMessageResult); } else if (originalRequest instanceof SendMessageBatchRequest) { SendMessageBatchRequest sendMessageBatchRequest = (SendMessageBatchRequest) originalRequest; SendMessageBatchResponse sendMessageBatchResult = (SendMessageBatchResponse) response; sendMessageBatchOperationMd5Check(sendMessageBatchRequest, sendMessageBatchResult); } } } /** * Throw an exception if the MD5 checksums returned in the SendMessageResponse do not match the * client-side calculation based on the original message in the SendMessageRequest. */ private static void sendMessageOperationMd5Check(SendMessageRequest sendMessageRequest, SendMessageResponse sendMessageResult) { String messageBodySent = sendMessageRequest.messageBody(); String bodyMd5Returned = sendMessageResult.md5OfMessageBody(); String clientSideBodyMd5 = calculateMessageBodyMd5(messageBodySent); if (!clientSideBodyMd5.equals(bodyMd5Returned)) { throw SdkClientException.builder() .message(String.format(MD5_MISMATCH_ERROR_MESSAGE, MESSAGE_BODY, clientSideBodyMd5, bodyMd5Returned)) .build(); } Map<String, MessageAttributeValue> messageAttrSent = sendMessageRequest.messageAttributes(); if (messageAttrSent != null && !messageAttrSent.isEmpty()) { String clientSideAttrMd5 = calculateMessageAttributesMd5(messageAttrSent); String attrMd5Returned = sendMessageResult.md5OfMessageAttributes(); if (!clientSideAttrMd5.equals(attrMd5Returned)) { throw SdkClientException.builder() .message(String.format(MD5_MISMATCH_ERROR_MESSAGE, MESSAGE_ATTRIBUTES, clientSideAttrMd5, attrMd5Returned)) .build(); } } } /** * Throw an exception if the MD5 checksums included in the ReceiveMessageResponse do not match the * client-side calculation on the received messages. */ private static void receiveMessageResultMd5Check(ReceiveMessageResponse receiveMessageResult) { if (receiveMessageResult.messages() != null) { for (Message messageReceived : receiveMessageResult.messages()) { String messageBody = messageReceived.body(); String bodyMd5Returned = messageReceived.md5OfBody(); String clientSideBodyMd5 = calculateMessageBodyMd5(messageBody); if (!clientSideBodyMd5.equals(bodyMd5Returned)) { throw SdkClientException.builder() .message(String.format(MD5_MISMATCH_ERROR_MESSAGE, MESSAGE_BODY, clientSideBodyMd5, bodyMd5Returned)) .build(); } Map<String, MessageAttributeValue> messageAttr = messageReceived.messageAttributes(); if (messageAttr != null && !messageAttr.isEmpty()) { String attrMd5Returned = messageReceived.md5OfMessageAttributes(); String clientSideAttrMd5 = calculateMessageAttributesMd5(messageAttr); if (!clientSideAttrMd5.equals(attrMd5Returned)) { throw SdkClientException.builder() .message(String.format(MD5_MISMATCH_ERROR_MESSAGE, MESSAGE_ATTRIBUTES, clientSideAttrMd5, attrMd5Returned)) .build(); } } } } } /** * Throw an exception if the MD5 checksums returned in the SendMessageBatchResponse do not match * the client-side calculation based on the original messages in the SendMessageBatchRequest. */ private static void sendMessageBatchOperationMd5Check(SendMessageBatchRequest sendMessageBatchRequest, SendMessageBatchResponse sendMessageBatchResult) { Map<String, SendMessageBatchRequestEntry> idToRequestEntryMap = new HashMap<>(); if (sendMessageBatchRequest.entries() != null) { for (SendMessageBatchRequestEntry entry : sendMessageBatchRequest.entries()) { idToRequestEntryMap.put(entry.id(), entry); } } if (sendMessageBatchResult.successful() != null) { for (SendMessageBatchResultEntry entry : sendMessageBatchResult.successful()) { String messageBody = idToRequestEntryMap.get(entry.id()).messageBody(); String bodyMd5Returned = entry.md5OfMessageBody(); String clientSideBodyMd5 = calculateMessageBodyMd5(messageBody); if (!clientSideBodyMd5.equals(bodyMd5Returned)) { throw SdkClientException.builder() .message(String.format(MD5_MISMATCH_ERROR_MESSAGE_WITH_ID, MESSAGE_BODY, entry.id(), clientSideBodyMd5, bodyMd5Returned)) .build(); } Map<String, MessageAttributeValue> messageAttr = idToRequestEntryMap.get(entry.id()) .messageAttributes(); if (messageAttr != null && !messageAttr.isEmpty()) { String attrMd5Returned = entry.md5OfMessageAttributes(); String clientSideAttrMd5 = calculateMessageAttributesMd5(messageAttr); if (!clientSideAttrMd5.equals(attrMd5Returned)) { throw SdkClientException.builder() .message(String.format(MD5_MISMATCH_ERROR_MESSAGE_WITH_ID, MESSAGE_ATTRIBUTES, entry.id(), clientSideAttrMd5, attrMd5Returned)) .build(); } } } } } /** * Returns the hex-encoded MD5 hash String of the given message body. */ private static String calculateMessageBodyMd5(String messageBody) { log.debug(() -> "Message body: " + messageBody); byte[] expectedMd5; try { expectedMd5 = Md5Utils.computeMD5Hash(messageBody.getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw SdkClientException.builder() .message("Unable to calculate the MD5 hash of the message body. " + e.getMessage()) .cause(e) .build(); } String expectedMd5Hex = BinaryUtils.toHex(expectedMd5); log.debug(() -> "Expected MD5 of message body: " + expectedMd5Hex); return expectedMd5Hex; } /** * Returns the hex-encoded MD5 hash String of the given message attributes. */ private static String calculateMessageAttributesMd5(final Map<String, MessageAttributeValue> messageAttributes) { log.debug(() -> "Message attributes: " + messageAttributes); List<String> sortedAttributeNames = new ArrayList<>(messageAttributes.keySet()); Collections.sort(sortedAttributeNames); MessageDigest md5Digest; try { md5Digest = MessageDigest.getInstance("MD5"); for (String attrName : sortedAttributeNames) { MessageAttributeValue attrValue = messageAttributes.get(attrName); // Encoded Name updateLengthAndBytes(md5Digest, attrName); // Encoded Type updateLengthAndBytes(md5Digest, attrValue.dataType()); // Encoded Value if (attrValue.stringValue() != null) { md5Digest.update(STRING_TYPE_FIELD_INDEX); updateLengthAndBytes(md5Digest, attrValue.stringValue()); } else if (attrValue.binaryValue() != null) { md5Digest.update(BINARY_TYPE_FIELD_INDEX); updateLengthAndBytes(md5Digest, attrValue.binaryValue().asByteBuffer()); } else if (attrValue.stringListValues() != null && attrValue.stringListValues().size() > 0) { md5Digest.update(STRING_LIST_TYPE_FIELD_INDEX); for (String strListMember : attrValue.stringListValues()) { updateLengthAndBytes(md5Digest, strListMember); } } else if (attrValue.binaryListValues() != null && attrValue.binaryListValues().size() > 0) { md5Digest.update(BINARY_LIST_TYPE_FIELD_INDEX); for (SdkBytes byteListMember : attrValue.binaryListValues()) { updateLengthAndBytes(md5Digest, byteListMember.asByteBuffer()); } } } } catch (Exception e) { throw SdkClientException.builder() .message("Unable to calculate the MD5 hash of the message attributes. " + e.getMessage()) .cause(e) .build(); } String expectedMd5Hex = BinaryUtils.toHex(md5Digest.digest()); log.debug(() -> "Expected MD5 of message attributes: " + expectedMd5Hex); return expectedMd5Hex; } /** * Update the digest using a sequence of bytes that consists of the length (in 4 bytes) of the * input String and the actual utf8-encoded byte values. */ private static void updateLengthAndBytes(MessageDigest digest, String str) { byte[] utf8Encoded = str.getBytes(StandardCharsets.UTF_8); ByteBuffer lengthBytes = ByteBuffer.allocate(INTEGER_SIZE_IN_BYTES).putInt(utf8Encoded.length); digest.update(lengthBytes.array()); digest.update(utf8Encoded); } /** * Update the digest using a sequence of bytes that consists of the length (in 4 bytes) of the * input ByteBuffer and all the bytes it contains. */ private static void updateLengthAndBytes(MessageDigest digest, ByteBuffer binaryValue) { ByteBuffer readOnlyBuffer = binaryValue.asReadOnlyBuffer(); int size = readOnlyBuffer.remaining(); ByteBuffer lengthBytes = ByteBuffer.allocate(INTEGER_SIZE_IN_BYTES).putInt(size); digest.update(lengthBytes.array()); digest.update(readOnlyBuffer); } }
4,776
0
Create_ds/aws-sdk-java-v2/services/iot/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/iot/src/it/java/software/amazon/awssdk/services/iot/IotControlPlaneIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.iot; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iot.model.AttributePayload; import software.amazon.awssdk.services.iot.model.CertificateStatus; import software.amazon.awssdk.services.iot.model.CreateCertificateFromCsrRequest; import software.amazon.awssdk.services.iot.model.CreateKeysAndCertificateRequest; import software.amazon.awssdk.services.iot.model.CreateKeysAndCertificateResponse; import software.amazon.awssdk.services.iot.model.CreatePolicyRequest; import software.amazon.awssdk.services.iot.model.CreatePolicyResponse; import software.amazon.awssdk.services.iot.model.CreateThingRequest; import software.amazon.awssdk.services.iot.model.CreateThingResponse; import software.amazon.awssdk.services.iot.model.DeleteCertificateRequest; import software.amazon.awssdk.services.iot.model.DeletePolicyRequest; import software.amazon.awssdk.services.iot.model.DeleteThingRequest; import software.amazon.awssdk.services.iot.model.DescribeThingRequest; import software.amazon.awssdk.services.iot.model.DescribeThingResponse; import software.amazon.awssdk.services.iot.model.GetPolicyVersionRequest; import software.amazon.awssdk.services.iot.model.GetPolicyVersionResponse; import software.amazon.awssdk.services.iot.model.InvalidRequestException; import software.amazon.awssdk.services.iot.model.ListThingsRequest; import software.amazon.awssdk.services.iot.model.ListThingsResponse; import software.amazon.awssdk.services.iot.model.UpdateCertificateRequest; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Integration tests for Iot control plane APIs. */ public class IotControlPlaneIntegrationTest extends AwsTestBase { private static final String THING_NAME = "java-sdk-thing-" + System.currentTimeMillis(); private static final Map<String, String> THING_ATTRIBUTES = new HashMap<String, String>(); private static final String ATTRIBUTE_NAME = "foo"; private static final String ATTRIBUTE_VALUE = "bar"; private static final String POLICY_NAME = "java-sdk-iot-policy-" + System.currentTimeMillis(); private static final String POLICY_DOC = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + " {\n" + " \"Sid\": \"Stmt1443818583140\",\n" + " \"Action\": \"iot:*\",\n" + " \"Effect\": \"Deny\",\n" + " \"Resource\": \"*\"\n" + " }\n" + " ]\n" + "}"; private static IotClient client; private static String certificateId = null; @BeforeClass public static void setup() throws IOException { setUpCredentials(); client = IotClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).region(Region.US_WEST_2).build(); THING_ATTRIBUTES.put(ATTRIBUTE_NAME, ATTRIBUTE_VALUE); } @AfterClass public static void tearDown() throws IOException { if (client != null) { client.deleteThing(DeleteThingRequest.builder().thingName(THING_NAME).build()); client.deletePolicy(DeletePolicyRequest.builder().policyName(POLICY_NAME).build()); if (certificateId != null) { client.deleteCertificate(DeleteCertificateRequest.builder().certificateId(certificateId).build()); } } } @Test public void describe_and_list_thing_returns_created_thing() { final CreateThingRequest createReq = CreateThingRequest.builder() .thingName(THING_NAME) .attributePayload(AttributePayload.builder().attributes(THING_ATTRIBUTES).build()) .build(); CreateThingResponse result = client.createThing(createReq); Assert.assertNotNull(result.thingArn()); Assert.assertEquals(THING_NAME, result.thingName()); final DescribeThingRequest descRequest = DescribeThingRequest.builder().thingName(THING_NAME).build(); DescribeThingResponse descResult = client.describeThing(descRequest); Map<String, String> actualAttributes = descResult.attributes(); Assert.assertEquals(THING_ATTRIBUTES.size(), actualAttributes.size()); Assert.assertTrue(actualAttributes.containsKey(ATTRIBUTE_NAME)); Assert.assertEquals(THING_ATTRIBUTES.get(ATTRIBUTE_NAME), actualAttributes.get(ATTRIBUTE_NAME)); ListThingsResponse listResult = client.listThings(ListThingsRequest.builder().build()); Assert.assertFalse(listResult.things().isEmpty()); } @Test public void get_policy_returns_created_policy() { final CreatePolicyRequest createReq = CreatePolicyRequest.builder().policyName(POLICY_NAME).policyDocument(POLICY_DOC).build(); CreatePolicyResponse createResult = client.createPolicy(createReq); Assert.assertNotNull(createResult.policyArn()); Assert.assertNotNull(createResult.policyVersionId()); final GetPolicyVersionRequest request = GetPolicyVersionRequest.builder() .policyName(POLICY_NAME) .policyVersionId(createResult.policyVersionId()) .build(); GetPolicyVersionResponse result = client.getPolicyVersion(request); Assert.assertEquals(createResult.policyArn(), result.policyArn()); Assert.assertEquals(createResult.policyVersionId(), result.policyVersionId()); } @Test public void createCertificate_Returns_success() { final CreateKeysAndCertificateRequest createReq = CreateKeysAndCertificateRequest.builder().setAsActive(true).build(); CreateKeysAndCertificateResponse createResult = client.createKeysAndCertificate(createReq); Assert.assertNotNull(createResult.certificateArn()); Assert.assertNotNull(createResult.certificateId()); Assert.assertNotNull(createResult.certificatePem()); Assert.assertNotNull(createResult.keyPair()); certificateId = createResult.certificateId(); client.updateCertificate(UpdateCertificateRequest.builder() .certificateId(certificateId) .newStatus(CertificateStatus.REVOKED) .build()); } @Test(expected = InvalidRequestException.class) public void create_certificate_from_invalid_csr_throws_exception() { client.createCertificateFromCsr(CreateCertificateFromCsrRequest.builder() .certificateSigningRequest("invalid-csr-string") .build()); } }
4,777
0
Create_ds/aws-sdk-java-v2/services/gamelift/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/gamelift/src/it/java/software/amazon/awssdk/services/gamelift/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.gamelift; import java.io.IOException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.gamelift.model.Alias; import software.amazon.awssdk.services.gamelift.model.CreateAliasRequest; import software.amazon.awssdk.services.gamelift.model.CreateAliasResponse; import software.amazon.awssdk.services.gamelift.model.DeleteAliasRequest; import software.amazon.awssdk.services.gamelift.model.DescribeAliasRequest; import software.amazon.awssdk.services.gamelift.model.DescribeAliasResponse; import software.amazon.awssdk.services.gamelift.model.RoutingStrategy; import software.amazon.awssdk.services.gamelift.model.RoutingStrategyType; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class ServiceIntegrationTest extends AwsIntegrationTestBase { private static GameLiftClient gameLift; private static String aliasId = null; @BeforeClass public static void setUp() throws IOException { gameLift = GameLiftClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } @AfterClass public static void cleanUp() { if (aliasId != null) { gameLift.deleteAlias(DeleteAliasRequest.builder().aliasId(aliasId).build()); } } @Test public void aliasOperations() { String aliasName = "alias-foo"; String fleetId = "fleet-foo"; CreateAliasResponse createAliasResult = gameLift .createAlias(CreateAliasRequest.builder() .name(aliasName) .routingStrategy(RoutingStrategy.builder() .type(RoutingStrategyType.SIMPLE) .fleetId(fleetId).build()).build()); Alias createdAlias = createAliasResult.alias(); aliasId = createdAlias.aliasId(); RoutingStrategy strategy = createdAlias.routingStrategy(); Assert.assertNotNull(createAliasResult); Assert.assertNotNull(createAliasResult.alias()); Assert.assertEquals(createdAlias.name(), aliasName); Assert.assertEquals(strategy.type(), RoutingStrategyType.SIMPLE); Assert.assertEquals(strategy.fleetId(), fleetId); DescribeAliasResponse describeAliasResult = gameLift .describeAlias(DescribeAliasRequest.builder().aliasId(aliasId).build()); Assert.assertNotNull(describeAliasResult); Alias describedAlias = describeAliasResult.alias(); Assert.assertEquals(createdAlias, describedAlias); } }
4,778
0
Create_ds/aws-sdk-java-v2/services/cloudtrail/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudtrail/src/it/java/software/amazon/awssdk/services/cloudtrail/CloudTrailIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudtrail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName; import java.io.IOException; import java.util.Iterator; import org.apache.commons.io.IOUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.cloudtrail.model.CreateTrailRequest; import software.amazon.awssdk.services.cloudtrail.model.CreateTrailResponse; import software.amazon.awssdk.services.cloudtrail.model.DeleteTrailRequest; import software.amazon.awssdk.services.cloudtrail.model.DescribeTrailsRequest; import software.amazon.awssdk.services.cloudtrail.model.DescribeTrailsResponse; import software.amazon.awssdk.services.cloudtrail.model.StartLoggingRequest; import software.amazon.awssdk.services.cloudtrail.model.StopLoggingRequest; import software.amazon.awssdk.services.cloudtrail.model.Trail; import software.amazon.awssdk.services.cloudtrail.model.UpdateTrailRequest; import software.amazon.awssdk.services.cloudtrail.model.UpdateTrailResponse; import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest; import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse; import software.amazon.awssdk.services.s3.model.ListObjectsRequest; import software.amazon.awssdk.services.s3.model.ListObjectsResponse; import software.amazon.awssdk.services.s3.model.ObjectVersion; import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest; import software.amazon.awssdk.services.s3.model.S3Object; public class CloudTrailIntegrationTest extends IntegrationTestBase { private static final String BUCKET_NAME = temporaryBucketName("aws-java-cloudtrail-integ"); private static final String TRAIL_NAME = "aws-java-trail-" + System.currentTimeMillis(); /** * Path to the sample policy for this test */ private static final String POLICY_FILE = "/software/amazon/awssdk/services/cloudtrail/samplePolicy.json"; @BeforeClass public static void setUp() throws IOException { IntegrationTestBase.setUp(); s3.createBucket(CreateBucketRequest.builder() .bucket(BUCKET_NAME) .createBucketConfiguration( CreateBucketConfiguration.builder() .locationConstraint(region.id()) .build()) .build()); } @AfterClass public static void tearDown() { deleteBucketAndAllContents(BUCKET_NAME); try { for (Trail trail : cloudTrail.describeTrails(DescribeTrailsRequest.builder().build()).trailList()) { cloudTrail.deleteTrail(DeleteTrailRequest.builder().name(trail.name()).build()); } } catch (Exception e) { // Expected. } } public static void deleteBucketAndAllContents(String bucketName) { System.out.println("Deleting S3 bucket: " + bucketName); ListObjectsResponse response = s3.listObjects(ListObjectsRequest.builder().bucket(bucketName).build()); while (true) { if (response.contents() == null) { break; } for (Iterator<?> iterator = response.contents().iterator(); iterator .hasNext(); ) { S3Object objectSummary = (S3Object) iterator.next(); s3.deleteObject(DeleteObjectRequest.builder().bucket(bucketName).key(objectSummary.key()).build()); } if (response.isTruncated()) { response = s3.listObjects(ListObjectsRequest.builder().marker(response.nextMarker()).build()); } else { break; } } ListObjectVersionsResponse versionsResponse = s3 .listObjectVersions(ListObjectVersionsRequest.builder().bucket(bucketName).build()); if (versionsResponse.versions() != null) { for (ObjectVersion s : versionsResponse.versions()) { s3.deleteObject(DeleteObjectRequest.builder() .bucket(bucketName) .key(s.key()) .versionId(s.versionId()) .build()); } } s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build()); } @Test public void testServiceOperations() throws IOException, InterruptedException { String policyText = IOUtils.toString(getClass().getResourceAsStream(POLICY_FILE)); policyText = policyText.replace("@BUCKET_NAME@", BUCKET_NAME); System.out.println(policyText); s3.putBucketPolicy(PutBucketPolicyRequest.builder().bucket(BUCKET_NAME).policy(policyText).build()); Thread.sleep(1000 * 5); // create trail CreateTrailResponse createTrailResult = cloudTrail.createTrail(CreateTrailRequest.builder() .name(TRAIL_NAME) .s3BucketName(BUCKET_NAME) .includeGlobalServiceEvents(true) .build()); assertEquals(TRAIL_NAME, createTrailResult.name()); assertEquals(BUCKET_NAME, createTrailResult.s3BucketName()); assertNull(createTrailResult.s3KeyPrefix()); assertTrue(createTrailResult.includeGlobalServiceEvents()); // describe trail DescribeTrailsResponse describeTrails = cloudTrail.describeTrails(DescribeTrailsRequest.builder().build()); assertTrue(describeTrails.trailList().size() > 0); describeTrails = cloudTrail .describeTrails(DescribeTrailsRequest.builder().trailNameList(TRAIL_NAME).build()); assertTrue(describeTrails.trailList().size() == 1); Trail trail = describeTrails.trailList().get(0); assertEquals(TRAIL_NAME, trail.name()); assertEquals(BUCKET_NAME, trail.s3BucketName()); assertNull(trail.s3KeyPrefix()); assertTrue(trail.includeGlobalServiceEvents()); // update the trail UpdateTrailResponse updateTrailResult = cloudTrail.updateTrail(UpdateTrailRequest.builder() .name(TRAIL_NAME) .s3BucketName(BUCKET_NAME) .includeGlobalServiceEvents(false) .s3KeyPrefix("123") .build()); assertEquals(TRAIL_NAME, updateTrailResult.name()); assertEquals(BUCKET_NAME, updateTrailResult.s3BucketName()); assertEquals("123", updateTrailResult.s3KeyPrefix()); assertFalse(updateTrailResult.includeGlobalServiceEvents()); // start and stop the logging cloudTrail.startLogging(StartLoggingRequest.builder().name(TRAIL_NAME).build()); cloudTrail.stopLogging(StopLoggingRequest.builder().name(TRAIL_NAME).build()); // delete the trail cloudTrail.deleteTrail(DeleteTrailRequest.builder().name(TRAIL_NAME).build()); // try to get the deleted trail DescribeTrailsResponse describeTrailResult = cloudTrail .describeTrails(DescribeTrailsRequest.builder().trailNameList(TRAIL_NAME).build()); assertEquals(0, describeTrailResult.trailList().size()); } }
4,779
0
Create_ds/aws-sdk-java-v2/services/cloudtrail/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudtrail/src/it/java/software/amazon/awssdk/services/cloudtrail/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.cloudtrail; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class IntegrationTestBase extends AwsIntegrationTestBase { protected static CloudTrailClient cloudTrail; protected static S3Client s3; protected static Region region = Region.US_WEST_2; @BeforeClass public static void setUp() throws IOException { System.setProperty("software.amazon.awssdk.sdk.disableCertChecking", "true"); cloudTrail = CloudTrailClient.builder().credentialsProvider(StaticCredentialsProvider.create(getCredentials())).build(); s3 = S3Client.builder() .credentialsProvider(StaticCredentialsProvider.create(getCredentials())) .region(region) .build(); } }
4,780
0
Create_ds/aws-sdk-java-v2/services/iam/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/iam/src/it/java/software/amazon/awssdk/services/iam/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.iam; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; public class ServiceIntegrationTest extends AwsTestBase { protected IamClient iam; @Before public void setUp() { iam = IamClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(c -> c.retryPolicy(RetryPolicy.builder().numRetries(50).build())) .region(Region.AWS_GLOBAL) .build(); } @Test public void smokeTest() { assertThat(iam.listUsers().users()).isNotNull(); } }
4,781
0
Create_ds/aws-sdk-java-v2/services/sso/src/test/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/test/java/software/amazon/awssdk/services/sso/auth/SsoCredentialsProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.auth; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.Duration; import java.time.Instant; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.services.sso.SsoClient; import software.amazon.awssdk.services.sso.model.GetRoleCredentialsRequest; import software.amazon.awssdk.services.sso.model.GetRoleCredentialsResponse; import software.amazon.awssdk.services.sso.model.RoleCredentials; /** * Validates the functionality of {@link SsoCredentialsProvider}. */ public class SsoCredentialsProviderTest { private SsoClient ssoClient; @Test public void cachingDoesNotApplyToExpiredSession() { callClientWithCredentialsProvider(Instant.now().minus(Duration.ofSeconds(5)), 2, false); callClient(verify(ssoClient, times(2)), Mockito.any()); } @Test public void cachingDoesNotApplyToExpiredSession_OverridePrefetchAndStaleTimes() { callClientWithCredentialsProvider(Instant.now().minus(Duration.ofSeconds(5)), 2, true); callClient(verify(ssoClient, times(2)), Mockito.any()); } @Test public void cachingAppliesToNonExpiredSession() { callClientWithCredentialsProvider(Instant.now().plus(Duration.ofHours(5)), 2, false); callClient(verify(ssoClient, times(1)), Mockito.any()); } @Test public void cachingAppliesToNonExpiredSession_OverridePrefetchAndStaleTimes() { callClientWithCredentialsProvider(Instant.now().plus(Duration.ofHours(5)), 2, true); callClient(verify(ssoClient, 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(ssoClient).getInvocations().size() < 2 && endCheckTime.isAfter(Instant.now())) { Thread.sleep(100); } callClient(verify(ssoClient, 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(ssoClient).getInvocations().size() < 2 && endCheckTime.isAfter(Instant.now())) { Thread.sleep(100); } callClient(verify(ssoClient, times(2)), Mockito.any()); } private GetRoleCredentialsRequestSupplier getRequestSupplier() { return new GetRoleCredentialsRequestSupplier(GetRoleCredentialsRequest.builder().build(), "cachedToken"); } private GetRoleCredentialsResponse getResponse(RoleCredentials roleCredentials) { return GetRoleCredentialsResponse.builder().roleCredentials(roleCredentials).build(); } private GetRoleCredentialsResponse callClient(SsoClient ssoClient, GetRoleCredentialsRequest request) { return ssoClient.getRoleCredentials(request); } private void callClientWithCredentialsProvider(Instant credentialsExpirationDate, int numTimesInvokeCredentialsProvider, boolean overrideStaleAndPrefetchTimes) { ssoClient = mock(SsoClient.class); RoleCredentials credentials = RoleCredentials.builder().accessKeyId("a").secretAccessKey("b").sessionToken("c") .expiration(credentialsExpirationDate.toEpochMilli()).build(); Supplier<GetRoleCredentialsRequest> supplier = getRequestSupplier(); GetRoleCredentialsResponse response = getResponse(credentials); when(ssoClient.getRoleCredentials(supplier.get())).thenReturn(response); SsoCredentialsProvider.Builder ssoCredentialsProviderBuilder = SsoCredentialsProvider.builder().refreshRequest(supplier); if(overrideStaleAndPrefetchTimes) { ssoCredentialsProviderBuilder.staleTime(Duration.ofMinutes(2)); ssoCredentialsProviderBuilder.prefetchTime(Duration.ofMinutes(4)); } try (SsoCredentialsProvider credentialsProvider = ssoCredentialsProviderBuilder.ssoClient(ssoClient).build()) { if(overrideStaleAndPrefetchTimes) { assertThat(credentialsProvider.staleTime()).as("stale time").isEqualTo(Duration.ofMinutes(2)); assertThat(credentialsProvider.prefetchTime()).as("prefetch time").isEqualTo(Duration.ofMinutes(4)); } else { 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 actualCredentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials(); assertThat(actualCredentials.accessKeyId()).isEqualTo("a"); assertThat(actualCredentials.secretAccessKey()).isEqualTo("b"); assertThat(actualCredentials.sessionToken()).isEqualTo("c"); } } } private static final class GetRoleCredentialsRequestSupplier implements Supplier { private final GetRoleCredentialsRequest request; private final String cachedToken; GetRoleCredentialsRequestSupplier(GetRoleCredentialsRequest request, String cachedToken) { this.request = request; this.cachedToken = cachedToken; } @Override public Object get() { return request.toBuilder().accessToken(cachedToken).build(); } } }
4,782
0
Create_ds/aws-sdk-java-v2/services/sso/src/test/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/test/java/software/amazon/awssdk/services/sso/auth/SsoProfileTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.auth; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; 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.StringInputStream; /** * Validate the completeness of sso profile properties consumed by the {@link ProfileCredentialsUtils}. */ public class SsoProfileTest { @Test public void createSsoCredentialsProvider_SsoAccountIdMissing_throwException() { String profileContent = "[profile foo]\n" + "sso_region=us-east-1\n" + "sso_role_name=SampleRole\n" + "sso_start_url=https://d-abc123.awsapps.com/start-beta\n"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); assertThat(profiles.profile("foo")).hasValueSatisfying(profile -> { assertThatThrownBy(() -> new ProfileCredentialsUtils(profiles, profile, profiles::profile).credentialsProvider()) .hasMessageContaining("Profile property 'sso_account_id' was not configured"); }); } @Test public void createSsoCredentialsProvider_SsoRegionMissing_throwException() { String profileContent = "[profile foo]\n" + "sso_account_id=012345678901\n" + "sso_role_name=SampleRole\n" + "sso_start_url=https://d-abc123.awsapps.com/start-beta\n"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); assertThat(profiles.profile("foo")).hasValueSatisfying(profile -> { assertThatThrownBy(() -> new ProfileCredentialsUtils(profiles, profile, profiles::profile).credentialsProvider()) .hasMessageContaining("Profile property 'sso_region' was not configured"); }); } @Test public void createSsoCredentialsProvider_SsoRoleNameMissing_throwException() { String profileContent = "[profile foo]\n" + "sso_account_id=012345678901\n" + "sso_region=us-east-1\n" + "sso_start_url=https://d-abc123.awsapps.com/start-beta\n"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); assertThat(profiles.profile("foo")).hasValueSatisfying(profile -> { assertThatThrownBy(() -> new ProfileCredentialsUtils(profiles, profile, profiles::profile).credentialsProvider()) .hasMessageContaining("Profile property 'sso_role_name' was not configured"); }); } @Test public void createSsoCredentialsProvider_SsoStartUrlMissing_throwException() { String profileContent = "[profile foo]\n" + "sso_account_id=012345678901\n" + "sso_region=us-east-1\n" + "sso_role_name=SampleRole\n"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); assertThat(profiles.profile("foo")).hasValueSatisfying(profile -> { assertThatThrownBy(() -> new ProfileCredentialsUtils(profiles, profile, profiles::profile).credentialsProvider()) .hasMessageContaining("Profile property 'sso_start_url' was not configured"); }); } }
4,783
0
Create_ds/aws-sdk-java-v2/services/sso/src/test/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/test/java/software/amazon/awssdk/services/sso/auth/SsoProfileCredentialsProviderFactoryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.auth; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableList; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.ProfileProviderCredentialsContext; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.services.sso.internal.SsoAccessToken; import software.amazon.awssdk.services.sso.internal.SsoAccessTokenProvider; import software.amazon.awssdk.utils.StringInputStream; /** * Validate the code path of creating the {@link SsoCredentialsProvider} with {@link SsoProfileCredentialsProviderFactory}. */ @ExtendWith(MockitoExtension.class) public class SsoProfileCredentialsProviderFactoryTest { @Mock SdkTokenProvider sdkTokenProvider; @Test public void createSsoCredentialsProviderWithFactorySucceed() throws IOException { String startUrl = "https//d-abc123.awsapps.com/start"; String generatedTokenFileName = "6a888bdb653a4ba345dd68f21b896ec2e218c6f4.json"; ProfileFile profileFile = configFile("[profile foo]\n" + "sso_account_id=accountId\n" + "sso_region=region\n" + "sso_role_name=roleName\n" + "sso_start_url=https//d-abc123.awsapps.com/start"); String tokenFile = "{\n" + "\"accessToken\": \"base64string\",\n" + "\"expiresAt\": \"2090-01-01T00:00:00Z\",\n" + "\"region\": \"us-west-2\", \n" + "\"startUrl\": \""+ startUrl +"\"\n" + "}"; Path cachedTokenFilePath = prepareTestCachedTokenFile(tokenFile, generatedTokenFileName); SsoAccessTokenProvider tokenProvider = new SsoAccessTokenProvider( cachedTokenFilePath); SsoProfileCredentialsProviderFactory factory = new SsoProfileCredentialsProviderFactory(); assertThat(factory.create(profileFile.profile("foo").get(), profileFile, tokenProvider)).isInstanceOf(AwsCredentialsProvider.class); } private Path prepareTestCachedTokenFile(String tokenFileContent, String generatedTokenFileName) throws IOException { FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); Path fileDirectory = fs.getPath("./foo"); Files.createDirectory(fileDirectory); Path cachedTokenFilePath = fileDirectory.resolve(generatedTokenFileName); Files.write(cachedTokenFilePath, ImmutableList.of(tokenFileContent), StandardCharsets.UTF_8); return cachedTokenFilePath; } private static ProfileFile configFile(String configFile) { return ProfileFile.builder() .content(new StringInputStream(configFile)) .type(ProfileFile.Type.CONFIGURATION) .build(); } @ParameterizedTest @MethodSource("ssoErrorValues") void validateSsoFactoryErrorWithIncorrectProfiles(ProfileFile profiles, String expectedValue) { assertThat(profiles.profile("test")).hasValueSatisfying(profile -> { SsoProfileCredentialsProviderFactory factory = new SsoProfileCredentialsProviderFactory(); assertThatThrownBy(() -> factory.create(ProfileProviderCredentialsContext.builder() .profileFile(profiles) .profile(profile) .build())).hasMessageContaining(expectedValue); }); } private static Stream<Arguments> ssoErrorValues() { // Session title is missing return Stream.of( Arguments.of(configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_role_name=roleName\n" + "sso_session=foo\n" + "[sso-session bar]\n" + "sso_start_url=https//d-abc123.awsapps.com/start\n" + "sso_region=region") , "Sso-session section not found with sso-session title foo."), // No sso_region in sso_session Arguments.of(configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_role_name=roleName\n" + "sso_session=foo\n" + "[sso-session foo]\n" + "sso_start_url=https//d-abc123.awsapps.com/start") , "'sso_region' must be set to use role-based credential loading in the 'foo' profile."), // sso_start_url mismatch in sso-session and profile Arguments.of(configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_role_name=roleName\n" + "sso_start_url=https//d-abc123.awsapps.com/startTwo\n" + "sso_session=foo\n" + "[sso-session foo]\n" + "sso_region=regionTwo\n" + "sso_start_url=https//d-abc123.awsapps.com/startOne") , "Profile test and Sso-session foo has different sso_start_url."), // sso_region mismatch in sso-session and profile Arguments.of(configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_role_name=roleName\n" + "sso_region=regionOne\n" + "sso_session=foo\n" + "[sso-session foo]\n" + "sso_region=regionTwo\n" + "sso_start_url=https//d-abc123.awsapps.com/start") , "Profile test and Sso-session foo has different sso_region.") ); } @Test public void tokenResolvedFromTokenProvider(@Mock SdkTokenProvider sdkTokenProvider){ ProfileFile profileFile = configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_role_name=roleName\n" + "sso_region=region\n" + "sso_session=foo\n" + "[sso-session foo]\n" + "sso_region=region\n" + "sso_start_url=https//d-abc123.awsapps.com/start"); SsoProfileCredentialsProviderFactory factory = new SsoProfileCredentialsProviderFactory(); when(sdkTokenProvider.resolveToken()).thenReturn(SsoAccessToken.builder().accessToken("sample").expiresAt(Instant.now()).build()); AwsCredentialsProvider credentialsProvider = factory.create(profileFile.profile("test").get(), profileFile, sdkTokenProvider); try { credentialsProvider.resolveCredentials(); } catch (Exception e) { // sso client created internally which cannot be mocked. } Mockito.verify(sdkTokenProvider, times(1)).resolveToken(); } }
4,784
0
Create_ds/aws-sdk-java-v2/services/sso/src/test/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/test/java/software/amazon/awssdk/services/sso/internal/SsoTokenFileUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.internal; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.services.sso.internal.SsoTokenFileUtils.generateCachedTokenPath; import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory; import org.junit.jupiter.api.Test; public class SsoTokenFileUtilsTest { @Test public void generateTheCorrectPathTest() { String startUrl = "https//d-abc123.awsapps.com/start"; String directory = "~/.aws/sso/cache"; assertThat(generateCachedTokenPath(startUrl, directory).toString()) .isEqualTo(userHomeDirectory() + "/.aws/sso/cache/6a888bdb653a4ba345dd68f21b896ec2e218c6f4.json"); } }
4,785
0
Create_ds/aws-sdk-java-v2/services/sso/src/test/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/test/java/software/amazon/awssdk/services/sso/internal/SsoAccessTokenProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.common.collect.ImmutableList; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import org.junit.jupiter.api.Test; /** * Check if the behavior of {@link SsoAccessTokenProvider} is correct while consuming different formats of cached token * file. */ public class SsoAccessTokenProviderTest { private static final String START_URL = "https//d-abc123.awsapps.com/start"; private static final String GENERATED_TOKEN_FILE_NAME = "6a888bdb653a4ba345dd68f21b896ec2e218c6f4.json"; private static final String WRONG_TOKEN_FILE_NAME = "wrong-token-file.json"; @Test void cachedTokenFile_correctFormat_resolveAccessTokenCorrectly() throws IOException { String tokenFile = "{\n" + "\"accessToken\": \"base64string\",\n" + "\"expiresAt\": \"2090-01-01T00:00:00Z\",\n" + "\"region\": \"us-west-2\", \n" + "\"startUrl\": \""+ START_URL +"\"\n" + "}"; SsoAccessTokenProvider provider = new SsoAccessTokenProvider( prepareTestCachedTokenFile(tokenFile, GENERATED_TOKEN_FILE_NAME)); assertThat(provider.resolveToken().token()).isEqualTo("base64string"); } @Test void cachedTokenFile_accessTokenMissing_throwNullPointerException() throws IOException { String tokenFile = "{\n" + "\"expiresAt\": \"2090-01-01T00:00:00Z\",\n" + "\"region\": \"us-west-2\", \n" + "\"startUrl\": \""+ START_URL +"\"\n" + "}"; SsoAccessTokenProvider provider = new SsoAccessTokenProvider( prepareTestCachedTokenFile(tokenFile, GENERATED_TOKEN_FILE_NAME)); assertThatThrownBy(() -> provider.resolveToken().token()).isInstanceOf(NullPointerException.class); } @Test void cachedTokenFile_expiresAtMissing_throwNullPointerException() throws IOException { String tokenFile = "{\n" + "\"accessToken\": \"base64string\",\n" + "\"region\": \"us-west-2\", \n" + "\"startUrl\": \""+ START_URL +"\"\n" + "}"; SsoAccessTokenProvider provider = new SsoAccessTokenProvider( prepareTestCachedTokenFile(tokenFile, GENERATED_TOKEN_FILE_NAME)); assertThatThrownBy(() -> provider.resolveToken().token()).isInstanceOf(NullPointerException.class); } @Test void cachedTokenFile_optionalRegionMissing_resolveAccessTokenCorrectly() throws IOException { String tokenFile = "{\n" + "\"accessToken\": \"base64string\",\n" + "\"expiresAt\": \"2090-01-01T00:00:00Z\",\n" + "\"startUrl\": \""+ START_URL +"\"\n" + "}"; SsoAccessTokenProvider provider = new SsoAccessTokenProvider( prepareTestCachedTokenFile(tokenFile, GENERATED_TOKEN_FILE_NAME)); assertThat(provider.resolveToken().token()).isEqualTo("base64string"); } @Test void cachedTokenFile_optionalStartUrlMissing_resolveAccessTokenCorrectly() throws IOException { String tokenFile = "{\n" + "\"accessToken\": \"base64string\",\n" + "\"expiresAt\": \"2090-01-01T00:00:00Z\",\n" + "\"region\": \"us-west-2\"\n" + "}"; SsoAccessTokenProvider provider = new SsoAccessTokenProvider( prepareTestCachedTokenFile(tokenFile, GENERATED_TOKEN_FILE_NAME)); assertThat(provider.resolveToken().token()).isEqualTo("base64string"); } @Test void cachedTokenFile_alreadyExpired_resolveAccessTokenCorrectly() throws IOException { String tokenFile = "{\n" + "\"accessToken\": \"base64string\",\n" + "\"expiresAt\": \"2019-01-01T00:00:00Z\",\n" + "\"region\": \"us-west-2\"\n" + "}"; SsoAccessTokenProvider provider = new SsoAccessTokenProvider( prepareTestCachedTokenFile(tokenFile, GENERATED_TOKEN_FILE_NAME)); assertThatThrownBy(() -> provider.resolveToken().token()).hasMessageContaining("The SSO session associated with this profile " + "has expired or is otherwise invalid."); } @Test void cachedTokenFile_tokenFileNotExist_throwNullPointerException() throws IOException { String tokenFile = "{\n" + "\"accessToken\": \"base64string\",\n" + "\"expiresAt\": \"2019-01-01T00:00:00Z\",\n" + "\"region\": \"us-west-2\"\n" + "}"; prepareTestCachedTokenFile(tokenFile, WRONG_TOKEN_FILE_NAME); SsoAccessTokenProvider provider = new SsoAccessTokenProvider(createTestCachedTokenFilePath( Jimfs.newFileSystem(Configuration.unix()).getPath("./foo"), GENERATED_TOKEN_FILE_NAME)); assertThatThrownBy(() -> provider.resolveToken().token()).isInstanceOf(UncheckedIOException.class); } @Test void cachedTokenFile_AboutToExpire_resolveAccessTokenCorrectly() throws IOException { String tokenFile = String.format("{\n" + "\"accessToken\": \"base64string\",\n" + "\"expiresAt\": \"%s\",\n" + "\"startUrl\": \""+ START_URL +"\"\n" + "}", stringFormattedTime(Instant.now().plusSeconds(10))); SsoAccessTokenProvider provider = new SsoAccessTokenProvider( prepareTestCachedTokenFile(tokenFile, GENERATED_TOKEN_FILE_NAME)); assertThat(provider.resolveToken().token()).isEqualTo("base64string"); } @Test void cachedTokenFile_JustExpired_throwsExpiredTokenException() throws IOException { String tokenFile = String.format("{\n" + "\"accessToken\": \"base64string\",\n" + "\"expiresAt\": \"%s\",\n" + "\"startUrl\": \""+ START_URL +"\"\n" + "}", stringFormattedTime(Instant.now())); SsoAccessTokenProvider provider = new SsoAccessTokenProvider( prepareTestCachedTokenFile(tokenFile, GENERATED_TOKEN_FILE_NAME)); assertThatThrownBy(() -> provider.resolveToken().token()).hasMessageContaining("The SSO session associated with this profile " + "has expired or is otherwise invalid."); } @Test void cachedTokenFile_ExpiredFewSecondsAgo_throwsExpiredTokenException() throws IOException { String tokenFile = String.format("{\n" + "\"accessToken\": \"base64string\",\n" + "\"expiresAt\": \"%s\",\n" + "\"startUrl\": \""+ START_URL +"\"\n" + "}", stringFormattedTime(Instant.now().minusSeconds(1))); SsoAccessTokenProvider provider = new SsoAccessTokenProvider( prepareTestCachedTokenFile(tokenFile, GENERATED_TOKEN_FILE_NAME)); assertThatThrownBy(() -> provider.resolveToken().token()).hasMessageContaining("The SSO session associated with this profile " + "has expired or is otherwise invalid."); } private Path prepareTestCachedTokenFile(String tokenFileContent, String generatedTokenFileName) throws IOException { FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); Path fileDirectory = fs.getPath("./foo"); Files.createDirectory(fileDirectory); Path cachedTokenFilePath = createTestCachedTokenFilePath(fileDirectory, generatedTokenFileName); Files.write(cachedTokenFilePath, ImmutableList.of(tokenFileContent), StandardCharsets.UTF_8); return cachedTokenFilePath; } private Path createTestCachedTokenFilePath(Path directory, String tokenFileName) { return directory.resolve(tokenFileName); } private String stringFormattedTime(Instant instant){ // Convert Instant to ZonedDateTime with UTC time zone ZonedDateTime zonedDateTime = instant.atZone(ZoneOffset.UTC); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); return formatter.format(zonedDateTime); } }
4,786
0
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso/auth/SsoCredentialsProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.auth; import static software.amazon.awssdk.utils.Validate.notNull; import java.time.Duration; import java.time.Instant; import java.util.Optional; 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.services.sso.SsoClient; import software.amazon.awssdk.services.sso.internal.SessionCredentialsHolder; import software.amazon.awssdk.services.sso.model.GetRoleCredentialsRequest; import software.amazon.awssdk.services.sso.model.RoleCredentials; import software.amazon.awssdk.utils.SdkAutoCloseable; 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 periodically sends a {@link GetRoleCredentialsRequest} to the AWS * Single Sign-On 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 SsoCredentialsProvider#builder()}. */ @SdkPublicApi public final class SsoCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable, ToCopyableBuilder<SsoCredentialsProvider.Builder, SsoCredentialsProvider> { private static final Duration DEFAULT_STALE_TIME = Duration.ofMinutes(1); private static final Duration DEFAULT_PREFETCH_TIME = Duration.ofMinutes(5); private static final String ASYNC_THREAD_NAME = "sdk-sso-credentials-provider"; private final Supplier<GetRoleCredentialsRequest> getRoleCredentialsRequestSupplier; private final SsoClient ssoClient; private final Duration staleTime; private final Duration prefetchTime; private final CachedSupplier<SessionCredentialsHolder> credentialCache; private final Boolean asyncCredentialUpdateEnabled; /** * @see #builder() */ private SsoCredentialsProvider(BuilderImpl builder) { this.ssoClient = notNull(builder.ssoClient, "SSO client must not be null."); this.getRoleCredentialsRequestSupplier = builder.getRoleCredentialsRequestSupplier; 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<SessionCredentialsHolder> cacheBuilder = CachedSupplier.builder(this::updateSsoCredentials) .cachedValueName(toString()); if (builder.asyncCredentialUpdateEnabled) { cacheBuilder.prefetchStrategy(new NonBlocking(ASYNC_THREAD_NAME)); } this.credentialCache = cacheBuilder.build(); } /** * Update the expiring session SSO credentials by calling SSO. Invoked by {@link CachedSupplier} when the credentials * are close to expiring. */ private RefreshResult<SessionCredentialsHolder> updateSsoCredentials() { SessionCredentialsHolder credentials = getUpdatedCredentials(ssoClient); Instant acutalTokenExpiration = credentials.sessionCredentialsExpiration(); return RefreshResult.builder(credentials) .staleTime(acutalTokenExpiration.minus(staleTime)) .prefetchTime(acutalTokenExpiration.minus(prefetchTime)) .build(); } private SessionCredentialsHolder getUpdatedCredentials(SsoClient ssoClient) { GetRoleCredentialsRequest request = getRoleCredentialsRequestSupplier.get(); notNull(request, "GetRoleCredentialsRequest can't be null."); RoleCredentials roleCredentials = ssoClient.getRoleCredentials(request).roleCredentials(); AwsSessionCredentials sessionCredentials = AwsSessionCredentials.create(roleCredentials.accessKeyId(), roleCredentials.secretAccessKey(), roleCredentials.sessionToken()); return new SessionCredentialsHolder(sessionCredentials, Instant.ofEpochMilli(roleCredentials.expiration())); } /** * The amount of time, relative to session 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 session token expiration, that the cached credentials are considered close to stale * and should be updated. */ public Duration prefetchTime() { return prefetchTime; } /** * Get a builder for creating a custom {@link SsoCredentialsProvider}. */ public static BuilderImpl builder() { return new BuilderImpl(); } @Override public AwsCredentials resolveCredentials() { return credentialCache.get().sessionCredentials(); } @Override public void close() { credentialCache.close(); } @Override public Builder toBuilder() { return new BuilderImpl(this); } /** * A builder for creating a custom {@link SsoCredentialsProvider}. */ public interface Builder extends CopyableBuilder<Builder, SsoCredentialsProvider> { /** * Configure the {@link SsoClient} to use when calling SSO to update the session. This client should not be shut * down as long as this credentials provider is in use. */ Builder ssoClient(SsoClient ssoclient); /** * 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 addtiional resources are used to maintian * the provider. * * <p>By default, this is disabled.</p> */ Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled); /** * Configure the amount of time, relative to SSO session token expiration, that the cached credentials are considered * stale and should no longer be used. All threads will block until the value is updated. * * <p>By default, this is 1 minute.</p> */ Builder staleTime(Duration staleTime); /** * Configure the amount of time, relative to SSO session 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> */ Builder prefetchTime(Duration prefetchTime); /** * Configure the {@link GetRoleCredentialsRequest} that should be periodically sent to the SSO service to update the * credentials. */ Builder refreshRequest(GetRoleCredentialsRequest getRoleCredentialsRequest); /** * Similar to {@link #refreshRequest(GetRoleCredentialsRequest)}, but takes a {@link Supplier} to supply the request to * SSO. */ Builder refreshRequest(Supplier<GetRoleCredentialsRequest> getRoleCredentialsRequestSupplier); /** * Create a {@link SsoCredentialsProvider} using the configuration applied to this builder. * @return */ SsoCredentialsProvider build(); } protected static final class BuilderImpl implements Builder { private Boolean asyncCredentialUpdateEnabled = false; private SsoClient ssoClient; private Duration staleTime; private Duration prefetchTime; private Supplier<GetRoleCredentialsRequest> getRoleCredentialsRequestSupplier; BuilderImpl() { } public BuilderImpl(SsoCredentialsProvider provider) { this.asyncCredentialUpdateEnabled = provider.asyncCredentialUpdateEnabled; this.ssoClient = provider.ssoClient; this.staleTime = provider.staleTime; this.prefetchTime = provider.prefetchTime; this.getRoleCredentialsRequestSupplier = provider.getRoleCredentialsRequestSupplier; } @Override public Builder ssoClient(SsoClient ssoClient) { this.ssoClient = ssoClient; return this; } @Override public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) { this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled; return this; } @Override public Builder staleTime(Duration staleTime) { this.staleTime = staleTime; return this; } @Override public Builder prefetchTime(Duration prefetchTime) { this.prefetchTime = prefetchTime; return this; } @Override public Builder refreshRequest(GetRoleCredentialsRequest getRoleCredentialsRequest) { return refreshRequest(() -> getRoleCredentialsRequest); } @Override public Builder refreshRequest(Supplier<GetRoleCredentialsRequest> getRoleCredentialsRequestSupplier) { this.getRoleCredentialsRequestSupplier = getRoleCredentialsRequestSupplier; return this; } @Override public SsoCredentialsProvider build() { return new SsoCredentialsProvider(this); } } }
4,787
0
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso/auth/SsoProfileCredentialsProviderFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.auth; import static software.amazon.awssdk.services.sso.internal.SsoTokenFileUtils.generateCachedTokenPath; import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory; import java.nio.file.Paths; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProviderFactory; import software.amazon.awssdk.auth.credentials.ProfileProviderCredentialsContext; import software.amazon.awssdk.auth.token.credentials.ProfileTokenProvider; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.auth.token.internal.LazyTokenProvider; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.profiles.internal.ProfileSection; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sso.SsoClient; import software.amazon.awssdk.services.sso.internal.SsoAccessTokenProvider; import software.amazon.awssdk.services.sso.model.GetRoleCredentialsRequest; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.Validate; /** * An implementation of {@link ProfileCredentialsProviderFactory} that allows users to get SSO role credentials using the startUrl * specified in either a {@link Profile} or environment variables. */ @SdkProtectedApi public class SsoProfileCredentialsProviderFactory implements ProfileCredentialsProviderFactory { private static final String TOKEN_DIRECTORY = Paths.get(userHomeDirectory(), ".aws", "sso", "cache").toString(); private static final String MISSING_PROPERTY_ERROR_FORMAT = "'%s' must be set to use role-based credential loading in the " + "'%s' profile."; /** * Default method to create the {@link SsoProfileCredentialsProvider} with a {@link SsoAccessTokenProvider} object created * with the start url from {@link Profile} in the {@link ProfileProviderCredentialsContext} or environment variables and the * default token file directory. */ @Override public AwsCredentialsProvider create(ProfileProviderCredentialsContext credentialsContext) { return new SsoProfileCredentialsProvider(credentialsContext.profile(), credentialsContext.profileFile(), sdkTokenProvider(credentialsContext.profile(), credentialsContext.profileFile())); } /** * Alternative method to create the {@link SsoProfileCredentialsProvider} with a customized {@link SsoAccessTokenProvider}. * This method is only used for testing. */ @SdkTestInternalApi public AwsCredentialsProvider create(Profile profile, ProfileFile profileFile, SdkTokenProvider tokenProvider) { return new SsoProfileCredentialsProvider(profile, profileFile, tokenProvider); } /** * A wrapper for a {@link SsoCredentialsProvider} that is returned by this factory when {@link * #create(ProfileProviderCredentialsContext)} * or {@link #create(Profile, ProfileFile, SdkTokenProvider)} is invoked. This * wrapper is important because it ensures * the parent credentials provider is closed when the sso credentials provider is no * longer needed. */ private static final class SsoProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { private final SsoClient ssoClient; private final SsoCredentialsProvider credentialsProvider; private SsoProfileCredentialsProvider(Profile profile, ProfileFile profileFile, SdkTokenProvider tokenProvider) { String ssoAccountId = profile.properties().get(ProfileProperty.SSO_ACCOUNT_ID); String ssoRoleName = profile.properties().get(ProfileProperty.SSO_ROLE_NAME); String ssoRegion = regionFromProfileOrSession(profile, profileFile); this.ssoClient = SsoClient.builder() .credentialsProvider(AnonymousCredentialsProvider.create()) .region(Region.of(ssoRegion)) .build(); GetRoleCredentialsRequest request = GetRoleCredentialsRequest.builder() .accountId(ssoAccountId) .roleName(ssoRoleName) .build(); SdkToken sdkToken = tokenProvider.resolveToken(); Validate.paramNotNull(sdkToken, "Token provided by the TokenProvider is null"); Supplier<GetRoleCredentialsRequest> supplier = () -> request.toBuilder() .accessToken(sdkToken.token()) .build(); this.credentialsProvider = SsoCredentialsProvider.builder() .ssoClient(ssoClient) .refreshRequest(supplier) .build(); } @Override public AwsCredentials resolveCredentials() { return this.credentialsProvider.resolveCredentials(); } @Override public void close() { IoUtils.closeQuietly(credentialsProvider, null); IoUtils.closeQuietly(ssoClient, null); } private static String regionFromProfileOrSession(Profile profile, ProfileFile profileFile) { Optional<String> ssoSession = profile.property(ProfileSection.SSO_SESSION.getPropertyKeyName()); String profileRegion = profile.properties().get(ProfileProperty.SSO_REGION); return ssoSession.isPresent() ? propertyFromSsoSession(ssoSession.get(), profileFile, ProfileProperty.SSO_REGION) : profileRegion; } private static String propertyFromSsoSession(String sessionName, ProfileFile profileFile, String propertyName) { Profile ssoProfile = ssoSessionInProfile(sessionName, profileFile); return requireProperty(ssoProfile, propertyName); } private static String requireProperty(Profile profile, String requiredProperty) { return profile.property(requiredProperty) .orElseThrow(() -> new IllegalArgumentException(String.format(MISSING_PROPERTY_ERROR_FORMAT, requiredProperty, profile.name()))); } } private static Profile ssoSessionInProfile(String sessionName, ProfileFile profileFile) { Profile ssoProfile = profileFile.getSection( ProfileSection.SSO_SESSION.getSectionTitle(), sessionName).orElseThrow(() -> new IllegalArgumentException( "Sso-session section not found with sso-session title " + sessionName + ".")); return ssoProfile; } private static SdkTokenProvider sdkTokenProvider(Profile profile, ProfileFile profileFile) { Optional<String> ssoSession = profile.property(ProfileSection.SSO_SESSION.getPropertyKeyName()); if (ssoSession.isPresent()) { Profile ssoSessionProfileFile = ssoSessionInProfile(ssoSession.get(), profileFile); validateCommonProfileProperties(profile, ssoSessionProfileFile, ProfileProperty.SSO_REGION); validateCommonProfileProperties(profile, ssoSessionProfileFile, ProfileProperty.SSO_START_URL); return LazyTokenProvider.create( () -> ProfileTokenProvider.builder() .profileFile(() -> profileFile) .profileName(profile.name()) .build()); } else { return new SsoAccessTokenProvider(generateCachedTokenPath( profile.properties().get(ProfileProperty.SSO_START_URL), TOKEN_DIRECTORY)); } } private static void validateCommonProfileProperties(Profile profile, Profile ssoSessionProfileFile, String propertyName) { profile.property(propertyName).ifPresent( property -> Validate.isTrue(property.equalsIgnoreCase(ssoSessionProfileFile.property(propertyName).get()), "Profile " + profile.name() + " and Sso-session " + ssoSessionProfileFile.name() + " has " + "different " + propertyName + ".")); } }
4,788
0
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso/auth/ExpiredTokenException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.auth; import java.util.Arrays; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.exception.SdkClientException; /** * <p> * The session token that was passed is expired or is not valid. * </p> */ @SdkPublicApi public final class ExpiredTokenException extends SdkClientException { private static final List<SdkField<?>> SDK_FIELDS = Collections.unmodifiableList(Arrays.asList()); private ExpiredTokenException(Builder b) { super(b); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder extends SdkPojo, SdkClientException.Builder { @Override Builder message(String message); @Override Builder cause(Throwable cause); @Override Builder writableStackTrace(Boolean writableStackTrace); @Override ExpiredTokenException build(); } static final class BuilderImpl extends SdkClientException.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(ExpiredTokenException model) { super(model); } @Override public BuilderImpl message(String message) { this.message = message; return this; } @Override public BuilderImpl cause(Throwable cause) { this.cause = cause; return this; } @Override public BuilderImpl writableStackTrace(Boolean writableStackTrace) { this.writableStackTrace = writableStackTrace; return this; } @Override public ExpiredTokenException build() { return new ExpiredTokenException(this); } @Override public List<SdkField<?>> sdkFields() { return SDK_FIELDS; } } }
4,789
0
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso/internal/SsoTokenFileUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.internal; import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.Validate; /** * A tool class helps generating the path of cached token file. */ @SdkInternalApi public class SsoTokenFileUtils { private static final Pattern HOME_DIRECTORY_PATTERN = Pattern.compile("^~(/|" + Pattern.quote(FileSystems.getDefault().getSeparator()) + ").*$"); private SsoTokenFileUtils() { } /** * Generate the cached file name by generating the SHA1 Hex Digest of the UTF-8 encoded start url bytes. */ public static Path generateCachedTokenPath(String startUrl, String tokenDirectory) { Validate.notNull(startUrl, "The start url shouldn't be null."); byte[] startUrlBytes = startUrl.getBytes(StandardCharsets.UTF_8); String encodedUrl = new String(startUrlBytes, StandardCharsets.UTF_8); return resolveProfileFilePath(Paths.get(tokenDirectory, sha1Hex(encodedUrl) + ".json").toString()); } /** * Use {@link MessageDigest} instance to encrypt the input String. */ private static String sha1Hex(String input) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); md.update(input.getBytes(StandardCharsets.UTF_8)); } catch (NoSuchAlgorithmException e) { throw SdkClientException.builder().message("Unable to use \"SHA-1\" algorithm.").cause(e).build(); } return BinaryUtils.toHex(md.digest()); } private static Path resolveProfileFilePath(String path) { // Resolve ~ using the CLI's logic, not whatever Java decides to do with it. if (HOME_DIRECTORY_PATTERN.matcher(path).matches()) { path = userHomeDirectory() + path.substring(1); } return Paths.get(path); } }
4,790
0
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso/internal/SsoAccessTokenProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.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.time.Instant; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.services.sso.auth.ExpiredTokenException; import software.amazon.awssdk.services.sso.auth.SsoCredentialsProvider; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Validate; /** * Resolve the access token from the cached token file. If the token has expired then throw out an exception to ask the users to * update the token. This provider can also be replaced by any other implementation of resolving the access token. The users can * resolve the access token in their own way and add it to the {@link SsoCredentialsProvider.Builder#refreshRequest}. */ @SdkInternalApi public final class SsoAccessTokenProvider implements SdkTokenProvider { private static final JsonNodeParser PARSER = JsonNodeParser.builder().removeErrorLocations(true).build(); private final Path cachedTokenFilePath; public SsoAccessTokenProvider(Path cachedTokenFilePath) { this.cachedTokenFilePath = cachedTokenFilePath; } @Override public SdkToken resolveToken() { return tokenFromFile(); } private SdkToken tokenFromFile() { try (InputStream cachedTokenStream = Files.newInputStream(cachedTokenFilePath)) { return getTokenFromJson(IoUtils.toUtf8String(cachedTokenStream)); } catch (IOException e) { throw new UncheckedIOException(e); } } private SdkToken getTokenFromJson(String json) { JsonNode jsonNode = PARSER.parse(json); String expiration = jsonNode.field("expiresAt").map(JsonNode::text).orElse(null); Validate.notNull(expiration, "The SSO session's expiration time could not be determined. Please refresh your SSO session."); if (tokenIsInvalid(expiration)) { throw ExpiredTokenException.builder().message("The SSO session associated with this profile has expired or is" + " otherwise invalid. To refresh this SSO session run aws sso" + " login with the corresponding profile.").build(); } return SsoAccessToken.builder() .accessToken(jsonNode.asObject().get("accessToken").text()) .expiresAt(Instant.parse(expiration)).build(); } private boolean tokenIsInvalid(String expirationTime) { return Instant.now().isAfter(Instant.parse(expirationTime)); } }
4,791
0
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso/internal/SsoAccessToken.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.internal; import java.time.Instant; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; @SdkInternalApi public class SsoAccessToken implements SdkToken { private final String accessToken; private final Instant expiresAt; private SsoAccessToken(BuilderImpl builder) { this.accessToken = Validate.paramNotNull(builder.accessToken, "accessToken"); this.expiresAt = Validate.paramNotNull(builder.expiresAt, "expiresAt"); } public static Builder builder() { return new BuilderImpl(); } @Override public String token() { return accessToken; } @Override public Optional<Instant> expirationTime() { return Optional.of(expiresAt); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SsoAccessToken ssoAccessToken = (SsoAccessToken) o; return Objects.equals(accessToken, ssoAccessToken.accessToken) && Objects.equals(expiresAt, ssoAccessToken.expiresAt); } @Override public int hashCode() { int result = Objects.hashCode(accessToken); result = 31 * result + Objects.hashCode(expiresAt); return result; } @Override public String toString() { return ToString.builder("SsoAccessToken") .add("accessToken", accessToken) .add("expiresAt", expiresAt) .build(); } public interface Builder { Builder accessToken(String accessToken); Builder expiresAt(Instant expiresAt); SsoAccessToken build(); } private static class BuilderImpl implements Builder { private String accessToken; private Instant expiresAt; @Override public Builder accessToken(String accessToken) { this.accessToken = accessToken; return this; } @Override public Builder expiresAt(Instant expiresAt) { this.expiresAt = expiresAt; return this; } @Override public SsoAccessToken build() { return new SsoAccessToken(this); } } }
4,792
0
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso
Create_ds/aws-sdk-java-v2/services/sso/src/main/java/software/amazon/awssdk/services/sso/internal/SessionCredentialsHolder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sso.internal; import java.time.Instant; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; /** * Holder class used to atomically store a session with its expiration time. */ @SdkInternalApi @ThreadSafe public final class SessionCredentialsHolder { private final AwsSessionCredentials sessionCredentials; private final Instant sessionCredentialsExpiration; public SessionCredentialsHolder(AwsSessionCredentials credentials, Instant expiration) { this.sessionCredentials = credentials; this.sessionCredentialsExpiration = expiration; } public AwsSessionCredentials sessionCredentials() { return sessionCredentials; } public Instant sessionCredentialsExpiration() { return sessionCredentialsExpiration; } }
4,793
0
Create_ds/aws-sdk-java-v2/services/codedeploy/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/codedeploy/src/it/java/software/amazon/awssdk/services/codedeploy/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.codedeploy; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.testutils.service.AwsTestBase; public class IntegrationTestBase extends AwsTestBase { /** * The code deploy client reference used for testing. */ protected static CodeDeployClient codeDeploy; /** * Reads the credentials and sets up the code deploy the client. */ @BeforeClass public static void setUp() throws FileNotFoundException, IOException { setUpCredentials(); codeDeploy = CodeDeployClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } }
4,794
0
Create_ds/aws-sdk-java-v2/services/codedeploy/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/codedeploy/src/it/java/software/amazon/awssdk/services/codedeploy/CodeDeployIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.codedeploy; 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.io.FileNotFoundException; import java.io.IOException; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.services.codedeploy.model.ApplicationInfo; import software.amazon.awssdk.services.codedeploy.model.CreateApplicationRequest; import software.amazon.awssdk.services.codedeploy.model.CreateApplicationResponse; import software.amazon.awssdk.services.codedeploy.model.CreateDeploymentGroupRequest; import software.amazon.awssdk.services.codedeploy.model.DeleteApplicationRequest; import software.amazon.awssdk.services.codedeploy.model.GetApplicationRequest; import software.amazon.awssdk.services.codedeploy.model.GetApplicationResponse; import software.amazon.awssdk.services.codedeploy.model.ListApplicationsRequest; import software.amazon.awssdk.services.codedeploy.model.ListApplicationsResponse; /** * Performs basic integration tests for AWS Code Deploy service. * */ public class CodeDeployIntegrationTest extends IntegrationTestBase { /** * The name of the application being created. */ private static final String APP_NAME = "java-sdk-appln-" + System.currentTimeMillis(); /** The name of the deployment group being created, */ private static final String DEPLOYMENT_GROUP_NAME = "java-sdk-deploy-" + System.currentTimeMillis(); /** * The id of the application created in AWS Code Deploy service. */ private static String applicationId = null; /** * Creates an application and asserts the result for the application id * returned from code deploy service. */ @BeforeClass public static void setUp() throws FileNotFoundException, IOException { IntegrationTestBase.setUp(); CreateApplicationRequest createRequest = CreateApplicationRequest.builder() .applicationName(APP_NAME) .build(); CreateApplicationResponse createResult = codeDeploy .createApplication(createRequest); applicationId = createResult.applicationId(); assertNotNull(applicationId); } /** * Delete the application from code deploy service created for this testing. */ @AfterClass public static void tearDown() { if (applicationId != null) { codeDeploy.deleteApplication(DeleteApplicationRequest.builder() .applicationName(APP_NAME) .build()); } } /** * Performs a list application operation. Asserts that the result should * have atleast one application */ @Test public void testListApplication() { ListApplicationsResponse listResult = codeDeploy.listApplications(ListApplicationsRequest.builder().build()); List<String> applicationList = listResult.applications(); assertTrue(applicationList.size() >= 1); assertTrue(applicationList.contains(APP_NAME)); } /** * Performs a get application operation. Asserts that the application name * and id retrieved matches the one created for the testing. */ @Test public void testGetApplication() { GetApplicationResponse getResult = codeDeploy .getApplication(GetApplicationRequest.builder() .applicationName(APP_NAME) .build()); ApplicationInfo applicationInfo = getResult.application(); assertEquals(applicationId, applicationInfo.applicationId()); assertEquals(APP_NAME, applicationInfo.applicationName()); } /** * Tries to create a deployment group. The operation should fail as the * service role arn is not mentioned as part of the request. * TODO: Re work on this test case to use the IAM role ARN when the code supports it. */ @Test public void testCreateDeploymentGroup() { try { codeDeploy.createDeploymentGroup(CreateDeploymentGroupRequest.builder() .applicationName(APP_NAME) .deploymentGroupName(DEPLOYMENT_GROUP_NAME).build()); fail("Create Deployment group should fail as it requires a service role ARN to be specified"); } catch (Exception ace) { assertTrue(ace instanceof SdkServiceException); } } }
4,795
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc/internal/SsoOidcTokenTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ssooidc.internal; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.time.Instant; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class SsoOidcTokenTest { @Test public void equalsAndHashCode_workCorrectly() { EqualsVerifier.forClass(SsoOidcToken.class) .usingGetClass() .verify(); } @Test public void builder_maximal() { String accessToken = "accesstoken"; Instant expiresAt = Instant.now(); String refreshToken = "refreshtoken"; String clientId = "clientid"; String clientSecret = "clientsecret"; Instant registrationExpiresAt = expiresAt.plus(Duration.ofHours(1)); String region = "region"; String startUrl = "starturl"; SsoOidcToken ssoOidcToken = SsoOidcToken.builder() .accessToken(accessToken) .expiresAt(expiresAt) .refreshToken(refreshToken) .clientId(clientId) .clientSecret(clientSecret) .registrationExpiresAt(registrationExpiresAt) .region(region) .startUrl(startUrl) .build(); assertThat(ssoOidcToken.token()).isEqualTo(accessToken); assertThat(ssoOidcToken.expirationTime()).hasValue(expiresAt); assertThat(ssoOidcToken.refreshToken()).isEqualTo(refreshToken); assertThat(ssoOidcToken.clientId()).isEqualTo(clientId); assertThat(ssoOidcToken.clientSecret()).isEqualTo(clientSecret); assertThat(ssoOidcToken.registrationExpiresAt()).isEqualTo(registrationExpiresAt); assertThat(ssoOidcToken.region()).isEqualTo(region); assertThat(ssoOidcToken.startUrl()).isEqualTo(startUrl); } }
4,796
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc/internal/OnDiskTokenManagerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ssooidc.internal; import static org.assertj.core.api.Assertions.assertThat; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeFormatter; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; public class OnDiskTokenManagerTest { private static final JsonNodeParser PARSER = JsonNodeParser.builder().removeErrorLocations(true).build(); private FileSystem testFs; private Path cache; @BeforeEach public void setup() throws IOException { testFs = Jimfs.newFileSystem(Configuration.unix()); cache = testFs.getPath("/cache"); Files.createDirectory(cache); } @AfterEach public void teardown() throws IOException { testFs.close(); } @ParameterizedTest @CsvSource({ "admin , d033e22ae348aeb5660fc2140aec35850c4da997.json", "dev-scopes, 75e4d41276d8bd17f85986fc6cccef29fd725ce3.json" }) public void loadToken_loadsCorrectFile(String sessionName, String expectedLocation) throws IOException { Path tokenPath = cache.resolve(expectedLocation); Instant expiresAt = Instant.now(); SsoOidcToken token = SsoOidcToken.builder() .accessToken("accesstoken") .expiresAt(expiresAt) .build(); String tokenJson = String.format("{\n" + " \"accessToken\": \"accesstoken\",\n" + " \"expiresAt\": \"%s\"\n" + "}", DateTimeFormatter.ISO_INSTANT.format(expiresAt)); try (OutputStream os = Files.newOutputStream(tokenPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) { os.write(tokenJson.getBytes(StandardCharsets.UTF_8)); } OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(cache, sessionName); assertThat(onDiskTokenManager.loadToken().get()).isEqualTo(token); } @Test public void loadToken_maximal() throws IOException { Instant expiresAt = Instant.now(); Instant registrationExpiresAt = expiresAt.plus(Duration.ofDays(1)); String tokenJson = String.format("{\n" + " \"accessToken\": \"accesstoken\",\n" + " \"expiresAt\": \"%s\",\n" + " \"refreshToken\": \"refreshtoken\",\n" + " \"clientId\": \"clientid\",\n" + " \"clientSecret\": \"clientsecret\",\n" + " \"registrationExpiresAt\": \"%s\",\n" + " \"region\": \"region\",\n" + " \"startUrl\": \"starturl\"\n" + "}", DateTimeFormatter.ISO_INSTANT.format(expiresAt), DateTimeFormatter.ISO_INSTANT.format(registrationExpiresAt)); SsoOidcToken token = SsoOidcToken.builder() .accessToken("accesstoken") .expiresAt(expiresAt) .refreshToken("refreshtoken") .clientId("clientid") .clientSecret("clientsecret") .registrationExpiresAt(registrationExpiresAt) .region("region") .startUrl("starturl") .build(); String ssoSession = "admin"; String expectedFile = "d033e22ae348aeb5660fc2140aec35850c4da997.json"; try (OutputStream os = Files.newOutputStream(cache.resolve(expectedFile), StandardOpenOption.CREATE, StandardOpenOption.WRITE)) { os.write(tokenJson.getBytes(StandardCharsets.UTF_8)); } OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(cache, ssoSession); SsoOidcToken loadedToken = onDiskTokenManager.loadToken().get(); assertThat(loadedToken).isEqualTo(token); } @Test public void storeToken_maximal() throws IOException { Instant expiresAt = Instant.now(); Instant registrationExpiresAt = expiresAt.plus(Duration.ofDays(1)); String startUrl = "https://d-abc123.awsapps.com/start"; String ssoSessionName = "admin"; String tokenJson = String.format("{\n" + " \"accessToken\": \"accesstoken\",\n" + " \"expiresAt\": \"%s\",\n" + " \"refreshToken\": \"refreshtoken\",\n" + " \"clientId\": \"clientid\",\n" + " \"clientSecret\": \"clientsecret\",\n" + " \"registrationExpiresAt\": \"%s\",\n" + " \"region\": \"region\",\n" + " \"startUrl\": \"%s\"\n" + "}", DateTimeFormatter.ISO_INSTANT.format(expiresAt), DateTimeFormatter.ISO_INSTANT.format(registrationExpiresAt), startUrl); SsoOidcToken token = SsoOidcToken.builder() .accessToken("accesstoken") .expiresAt(expiresAt) .refreshToken("refreshtoken") .clientId("clientid") .clientSecret("clientsecret") .registrationExpiresAt(registrationExpiresAt) .region("region") .startUrl(startUrl) .build(); String expectedFile = "d033e22ae348aeb5660fc2140aec35850c4da997.json"; OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(cache, ssoSessionName); onDiskTokenManager.storeToken(token); JsonNode expectedJson = PARSER.parse(tokenJson); try (InputStream is = Files.newInputStream(cache.resolve(expectedFile))) { JsonNode storedJson = PARSER.parse(is); assertThat(storedJson).isEqualTo(expectedJson); } } @Test public void storeToken_loadToken_roundTrip() { Instant expiresAt = Instant.now(); Instant registrationExpiresAt = expiresAt.plus(Duration.ofDays(1)); String startUrl = "https://d-abc123.awsapps.com/start"; String sessionName = "ssoToken-Session"; SsoOidcToken token = SsoOidcToken.builder() .accessToken("accesstoken") .expiresAt(expiresAt) .refreshToken("refreshtoken") .clientId("clientid") .clientSecret("clientsecret") .registrationExpiresAt(registrationExpiresAt) .region("region") .startUrl(startUrl) .build(); OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(cache, sessionName); onDiskTokenManager.storeToken(token); SsoOidcToken loadedToken = onDiskTokenManager.loadToken().get(); assertThat(loadedToken).isEqualTo(token); } @Test public void loadToken_cachedValueNotFound_returnsEmpty() { OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(cache, "does-not-exist-session"); assertThat(onDiskTokenManager.loadToken()).isEmpty(); } }
4,797
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc/internal/SsoOidcTokenRefreshTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ssooidc.internal; import software.amazon.awssdk.services.ssooidc.internal.common.SsoOidcTokenRefreshTestBase; public final class SsoOidcTokenRefreshTest extends SsoOidcTokenRefreshTestBase { @Override public void initializeClient() { shouldMockServiceClient = true; baseTokenResourceFile = "src/test/resources/baseCreateToken.json"; testStartUrl = "http://caws-testing.com/start-url"; ssoOidcClient = mockSsoOidcClient(); } }
4,798
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc/internal/SsoOidcProfileTokenProviderFactoryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ssooidc.internal; import java.util.stream.Stream; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.auth.token.credentials.SdkTokenProviderFactoryProperties; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.services.ssooidc.SsoOidcProfileTokenProviderFactory; import software.amazon.awssdk.utils.StringInputStream; public class SsoOidcProfileTokenProviderFactoryTest { private static Stream<Arguments> ssoSessionMissingProperties() { String ssoRegionErrorMsg = "'sso_region' must be set to use bearer tokens loading in the 'one' profile."; String ssoStartUrlErrorMsg = "'sso_start_url' must be set to use bearer tokens loading in the 'one' profile."; String ssoSectionNotFoundError = "Sso-session section not found with sso-session title one."; return Stream.of(Arguments.of("[profile sso]\n" + "sso_session=one\n" + "[sso-session one]\n" + "sso_regions=us-east-1\n" + "sso_start_url= https://start-url\n", ssoRegionErrorMsg), Arguments.of("[profile sso]\n" + "sso_session=one\n" + "[sso-session one]\n" + "sso_region=us-east-1\n" + "sso_end_url= https://start-url\n", ssoStartUrlErrorMsg), Arguments.of("[profile sso]\n" + "sso_session=one\n" + "[sso-session one]\n" , ssoStartUrlErrorMsg), Arguments.of( "[profile sso]\n" + "sso_session=one\n" + "[sso-session two]\n" + "sso_region=us-east-1\n" + "sso_start_url= https://start-url\n", ssoSectionNotFoundError)); } @Test void create_throwsExceptionIfRegionNotPassed() { String startUrl = "https://my-start-url.com"; Assertions.assertThatExceptionOfType(NullPointerException.class).isThrownBy( () -> SdkTokenProviderFactoryProperties.builder() .startUrl(startUrl) .build() ).withMessage("region must not be null."); } @Test void create_throwsExceptionIfStartUrlNotPassed() { String region = "test-region"; Assertions.assertThatExceptionOfType(NullPointerException.class).isThrownBy( () -> SdkTokenProviderFactoryProperties.builder() .region(region) .build() ).withMessage("startUrl must not be null."); } @Test void create_SsooidcTokenProvider_from_SsooidcSpecificProfile() { String profileContent = "[profile ssotoken]\n" + "sso_session=admin\n" + "[sso-session admin]\n" + "sso_region=us-east-1\n" + "sso_start_url= https://start-url\n"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); SdkTokenProvider sdkTokenProvider = new SsoOidcProfileTokenProviderFactory().create(profiles, profiles.profile("ssotoken").get()); Assertions.assertThat(sdkTokenProvider).isNotNull(); } @Test void create_SsoOidcTokenProvider_from_SsooidcSpecificProfileSupplier() { String profileContent = "[profile ssotoken]\n" + "sso_session=admin\n" + "[sso-session admin]\n" + "sso_region=us-east-1\n" + "sso_start_url= https://start-url\n"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); SdkTokenProvider sdkTokenProvider = new SsoOidcProfileTokenProviderFactory().create(() -> profiles, "ssotoken"); Assertions.assertThat(sdkTokenProvider).isNotNull(); } @Test void create_SsoOidcTokenProvider_with_ssoAccountIdInProfile() { String profileContent = "[profile sso]\n" + "sso_region=us-east-1\n" + "sso_account_id=1234567\n" + "sso_start_url= https://start-url\n"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); Assertions.assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(() -> new SsoOidcProfileTokenProviderFactory().create(profiles, profiles.profile("sso").get())); } @Test void create_SsoOidcTokenProvider_with_ssoRoleNameInProfile() { String profileContent = "[profile sso]\n" + "sso_region=us-east-1\n" + "sso_role_name=ssoSpecificRole\n" + "sso_start_url= https://start-url\n"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); Assertions.assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(() -> new SsoOidcProfileTokenProviderFactory().create(profiles, profiles.profile("sso").get())); } @Test void create_SsoOidcTokenProvider_with_ssoRoleNameInProfileSupplier() { String profileContent = "[profile sso]\n" + "sso_region=us-east-1\n" + "sso_role_name=ssoSpecificRole\n" + "sso_start_url= https://start-url\n"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); Assertions.assertThatNoException() .isThrownBy(() -> new SsoOidcProfileTokenProviderFactory().create(() -> profiles, "sso")); } @ParameterizedTest @MethodSource("ssoSessionMissingProperties") void incorrectSsoProperties_throwsException(String ssoProfileContent, String msg) { ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(ssoProfileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); Assertions.assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy( () -> new SsoOidcProfileTokenProviderFactory().create(profiles, profiles.profile("sso").get())) .withMessageContaining(msg); } }
4,799