index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/services/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, } }
5,000
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(); } }
5,001
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; } }
5,002
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; } }
5,003
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; } }
5,004
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; } }
5,005
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; } }
5,006
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; } }
5,007
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. } } }
5,008
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); } }
5,009
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."); } } }
5,010
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); } }
5,011
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))); } }
5,012
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 {} }
5,013
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); } }
5,014
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); } }
5,015
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); } }
5,016
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()); } } }
5,017
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); } }
5,018
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(); } }
5,019
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()); } }
5,020
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"); } }
5,021
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()); } } }
5,022
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(); } }
5,023
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()); } }
5,024
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(); } }
5,025
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()); } }
5,026
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(); } }
5,027
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()); } }
5,028
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()); } }
5,029
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()); } }
5,030
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)); } }
5,031
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); } }
5,032
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; } }
5,033
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()); } }
5,034
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(); } }
5,035
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); } }
5,036
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; } }
5,037
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; } }
5,038
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()); } }
5,039
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(); } }
5,040
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()); } } }
5,041
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"; } }
5,042
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("-", ""); } }
5,043
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; } }
5,044
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(); } }
5,045
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]; } }
5,046
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); } }
5,047
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()); } }
5,048
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); } }
5,049
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()); } }
5,050
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); } }
5,051
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()); } }
5,052
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(); } }
5,053
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(); } }
5,054
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(); } } }
5,055
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"); }); } }
5,056
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(); } }
5,057
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"); } }
5,058
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); } }
5,059
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); } } }
5,060
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 + ".")); } }
5,061
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; } } }
5,062
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); } }
5,063
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)); } }
5,064
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); } } }
5,065
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; } }
5,066
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(); } }
5,067
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); } } }
5,068
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); } }
5,069
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(); } }
5,070
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(); } }
5,071
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); } }
5,072
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/SsoOidcTokenProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.io.File; 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.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; import java.util.Locale; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.awscore.internal.token.TokenManager; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.ssooidc.SsoOidcClient; import software.amazon.awssdk.services.ssooidc.SsoOidcTokenProvider; import software.amazon.awssdk.services.ssooidc.internal.common.SsoOidcTokenRefreshTestBase; import software.amazon.awssdk.services.ssooidc.model.CreateTokenRequest; import software.amazon.awssdk.services.ssooidc.model.CreateTokenResponse; import software.amazon.awssdk.services.ssooidc.model.UnauthorizedClientException; import software.amazon.awssdk.utils.BinaryUtils; public class SsoOidcTokenProviderTest { public static final String START_URL = "https://d-123.awsapps.com/start"; public static final String REGION = "region"; private TokenManager<SsoOidcToken> mockTokenManager; private SsoOidcClient ssoOidcClient; private FileSystem testFs; private Path cache; public static String deriveCacheKey(String startUrl) { try { MessageDigest sha1 = MessageDigest.getInstance("sha1"); sha1.update(startUrl.getBytes(StandardCharsets.UTF_8)); return BinaryUtils.toHex(sha1.digest()).toLowerCase(Locale.ENGLISH); } catch (NoSuchAlgorithmException e) { throw SdkClientException.create("Unable to derive cache key", e); } } @BeforeEach public void setup() throws IOException { File cacheDirectory = SsoOidcTokenRefreshTestBase.DEFAULT_TOKEN_LOCATION.toFile(); if(! cacheDirectory.exists()){ cacheDirectory.mkdirs(); } Path file = Paths.get(cacheDirectory.getPath()+ deriveCacheKey(START_URL) + ".json"); if(file.toFile().exists()){ file.toFile().delete(); } Files.createDirectories(file.getParent()); Files.createFile(file); mockTokenManager = OnDiskTokenManager.create(START_URL); ssoOidcClient = mock(SsoOidcClient.class); } @AfterEach public void teardown() throws IOException { Path path = Paths.get(userHomeDirectory(), ".aws", "sso", "cache"); Path resolve = path.resolve(deriveCacheKey(START_URL) + ".json"); Files.deleteIfExists(resolve); } @Test public void resolveToken_usesTokenManager() { SsoOidcToken ssoOidcToken = SsoOidcToken.builder() .accessToken("accesstoken") .expiresAt(Instant.now().plus(Duration.ofDays(1))) .build(); mockTokenManager.storeToken(ssoOidcToken); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThat(tokenProvider.resolveToken()).isEqualTo(ssoOidcToken); } private SsoOidcTokenProvider.Builder getDefaultSsoOidcTokenProviderBuilder() { return SsoOidcTokenProvider.builder().sessionName(START_URL).ssoOidcClient(ssoOidcClient); } @Test public void resolveToken_cachedValueNotPresent_throws() { SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThatThrownBy(tokenProvider::resolveToken) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Unable to load"); } // { // "documentation": "Valid token with all fields", // "currentTime": "2021-12-25T13:30:00Z", // "cachedToken": { // "startUrl": "https://d-123.awsapps.com/start", // "region": "us-west-2", // "accessToken": "cachedtoken", // "expiresAt": "2021-12-25T21:30:00Z", // "clientId": "clientid", // "clientSecret": "YSBzZWNyZXQ=", // "registrationExpiresAt": "2022-12-25T13:30:00Z", // "refreshToken": "cachedrefreshtoken" // }, // "expectedToken": { // "token": "cachedtoken", // "expiration": "2021-12-25T21:30:00Z" // } // }, @Test public void standardTest_Valid_token_with_all_fields() { SsoOidcToken token = getDefaultTokenBuilder() .expiresAt(Instant.now().plusSeconds(10000)).registrationExpiresAt(Instant.now().plusSeconds(90000)) .build(); mockTokenManager.storeToken(token); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); SdkToken resolvedToken = tokenProvider.resolveToken(); assertThat(resolvedToken.token()).isEqualTo(token.token()); assertThat(resolvedToken.expirationTime()).isEqualTo(token.expirationTime()); } @Test public void refresh_returns_cached_token_when_service_calls_fails() { SsoOidcToken nearToExpiryToken = getDefaultTokenBuilder() .expiresAt(Instant.now().plusSeconds(5000)).registrationExpiresAt(Instant.now().plusSeconds(10000)) .build(); mockTokenManager.storeToken(nearToExpiryToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenThrow(UnauthorizedClientException.class); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); SdkToken resolvedToken = tokenProvider.resolveToken(); assertThat(resolvedToken.token()).isEqualTo(nearToExpiryToken.token()); assertThat(resolvedToken.expirationTime()).isEqualTo(nearToExpiryToken.expirationTime()); } @Test public void refresh_fails_when_supplier_fails_due_to_Non_service_issues() { SsoOidcToken nearToExpiryToken = getDefaultTokenBuilder() .expiresAt(Instant.now().minusSeconds(2)).registrationExpiresAt(Instant.now().minusSeconds(2)) .build(); mockTokenManager.storeToken(nearToExpiryToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenThrow(SdkClientException.class); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(() -> tokenProvider.resolveToken()); } // { // "documentation": "Minimal valid cached token", // "currentTime": "2021-12-25T13:30:00Z", // "cachedToken": { // "accessToken": "cachedtoken", // "expiresAt": "2021-12-25T21:30:00Z" // }, // "expectedToken": { // "token": "cachedtoken", // "expiration": "2021-12-25T21:30:00Z" // } // }, @Test public void standardTest_Minimal_valid_cached_token() { Instant expiresAt = Instant.now().plusSeconds(3600); SsoOidcToken ssoOidcToken = SsoOidcToken.builder().accessToken("cachedtoken").expiresAt(expiresAt).build(); mockTokenManager.storeToken(ssoOidcToken); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThat(tokenProvider.resolveToken()).isEqualTo(ssoOidcToken); } // { // "documentation": "Minimal expired cached token", // "currentTime": "2021-12-25T13:30:00Z", // "cachedToken": { // "accessToken": "cachedtoken", // "expiresAt": "2021-12-25T13:00:00Z" // }, // "expectedException": "ExpiredToken" // } @Test public void standardTest_Minimal_expired_cached_token() { String startUrl = START_URL; Instant expiresAt = Instant.parse("2021-12-25T13:00:00Z"); SsoOidcToken ssoOidcToken = SsoOidcToken.builder().startUrl(startUrl).clientId("clientId").clientSecret("clientSecret") .accessToken("cachedtoken").expiresAt(expiresAt).build(); mockTokenManager.storeToken(ssoOidcToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))) .thenReturn(CreateTokenResponse.builder().accessToken("cachedtoken") .expiresIn(-1) .build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThatThrownBy(tokenProvider::resolveToken).isInstanceOf(SdkClientException.class).hasMessageContaining("expired"); } // { // "documentation": "Token missing the expiresAt field", // "currentTime": "2021-12-25T13:30:00Z", // "cachedToken": { // "accessToken": "cachedtoken" // }, // "expectedException": "InvalidToken" // }, @Test public void standardTest_Token_missing_the_expiresAt_field() { SsoOidcToken ssoOidcToken = SsoOidcToken.builder() .startUrl(START_URL) .accessToken("cachedtoken").clientId("client").clientSecret("secret") .expiresAt(Instant.parse("2021-12-25T13:00:00Z")) .build(); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))) .thenReturn(CreateTokenResponse.builder().accessToken("cachedtoken") .build()); mockTokenManager.storeToken(ssoOidcToken); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThatThrownBy(tokenProvider::resolveToken) .isInstanceOf(NullPointerException.class) .hasMessageContaining("expiresIn must not be null."); } // { // "documentation": "Token missing the accessToken field", // "currentTime": "2021-12-25T13:30:00Z", // "cachedToken": { // "expiresAt": "2021-12-25T13:00:00Z" // }, // "expectedException": "InvalidToken" // }, @Test public void standardTest_Token_missing_the_accessToken_field() { SsoOidcToken ssoOidcToken = SsoOidcToken.builder() .startUrl(START_URL) .accessToken("cachedtoken").clientId("client").clientSecret("secret") .expiresAt(Instant.parse("2021-12-25T13:00:00Z")) .build(); mockTokenManager.storeToken(ssoOidcToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))) .thenReturn(CreateTokenResponse.builder().expiresIn(3600).build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThatThrownBy(tokenProvider::resolveToken) .isInstanceOf(NullPointerException.class) .hasMessageContaining("accessToken must not be null."); } @Test public void refresh_token_from_service_when_token_outside_expiry_window() { SsoOidcToken nearToExpiryToken = getDefaultTokenBuilder() .expiresAt(Instant.now().plusSeconds(59)) .registrationExpiresAt(Instant.now().plusSeconds(59)).build(); mockTokenManager.storeToken(nearToExpiryToken); int extendedExpiryTimeInSeconds = 120; when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenReturn(getDefaultServiceResponse().expiresIn(extendedExpiryTimeInSeconds).build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); SsoOidcToken resolvedToken = (SsoOidcToken) tokenProvider.resolveToken(); assertThat(resolvedToken.token()).isEqualTo("serviceToken"); assertThat(resolvedToken.refreshToken()).isEqualTo("refreshedToken"); Duration extendedExpiryDate = Duration.between(resolvedToken.expirationTime().get(), Instant.now()); // Base properties of tokens are retained. assertThat(Duration.ofSeconds(extendedExpiryTimeInSeconds)).isGreaterThanOrEqualTo(extendedExpiryDate); assertThat(resolvedToken.clientId()).isEqualTo(nearToExpiryToken.clientId()); assertThat(resolvedToken.clientSecret()).isEqualTo(nearToExpiryToken.clientSecret()); assertThat(resolvedToken.region()).isEqualTo(nearToExpiryToken.region()); assertThat(resolvedToken.startUrl()).isEqualTo(nearToExpiryToken.startUrl()); assertThat(resolvedToken.registrationExpiresAt()).isEqualTo(nearToExpiryToken.registrationExpiresAt()); } @Test public void refresh_token_does_not_fetch_from_service_when_token_inside_expiry_window() { SsoOidcToken cachedDiskToken = getDefaultTokenBuilder() .expiresAt(Instant.now().plusSeconds(120)).registrationExpiresAt(Instant.now().plusSeconds(120)) .build(); mockTokenManager.storeToken(cachedDiskToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenReturn(getDefaultServiceResponse().build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().prefetchTime(Duration.ofSeconds(90)).build(); SdkToken resolvedToken = tokenProvider.resolveToken(); assertThat(resolvedToken).isEqualTo(cachedDiskToken); verify(ssoOidcClient, never()).createToken(any(CreateTokenRequest.class)); } @Test public void token_is_obtained_from_inmemory_when_token_is_within_inmemory_stale_time() { Instant futureExpiryDate = Instant.now().plus(Duration.ofDays(1)); SsoOidcToken cachedDiskToken = getDefaultTokenBuilder() .expiresAt(futureExpiryDate).registrationExpiresAt(Instant.parse("2022-12-25T11:30:00Z")).build(); mockTokenManager.storeToken(cachedDiskToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenReturn(getDefaultServiceResponse().build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); SdkToken resolvedToken = tokenProvider.resolveToken(); assertThat(resolvedToken).isEqualTo(cachedDiskToken); verify(ssoOidcClient, never()).createToken(any(CreateTokenRequest.class)); SdkToken consecutiveToken = tokenProvider.resolveToken(); assertThat(consecutiveToken).isEqualTo(resolvedToken); verify(ssoOidcClient, never()).createToken(any(CreateTokenRequest.class)); } // Test to make sure cache fetches from Cached values. @Test public void token_is_obtained_from_refresher_and_then_refresher_cache_if_its_within_stale_time() { Instant closeToExpireTime = Instant.now().plus(Duration.ofMinutes(4)); SsoOidcToken cachedDiskToken = getDefaultTokenBuilder().accessToken("fourMinutesToExpire") .expiresAt(closeToExpireTime) .registrationExpiresAt(Instant.parse("2022-12-25T11:30:00Z")).build(); mockTokenManager.storeToken(cachedDiskToken); Instant eightMinutesFromNow = Instant.now().plus(Duration.ofMinutes(8)); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenReturn(getDefaultServiceResponse().accessToken( "eightMinutesExpiry").expiresIn((int) eightMinutesFromNow.getEpochSecond()).build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().staleTime(Duration.ofMinutes(7)).build(); SdkToken resolvedToken = tokenProvider.resolveToken(); // Resolves to fresh token assertThat(resolvedToken.token()).isEqualTo("eightMinutesExpiry"); verify(ssoOidcClient, times(1)).createToken(any(CreateTokenRequest.class)); SdkToken consecutiveToken = tokenProvider.resolveToken(); assertThat(consecutiveToken).isEqualTo(resolvedToken); verify(ssoOidcClient, times(1)).createToken(any(CreateTokenRequest.class)); SdkToken thirdTokenAccess = tokenProvider.resolveToken(); assertThat(thirdTokenAccess).isEqualTo(resolvedToken); verify(ssoOidcClient, times(1)).createToken(any(CreateTokenRequest.class)); } @Test public void token_is_retrieved_from_service_when_service_returns_tokens_with_short_expiration() { Instant closeToExpireTime = Instant.now().plus(Duration.ofSeconds(4)); SsoOidcToken cachedDiskToken = getDefaultTokenBuilder().accessToken("fourMinutesToExpire") .expiresAt(closeToExpireTime) .registrationExpiresAt(Instant.parse("2022-12-25T11:30:00Z")) .build(); mockTokenManager.storeToken(cachedDiskToken); CreateTokenResponse eightSecondExpiryToken = getDefaultServiceResponse().accessToken( "eightSecondExpiryToken").expiresIn(8).build(); CreateTokenResponse eightySecondExpiryToken = getDefaultServiceResponse().accessToken( "eightySecondExpiryToken").expiresIn(80).build(); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenReturn(eightSecondExpiryToken).thenReturn(eightySecondExpiryToken); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().staleTime(Duration.ofSeconds(10)).build(); SdkToken resolvedToken = tokenProvider.resolveToken(); assertThat(resolvedToken.token()).contains("eightSecondExpiryToken"); verify(ssoOidcClient, times(1)).createToken(any(CreateTokenRequest.class)); SdkToken consecutiveToken = tokenProvider.resolveToken(); assertThat(consecutiveToken.token()).contains("eightySecondExpiryToken"); verify(ssoOidcClient, times(2)).createToken(any(CreateTokenRequest.class)); } @Test public void token_is_retrieved_automatically_when_prefetch_time_is_set() throws InterruptedException { Instant closeToExpireTime = Instant.now().plus(Duration.ofMillis(3)); SsoOidcToken cachedDiskToken = getDefaultTokenBuilder().accessToken("closeToExpire") .expiresAt(closeToExpireTime) .registrationExpiresAt(Instant.parse("2022-12-25T11:30:00Z")) .build(); mockTokenManager.storeToken(cachedDiskToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))) .thenReturn(getDefaultServiceResponse().accessToken("tokenGreaterThanStaleButLessThanPrefetch").expiresIn(1) .build()) .thenReturn(getDefaultServiceResponse().accessToken("tokenVeryHighExpiry").expiresIn(20000).build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder() .asyncTokenUpdateEnabled(true) .staleTime(Duration.ofSeconds(50)) .prefetchTime(Duration.ofSeconds(300)) .build(); Thread.sleep(100); SdkToken sdkToken = tokenProvider.resolveToken(); assertThat(sdkToken.token()).isEqualTo("tokenGreaterThanStaleButLessThanPrefetch"); Thread.sleep(1000); // Sleep to make sure Async prefetch thread gets picked up and it calls createToken to get new token. verify(ssoOidcClient, times(1)).createToken(any(CreateTokenRequest.class)); SdkToken highExpiryDateToken = tokenProvider.resolveToken(); Thread.sleep(1000); assertThat(highExpiryDateToken.token()).isEqualTo("tokenVeryHighExpiry"); } private CreateTokenResponse someOne(CreateTokenResponse.Builder builder, String tokenGreaterThanStaleButLessThanPrefetch, int i) { return builder.accessToken(tokenGreaterThanStaleButLessThanPrefetch).expiresIn(i).build(); } @Test public void tokenProvider_throws_exception_if_client_is_null() { assertThatExceptionOfType(NullPointerException.class).isThrownBy( () -> SsoOidcTokenProvider.builder().sessionName(START_URL).build()).withMessage("ssoOidcClient must not be null."); } @Test public void tokenProvider_throws_exception_if_start_url_is_null() { assertThatExceptionOfType(NullPointerException.class).isThrownBy( () -> SsoOidcTokenProvider.builder().ssoOidcClient(ssoOidcClient).build()).withMessage("sessionName must not be " + "null."); } private CreateTokenResponse.Builder getDefaultServiceResponse() { return CreateTokenResponse.builder().accessToken( "serviceToken").expiresIn(3600).refreshToken( "refreshedToken"); } private SsoOidcToken.Builder getDefaultTokenBuilder() { return SsoOidcToken.builder() .startUrl(START_URL) .region("us-west-2") .accessToken("cachedtoken") .expiresAt(Instant.parse("2022-12-25T13:30:00Z")) .clientId("clientid") .clientSecret("YSBzZWNyZXQ=") .registrationExpiresAt(Instant.parse("2022-12-25T13:40:00Z")) .refreshToken("cachedrefreshtoken"); } }
5,073
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc/internal
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc/internal/common/SsoOidcTokenRefreshTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.common; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static software.amazon.awssdk.services.ssooidc.internal.SsoOidcTokenProviderTest.deriveCacheKey; import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.function.Supplier; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.auth.token.internal.ProfileTokenProviderLoader; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.services.ssooidc.SsoOidcClient; import software.amazon.awssdk.services.ssooidc.SsoOidcTokenProvider; import software.amazon.awssdk.services.ssooidc.internal.OnDiskTokenManager; import software.amazon.awssdk.services.ssooidc.internal.SsoOidcToken; import software.amazon.awssdk.services.ssooidc.model.CreateTokenRequest; import software.amazon.awssdk.services.ssooidc.model.CreateTokenResponse; import software.amazon.awssdk.services.ssooidc.model.InvalidRequestException; import software.amazon.awssdk.utils.StringInputStream; public abstract class SsoOidcTokenRefreshTestBase { protected static final String REGION = "us-east-1"; protected boolean shouldMockServiceClient; protected SsoOidcClient ssoOidcClient; protected String testStartUrl; protected String testSessionName = "sso-prod"; protected String baseTokenResourceFile; protected ProfileTokenProviderLoader profileTokenProviderLoader; public static final Path DEFAULT_TOKEN_LOCATION = Paths.get(userHomeDirectory(), ".aws", "sso", "cache"); @BeforeEach public void setUp() throws IOException { initializeClient(); initializeProfileProperties(); File cacheDirectory = DEFAULT_TOKEN_LOCATION.toFile(); if(! cacheDirectory.exists()){ cacheDirectory.mkdirs(); } Path file = DEFAULT_TOKEN_LOCATION.resolve(deriveCacheKey(this.testStartUrl)).getFileName(); try { Files.createDirectories(file.getParent()); Files.createFile(file); }catch (Exception e){ } } @AfterAll public static void cleanUp(){ File cacheDirectory = DEFAULT_TOKEN_LOCATION.toFile(); if(cacheDirectory.exists()){ cacheDirectory.delete(); } } protected abstract void initializeClient(); protected void initializeProfileProperties() { String profileContent = "[profile sso-refresh]\n" + "sso_region=us-east-1\n" + "sso_start_url=" + testStartUrl + "\n"; ProfileFile profile = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); profileTokenProviderLoader = new ProfileTokenProviderLoader(() -> profile, "sso-refresh"); } @Test public void tokenReadFromCacheLocation_when_tokenIsWithinExpiry() throws IOException { // Creating a token and saving to disc OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(testSessionName); SsoOidcToken tokenFromJsonFile = getTokenFromJsonFile(baseTokenResourceFile) .expiresAt(Instant.now().plusSeconds(3600)).build(); onDiskTokenManager.storeToken(tokenFromJsonFile); //Creating default token provider SdkTokenProvider awsTokenProvider = defaultTokenProvider(); SdkToken resolvedToken = awsTokenProvider.resolveToken(); assertThat(resolvedToken).isEqualTo(tokenFromJsonFile); } @Test public void tokenReadFromService_And_DiscCacheUpdate_whenTokenInCacheIsExpired() { // Creating a token and saving to disc OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(testSessionName); SsoOidcToken tokenFromJsonFile = getTokenFromJsonFile(baseTokenResourceFile).expiresAt(Instant.now().minusSeconds(10)).build(); onDiskTokenManager.storeToken(tokenFromJsonFile); //Creating default token provider SdkTokenProvider awsTokenProvider = defaultTokenProvider(); SsoOidcToken firstResolvedToken = (SsoOidcToken) awsTokenProvider.resolveToken(); assert_oldCachedToken_isNoSameAs_NewResolvedToken(tokenFromJsonFile, firstResolvedToken); Optional<SsoOidcToken> loadedFromDiscAfterSecondRefresh = onDiskTokenManager.loadToken(); assertThat(loadedFromDiscAfterSecondRefresh).hasValue(firstResolvedToken); // Token taken from Cache SsoOidcToken secondResolvedToken = (SsoOidcToken) awsTokenProvider.resolveToken(); assertThat(firstResolvedToken).isEqualTo(secondResolvedToken); assertThat(secondResolvedToken).isNotEqualTo(tokenFromJsonFile); assertThat(onDiskTokenManager.loadToken()).hasValue(secondResolvedToken); } @Test public void tokenProvider_with_customStaleTime_refreshes_token() throws IOException, InterruptedException { // Creating a token and saving to disc OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(testSessionName); SsoOidcToken tokenFromJsonFile = getTokenFromJsonFile(baseTokenResourceFile).expiresAt(Instant.now().minusSeconds(10)).build(); onDiskTokenManager.storeToken(tokenFromJsonFile); //Creating default token provider SdkTokenProvider awsTokenProvider = tokenProviderBuilderWithClient().staleTime(Duration.ofMinutes(70)).sessionName(testSessionName).build(); // Resolve first Time SsoOidcToken firstResolvedToken = (SsoOidcToken) awsTokenProvider.resolveToken(); assert_oldCachedToken_isNoSameAs_NewResolvedToken(tokenFromJsonFile, firstResolvedToken); Optional<SsoOidcToken> loadedFromDiscAfterSecondRefresh = onDiskTokenManager.loadToken(); assertThat(loadedFromDiscAfterSecondRefresh).hasValue(firstResolvedToken); // Resolve second time Thread.sleep(1000); SsoOidcToken secondResolvedToken = (SsoOidcToken) awsTokenProvider.resolveToken(); assert_oldCachedToken_isNoSameAs_NewResolvedToken(firstResolvedToken, secondResolvedToken); loadedFromDiscAfterSecondRefresh = onDiskTokenManager.loadToken(); assertThat(loadedFromDiscAfterSecondRefresh).hasValue(secondResolvedToken); } @Test public void asyncCredentialUpdateEnabled_prefetch_when_prefetch_time_expired() throws InterruptedException, IOException { // Creating a token and saving to disc OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(testSessionName); SsoOidcToken tokenFromJsonFile = getTokenFromJsonFile(baseTokenResourceFile).build(); onDiskTokenManager.storeToken(tokenFromJsonFile); //Creating default token provider SsoOidcTokenProvider awsTokenProvider = tokenProviderBuilderWithClient().staleTime(Duration.ofMinutes(5)).asyncTokenUpdateEnabled(true) .prefetchTime(Duration.ofMinutes(10)) .sessionName(testSessionName).prefetchTime(Duration.ofMillis(100)).build(); // Make sure that tokens are refreshed from service after the autoRefreshDuration time awsTokenProvider.resolveToken(); SsoOidcToken refreshedTokenInDisc = onDiskTokenManager.loadToken().get(); assert_oldCachedToken_isNoSameAs_NewResolvedToken(tokenFromJsonFile, refreshedTokenInDisc); // Make sure that tokens are refreshed from disc for consecutive refresh awsTokenProvider.resolveToken(); Thread.sleep(100); awsTokenProvider.close(); SsoOidcToken refreshedTokenAfterPrefetch = onDiskTokenManager.loadToken().get(); assertThat(refreshedTokenAfterPrefetch).isEqualTo(refreshedTokenInDisc); } @Test public void tokenNotRefreshed_when_serviceRequestFailure() throws IOException { // Creating a token and saving to disc OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(testSessionName); if (shouldMockServiceClient) { when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenThrow(InvalidRequestException.builder().build()); } SsoOidcToken tokenFromJsonFile = getTokenFromJsonFile(baseTokenResourceFile) .clientId("Incorrect Client Id").expiresAt(Instant.now().minusSeconds(10)).build(); onDiskTokenManager.storeToken(tokenFromJsonFile); //Creating default token provider SdkTokenProvider awsTokenProvider = defaultTokenProvider(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(() -> awsTokenProvider.resolveToken()).withMessage( "Token is expired"); // Cached token is same as before assertThat(onDiskTokenManager.loadToken().get()).isEqualTo(tokenFromJsonFile); } private SdkTokenProvider defaultTokenProvider() { if (shouldMockServiceClient) { return tokenProviderBuilderWithClient().sessionName(testSessionName) .ssoOidcClient(this.ssoOidcClient).build(); } // return profileTokenProviderLoader.tokenProvider().get(); // TODO : remove the custom client before GA. return tokenProviderBuilderWithClient().sessionName(testSessionName) .ssoOidcClient(this.ssoOidcClient).build(); } private SsoOidcTokenProvider.Builder tokenProviderBuilderWithClient() { return SsoOidcTokenProvider.builder().ssoOidcClient(ssoOidcClient); } private void assert_oldCachedToken_isNoSameAs_NewResolvedToken(SsoOidcToken firstResolvedToken, SsoOidcToken secondResolvedToken) { assertThat(secondResolvedToken).isNotEqualTo(firstResolvedToken); assertThat(secondResolvedToken.expirationTime().get()).isAfter(firstResolvedToken.expirationTime().get()); assertThat(secondResolvedToken.token()).isNotEqualTo(firstResolvedToken.token()); assertThat(secondResolvedToken.refreshToken()).isEqualTo(firstResolvedToken.refreshToken()); assertThat(secondResolvedToken.startUrl()).isEqualTo(firstResolvedToken.startUrl()); assertThat(secondResolvedToken.clientId()).isEqualTo(firstResolvedToken.clientId()); assertThat(secondResolvedToken.clientSecret()).isEqualTo(firstResolvedToken.clientSecret()); } protected SsoOidcClient mockSsoOidcClient() { ssoOidcClient = mock(SsoOidcClient.class); SsoOidcToken baseToken = getTokenFromJsonFile(baseTokenResourceFile).build(); Supplier<CreateTokenResponse> responseSupplier = () -> CreateTokenResponse.builder().expiresIn(3600) .accessToken(RandomStringUtils.randomAscii(20)) .refreshToken(baseToken.refreshToken()) .build(); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))) .thenReturn(responseSupplier.get()).thenReturn(responseSupplier.get()).thenReturn(responseSupplier.get()); return ssoOidcClient; } private SsoOidcToken.Builder getTokenFromJsonFile(String fileName) { String content = null; try { content = new String(Files.readAllBytes(Paths.get(fileName))); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Could not load resource file " + fileName, e); } JsonNode jsonNode = JsonNode.parser().parse(content); return SsoOidcToken.builder() .accessToken(jsonNode.field("accessToken").get().asString()) .refreshToken(jsonNode.field("refreshToken").get().asString()) .clientId(jsonNode.field("clientId").get().asString()) .clientSecret(jsonNode.field("clientSecret").get().asString()) .region(jsonNode.field("region").get().asString()) .startUrl(jsonNode.field("startUrl").get().asString()) .expiresAt(Instant.parse(jsonNode.field("expiresAt").get().asString())); } }
5,074
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ssooidc/src/it/java/software/amazon/awssdk/services/ssooidc/SsoOidcTokenRefreshIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; import org.junit.jupiter.api.Disabled; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ssooidc.internal.common.SsoOidcTokenRefreshTestBase; @Disabled("Disabled since base registered tokens comes with expiration date and registration of token requires manual login") public class SsoOidcTokenRefreshIntegrationTest extends SsoOidcTokenRefreshTestBase { // TODO : Remove this gamma specific startUrl and endpoint before GA release. @Override public void initializeClient() { shouldMockServiceClient = false; // Follow registration steps to get the base token. baseTokenResourceFile = "src/it/resources/baseCreateToken.json"; testStartUrl = "http://caws-sono-testing.awsapps.com/start-beta"; ssoOidcClient = SsoOidcClient.builder() .region(Region.of(REGION)) .credentialsProvider(AnonymousCredentialsProvider.create()) .build(); } }
5,075
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc/SsoOidcTokenProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; import java.time.Duration; import java.time.Instant; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.awscore.internal.token.CachedTokenRefresher; import software.amazon.awssdk.awscore.internal.token.TokenManager; import software.amazon.awssdk.awscore.internal.token.TokenRefresher; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.services.ssooidc.internal.OnDiskTokenManager; import software.amazon.awssdk.services.ssooidc.internal.SsoOidcToken; import software.amazon.awssdk.services.ssooidc.internal.SsoOidcTokenTransformer; import software.amazon.awssdk.services.ssooidc.model.CreateTokenRequest; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.Validate; /** * Implementation of {@link SdkTokenProvider} that is capable of loading and * storing SSO tokens to {@code ~/.aws/sso/cache}. This is also capable of * refreshing the cached token via the SSO-OIDC service. */ @SdkPublicApi @ThreadSafe public final class SsoOidcTokenProvider implements SdkTokenProvider, SdkAutoCloseable { private static final Duration DEFAULT_STALE_DURATION = Duration.ofMinutes(1); private static final Duration DEFAULT_PREFETCH_DURATION = Duration.ofMinutes(5); private static final Logger log = Logger.loggerFor(SsoOidcTokenProvider.class); private final TokenManager<SsoOidcToken> onDiskTokenManager; private final TokenRefresher<SsoOidcToken> tokenRefresher; private final SsoOidcClient ssoOidcClient; private final Duration staleTime; private final Duration prefetchTime; private SsoOidcTokenProvider(BuilderImpl builder) { Validate.paramNotNull(builder.sessionName, "sessionName"); Validate.paramNotNull(builder.ssoOidcClient, "ssoOidcClient"); this.ssoOidcClient = builder.ssoOidcClient; this.staleTime = builder.staleTime == null ? DEFAULT_STALE_DURATION : builder.staleTime; this.prefetchTime = builder.prefetchTime == null ? DEFAULT_PREFETCH_DURATION : builder.prefetchTime; this.onDiskTokenManager = OnDiskTokenManager.create(builder.sessionName); this.tokenRefresher = CachedTokenRefresher.builder() .tokenRetriever(getDefaultSsoTokenRetriever(this.ssoOidcClient, this.onDiskTokenManager, this.staleTime, this.prefetchTime)) .exceptionHandler(exceptionHandler()) .prefetchTime(this.prefetchTime) .staleDuration(this.staleTime) .asyncRefreshEnabled(builder.asyncTokenUpdateEnabled) .build(); } private Function<SdkException, SsoOidcToken> exceptionHandler() { return e -> { if (e instanceof AwsServiceException) { log.warn(() -> "Failed to fetch token.", e); // If we fail to get token from service then fetch the previous cached token from disc. return onDiskTokenManager.loadToken() .orElseThrow(() -> SdkClientException.create("Unable to load SSO token")); } throw e; }; } @Override public SdkToken resolveToken() { SsoOidcToken ssoOidcToken = tokenRefresher.refreshIfStaleAndFetch(); if (isExpired(ssoOidcToken)) { throw SdkClientException.create("Token is expired"); } return ssoOidcToken; } public static Builder builder() { return new BuilderImpl(); } @Override public void close() { tokenRefresher.close(); } public interface Builder { /** * The sessionName used to retrieve the SSO token. */ Builder sessionName(String sessionName); /** * * Client to fetch token from SSO OIDC service. */ Builder ssoOidcClient(SsoOidcClient ssoOidcClient); /** * Configure the amount of time, relative to Sso-Oidc token , that the cached tokens in refresher are considered * stale and should no longer be used. * * <p>By default, this is 5 minute.</p> */ Builder staleTime(Duration onDiskStaleDuration); /** * * Configure the amount of time, relative to Sso-Oidc token , that the cached tokens in refresher are considered * prefetched from service.. */ Builder prefetchTime(Duration prefetchTime); /** * Configure whether the provider should fetch tokens asynchronously in the background. If this is true, * threads are less likely to block when token are loaded, but additional resources are used to maintain * the provider. * * <p>By default, this is disabled.</p> */ Builder asyncTokenUpdateEnabled(Boolean asyncTokenUpdateEnabled); SsoOidcTokenProvider build(); } private boolean isExpired(SsoOidcToken token) { Instant expiration = token.expirationTime().get(); Instant now = Instant.now(); return now.isAfter(expiration); } private static boolean isWithinRefreshWindow(SsoOidcToken token, Duration staleTime) { Instant expiration = token.expirationTime().get(); Instant now = Instant.now(); return expiration.isAfter(now.plus(staleTime)); } private static void validateToken(SsoOidcToken token) { Validate.notNull(token.token(), "token cannot be null"); Validate.notNull(token.expirationTime(), "expirationTime cannot be null"); } private static class BuilderImpl implements Builder { private String sessionName; private SsoOidcClient ssoOidcClient; private Duration staleTime; private Duration prefetchTime; private Boolean asyncTokenUpdateEnabled = false; private BuilderImpl() { } @Override public Builder sessionName(String sessionName) { this.sessionName = sessionName; return this; } @Override public Builder ssoOidcClient(SsoOidcClient ssoOidcClient) { this.ssoOidcClient = ssoOidcClient; 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 asyncTokenUpdateEnabled(Boolean asyncTokenUpdateEnabled) { this.asyncTokenUpdateEnabled = asyncTokenUpdateEnabled; return this; } @Override public SsoOidcTokenProvider build() { return new SsoOidcTokenProvider(this); } } private static Supplier<SsoOidcToken> getDefaultSsoTokenRetriever(SsoOidcClient ssoOidcClient, TokenManager<SsoOidcToken> tokenManager, Duration staleTime, Duration prefetchTime) { return () -> { SsoOidcToken baseToken = tokenManager.loadToken() .orElseThrow(() -> SdkClientException.create("Unable to load SSO token")); validateToken(baseToken); if (isWithinRefreshWindow(baseToken, staleTime) && isWithinRefreshWindow(baseToken, prefetchTime)) { return baseToken; } SsoOidcTokenTransformer ssoOidcTokenTransformer = SsoOidcTokenTransformer.create(baseToken); SsoOidcToken refreshToken = ssoOidcTokenTransformer.transform(ssoOidcClient.createToken( CreateTokenRequest.builder() .grantType("refresh_token") .clientId(baseToken.clientId()) .clientSecret(baseToken.clientSecret()) .refreshToken(baseToken.refreshToken()) .build())); tokenManager.storeToken(refreshToken); return refreshToken; }; } }
5,076
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc/SsoOidcProfileTokenProviderFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; import java.util.Objects; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.token.credentials.ChildProfileTokenProviderFactory; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.core.exception.SdkClientException; 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.utils.IoUtils; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Factory for creating {@link SsoOidcTokenProvider}. */ @SdkProtectedApi public final class SsoOidcProfileTokenProviderFactory implements ChildProfileTokenProviderFactory { private static final String MISSING_PROPERTY_ERROR_FORMAT = "'%s' must be set to use bearer tokens loading in the " + "'%s' profile."; @Override public SdkTokenProvider create(ProfileFile profileFile, Profile profile) { return new SsoOidcProfileTokenProvider(profileFile, profile); } public SdkTokenProvider create(Supplier<ProfileFile> profileFile, String profileName) { return new SsoOidcSuppliedProfileTokenProvider(profileFile, profileName); } private static final class SsoOidcSuppliedProfileTokenProvider implements SdkTokenProvider, SdkAutoCloseable { private final Supplier<ProfileFile> profileFile; private final String profileName; private volatile ProfileFile currentProfileFile; private volatile SsoOidcProfileTokenProvider currentTokenProvider; private SsoOidcSuppliedProfileTokenProvider(Supplier<ProfileFile> profileFile, String profileName) { this.profileFile = profileFile; this.profileName = profileName; } @Override public SdkToken resolveToken() { return sdkTokenProvider().resolveToken(); } private SdkTokenProvider sdkTokenProvider() { ProfileFile profileFileInstance = profileFile.get(); if (!Objects.equals(profileFileInstance, currentProfileFile)) { synchronized (this) { if (!Objects.equals(profileFileInstance, currentProfileFile)) { Profile profileInstance = resolveProfile(profileFileInstance, profileName); currentProfileFile = profileFileInstance; currentTokenProvider = new SsoOidcProfileTokenProvider(profileFileInstance, profileInstance); } } } return currentTokenProvider; } private Profile resolveProfile(ProfileFile profileFile, String profileName) { return profileFile.profile(profileName) .orElseThrow(() -> { String errorMessage = String.format("Profile file contained no information for profile" + "'%s': %s", profileName, profileFile); return SdkClientException.builder().message(errorMessage).build(); }); } @Override public void close() { IoUtils.closeQuietly(currentTokenProvider, null); } } /** * A wrapper for a {@link SdkTokenProvider} that is returned by this factory when {@link #create(ProfileFile,Profile)} is * invoked. This wrapper is important because it ensures the token provider is closed when it is no longer needed. */ private static final class SsoOidcProfileTokenProvider implements SdkTokenProvider, SdkAutoCloseable { private final SsoOidcTokenProvider sdkTokenProvider; private SsoOidcProfileTokenProvider(ProfileFile profileFile, Profile profile) { String profileSsoSectionName = profile.property( ProfileSection.SSO_SESSION .getPropertyKeyName()).orElseThrow(() -> new IllegalStateException( "Profile " + profile.name() + " does not have sso_session property")); Profile ssoProfile = profileFile.getSection( ProfileSection.SSO_SESSION.getSectionTitle(), profileSsoSectionName).orElseThrow(() -> new IllegalArgumentException( "Sso-session section not found with sso-session title " + profileSsoSectionName + ".")); String startUrl = requireProperty(ssoProfile, ProfileProperty.SSO_START_URL); String region = requireProperty(ssoProfile, ProfileProperty.SSO_REGION); if (ssoProfile.property(ProfileProperty.SSO_ACCOUNT_ID).isPresent() || ssoProfile.property(ProfileProperty.SSO_ROLE_NAME).isPresent()) { throw new IllegalStateException("sso_account_id or sso_role_name properties must not be defined for" + "profiles that provide ssooidc providers"); } this.sdkTokenProvider = SsoOidcTokenProvider.builder() .sessionName(ssoProfile.name()) .ssoOidcClient(SsoOidcClient.builder() .region(Region.of(region)) .credentialsProvider( AnonymousCredentialsProvider.create()) .build()) .build(); } private String requireProperty(Profile profile, String requiredProperty) { return profile.property(requiredProperty) .orElseThrow(() -> new IllegalArgumentException(String.format(MISSING_PROPERTY_ERROR_FORMAT, requiredProperty, profile.name()))); } @Override public SdkToken resolveToken() { return this.sdkTokenProvider.resolveToken(); } @Override public void close() { IoUtils.closeQuietly(sdkTokenProvider, null); } } }
5,077
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc/internal/SsoOidcTokenTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.time.Instant; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.internal.token.TokenTransformer; import software.amazon.awssdk.services.ssooidc.model.CreateTokenResponse; import software.amazon.awssdk.utils.Validate; /** * Transformer to transform CreateTokenResponse to SsoToken. */ @SdkInternalApi public final class SsoOidcTokenTransformer implements TokenTransformer<SsoOidcToken, CreateTokenResponse> { private final SsoOidcToken baseToken; private SsoOidcTokenTransformer(SsoOidcToken baseToken) { Validate.notNull(baseToken.startUrl(), "startUrl is null "); Validate.notNull(baseToken.clientId(), "clientId is null "); Validate.notNull(baseToken.clientSecret(), "clientSecret is null "); this.baseToken = baseToken; } public static SsoOidcTokenTransformer create(SsoOidcToken baseToken) { Validate.paramNotNull(baseToken, "baseToken"); return new SsoOidcTokenTransformer(baseToken); } @Override public SsoOidcToken transform(CreateTokenResponse awsResponse) { Validate.paramNotNull(awsResponse.accessToken(), "accessToken"); Validate.paramNotNull(awsResponse.expiresIn(), "expiresIn"); return SsoOidcToken.builder() .accessToken(awsResponse.accessToken()) .refreshToken(awsResponse.refreshToken()) .expiresAt(awsResponse.expiresIn() != null ? Instant.now().plusSeconds(awsResponse.expiresIn()) : null) .startUrl(baseToken.startUrl()) .registrationExpiresAt(baseToken.registrationExpiresAt()) .region(baseToken.region()) .clientSecret(baseToken.clientSecret()) .clientId(baseToken.clientId()) .build(); } }
5,078
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc/internal/OnDiskTokenManager.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.internal.token.TokenManager; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.thirdparty.jackson.core.JsonGenerator; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Validate; /** * Implementation of {@link TokenManager} that can load and store SSO tokens * from and to disk. */ @SdkInternalApi public final class OnDiskTokenManager implements TokenManager<SsoOidcToken> { private static final Path DEFAULT_TOKEN_LOCATION = Paths.get(userHomeDirectory(), ".aws", "sso", "cache"); private final JsonNodeParser jsonParser = JsonNodeParser.builder().removeErrorLocations(true).build(); private final String sessionName; private final Path tokenLocation; private OnDiskTokenManager(Path cacheLocation, String sessionName) { Validate.notNull(cacheLocation, "cacheLocation must not be null"); this.sessionName = Validate.notNull(sessionName, "sessionName must not be null"); Validate.notBlank(sessionName, "sessionName must not be blank"); String cacheKey = deriveCacheKey(sessionName); this.tokenLocation = cacheLocation.resolve(cacheKey + ".json"); } @Override public Optional<SsoOidcToken> loadToken() { if (!Files.exists(tokenLocation)) { return Optional.empty(); } try (InputStream cachedTokenStream = Files.newInputStream(tokenLocation)) { String content = IoUtils.toUtf8String(cachedTokenStream); return Optional.of(unmarshalToken(content)); } catch (IOException e) { throw SdkClientException.create("Failed to load cached token at " + tokenLocation, e); } } @Override public void storeToken(SsoOidcToken token) { try (OutputStream os = Files.newOutputStream(tokenLocation)) { os.write(marshalToken(token)); } catch (IOException e) { throw SdkClientException.create("Unable to write token to location " + tokenLocation, e); } } @Override public void close() { } public static OnDiskTokenManager create(Path cacheLocation, String sessionName) { return new OnDiskTokenManager(cacheLocation, sessionName); } public static OnDiskTokenManager create(String sessionName) { return create(DEFAULT_TOKEN_LOCATION, sessionName); } private SsoOidcToken unmarshalToken(String contents) { JsonNode node = jsonParser.parse(contents); SsoOidcToken.Builder tokenBuilder = SsoOidcToken.builder(); JsonNode accessToken = node.field("accessToken") .orElseThrow(() -> SdkClientException.create("required member 'accessToken' not found")); tokenBuilder.accessToken(accessToken.text()); JsonNode expiresAt = node.field("expiresAt") .orElseThrow(() -> SdkClientException.create("required member 'expiresAt' not found")); tokenBuilder.expiresAt(Instant.parse(expiresAt.text())); node.field("refreshToken").map(JsonNode::text).ifPresent(tokenBuilder::refreshToken); node.field("clientId").map(JsonNode::text).ifPresent(tokenBuilder::clientId); node.field("clientSecret").map(JsonNode::text).ifPresent(tokenBuilder::clientSecret); node.field("registrationExpiresAt") .map(JsonNode::text) .map(Instant::parse) .ifPresent(tokenBuilder::registrationExpiresAt); node.field("region").map(JsonNode::text).ifPresent(tokenBuilder::region); node.field("startUrl").map(JsonNode::text).ifPresent(tokenBuilder::startUrl); return tokenBuilder.build(); } private byte[] marshalToken(SsoOidcToken token) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = null; try { generator = JsonNodeParser.DEFAULT_JSON_FACTORY.createGenerator(baos); generator.writeStartObject(); generator.writeStringField("accessToken", token.token()); generator.writeStringField("expiresAt", DateTimeFormatter.ISO_INSTANT.format(token.expirationTime().get())); if (token.refreshToken() != null) { generator.writeStringField("refreshToken", token.refreshToken()); } if (token.clientId() != null) { generator.writeStringField("clientId", token.clientId()); } if (token.clientSecret() != null) { generator.writeStringField("clientSecret", token.clientSecret()); } if (token.registrationExpiresAt() != null) { generator.writeStringField("registrationExpiresAt", DateTimeFormatter.ISO_INSTANT.format(token.registrationExpiresAt())); } if (token.region() != null) { generator.writeStringField("region", token.region()); } if (token.startUrl() != null) { generator.writeStringField("startUrl", token.startUrl()); } generator.writeEndObject(); generator.close(); return baos.toByteArray(); } catch (IOException e) { throw SdkClientException.create("Unable to marshal token to JSON", e); } finally { if (generator != null) { IoUtils.closeQuietly(generator, null); } } } private static String deriveCacheKey(String sessionName) { try { MessageDigest sha1 = MessageDigest.getInstance("sha1"); sha1.update(sessionName.getBytes(StandardCharsets.UTF_8)); return BinaryUtils.toHex(sha1.digest()).toLowerCase(Locale.ENGLISH); } catch (NoSuchAlgorithmException e) { throw SdkClientException.create("Unable to derive cache key", e); } } }
5,079
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc/internal/SsoOidcToken.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.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; /** * Represents a cached SSO token. * * <code> * { * "accessToken": "string", * "expiresAt": "2019-11-14T04:05:45Z", * "refreshToken": "string", * "clientId": "ABCDEFG323242423121312312312312312", * "clientSecret": "ABCDE123", * "registrationExpiresAt": "2022-03-06T19:53:17Z", * "region": "us-west-2", * "startUrl": "https://d-abc123.awsapps.com/start" * } * </code> */ @SdkInternalApi public final class SsoOidcToken implements SdkToken { private final String accessToken; private final Instant expiresAt; private final String refreshToken; private final String clientId; private final String clientSecret; private final Instant registrationExpiresAt; private final String region; private final String startUrl; private SsoOidcToken(BuilderImpl builder) { Validate.paramNotNull(builder.accessToken, "accessToken"); Validate.paramNotNull(builder.expiresAt, "expiresAt"); this.accessToken = builder.accessToken; this.expiresAt = builder.expiresAt; this.refreshToken = builder.refreshToken; this.clientId = builder.clientId; this.clientSecret = builder.clientSecret; this.registrationExpiresAt = builder.registrationExpiresAt; this.region = builder.region; this.startUrl = builder.startUrl; } @Override public String token() { return accessToken; } @Override public Optional<Instant> expirationTime() { return Optional.of(expiresAt); } public String refreshToken() { return refreshToken; } public String clientId() { return clientId; } public String clientSecret() { return clientSecret; } public Instant registrationExpiresAt() { return registrationExpiresAt; } public String region() { return region; } public String startUrl() { return startUrl; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SsoOidcToken ssoOidcToken = (SsoOidcToken) o; return Objects.equals(accessToken, ssoOidcToken.accessToken) && Objects.equals(expiresAt, ssoOidcToken.expiresAt) && Objects.equals(refreshToken, ssoOidcToken.refreshToken) && Objects.equals(clientId, ssoOidcToken.clientId) && Objects.equals(clientSecret, ssoOidcToken.clientSecret) && Objects.equals(registrationExpiresAt, ssoOidcToken.registrationExpiresAt) && Objects.equals(region, ssoOidcToken.region) && Objects.equals(startUrl, ssoOidcToken.startUrl); } @Override public int hashCode() { int result = Objects.hashCode(accessToken); result = 31 * result + Objects.hashCode(expiresAt); result = 31 * result + Objects.hashCode(refreshToken); result = 31 * result + Objects.hashCode(clientId); result = 31 * result + Objects.hashCode(clientSecret); result = 31 * result + Objects.hashCode(registrationExpiresAt); result = 31 * result + Objects.hashCode(region); result = 31 * result + Objects.hashCode(startUrl); return result; } @Override public String toString() { return ToString.builder("SsoOidcToken") .add("accessToken", accessToken) .add("expiresAt", expiresAt) .add("refreshToken", refreshToken) .add("clientId", clientId) .add("clientSecret", clientSecret) .add("registrationExpiresAt", registrationExpiresAt) .add("region", region) .add("startUrl", startUrl) .build(); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { Builder accessToken(String accessToken); Builder expiresAt(Instant expiresAt); Builder refreshToken(String refreshToken); Builder clientId(String clientId); Builder clientSecret(String clientSecret); Builder registrationExpiresAt(Instant registrationExpiresAt); Builder region(String region); Builder startUrl(String startUrl); SsoOidcToken build(); } private static class BuilderImpl implements Builder { private String accessToken; private Instant expiresAt; private String refreshToken; private String clientId; private String clientSecret; private Instant registrationExpiresAt; private String region; private String startUrl; @Override public Builder accessToken(String accessToken) { this.accessToken = accessToken; return this; } @Override public Builder expiresAt(Instant expiresAt) { this.expiresAt = expiresAt; return this; } @Override public Builder refreshToken(String refreshToken) { this.refreshToken = refreshToken; return this; } @Override public Builder clientId(String clientId) { this.clientId = clientId; return this; } @Override public Builder clientSecret(String clientSecret) { this.clientSecret = clientSecret; return this; } @Override public Builder registrationExpiresAt(Instant registrationExpiresAt) { this.registrationExpiresAt = registrationExpiresAt; return this; } @Override public Builder region(String region) { this.region = region; return this; } @Override public Builder startUrl(String startUrl) { this.startUrl = startUrl; return this; } @Override public SsoOidcToken build() { return new SsoOidcToken(this); } } }
5,080
0
Create_ds/aws-sdk-java-v2/services/waf/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/waf/src/it/java/software/amazon/awssdk/services/waf/WafIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.waf; import java.io.IOException; import java.time.Duration; import java.util.List; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.waf.model.ChangeAction; import software.amazon.awssdk.services.waf.model.CreateIpSetRequest; import software.amazon.awssdk.services.waf.model.CreateIpSetResponse; import software.amazon.awssdk.services.waf.model.GetChangeTokenRequest; import software.amazon.awssdk.services.waf.model.GetChangeTokenResponse; import software.amazon.awssdk.services.waf.model.GetIpSetRequest; import software.amazon.awssdk.services.waf.model.GetIpSetResponse; import software.amazon.awssdk.services.waf.model.IPSet; import software.amazon.awssdk.services.waf.model.IPSetDescriptor; import software.amazon.awssdk.services.waf.model.IPSetDescriptorType; import software.amazon.awssdk.services.waf.model.IPSetUpdate; import software.amazon.awssdk.services.waf.model.ListIpSetsRequest; import software.amazon.awssdk.services.waf.model.ListIpSetsResponse; import software.amazon.awssdk.services.waf.model.UpdateIpSetRequest; import software.amazon.awssdk.services.waf.model.WafNonEmptyEntityException; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.testutils.service.AwsTestBase; public class WafIntegrationTest extends AwsTestBase { private static final String IP_SET_NAME = "java-sdk-ipset-" + System.currentTimeMillis(); private static final String IP_ADDRESS_RANGE = "192.0.2.0/24"; private static WafClient client = null; private static String ipSetId = null; @BeforeClass public static void setup() throws IOException { FixedDelayBackoffStrategy fixedBackoffStrategy = FixedDelayBackoffStrategy.create(Duration.ofSeconds(30)); setUpCredentials(); client = WafClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.AWS_GLOBAL) .overrideConfiguration(cfg -> cfg.retryPolicy(r -> r.backoffStrategy(fixedBackoffStrategy))) .build(); } @AfterClass public static void tearDown() throws IOException { if (client != null) { deleteIpSet(); } } private static void deleteIpSet() { if (ipSetId != null) { Waiter.run(() -> client.deleteIPSet(r -> r.ipSetId(ipSetId).changeToken(newChangeToken()))) .ignoringException(WafNonEmptyEntityException.class) .orFailAfter(Duration.ofMinutes(2)); } } private static String newChangeToken() { GetChangeTokenResponse result = client.getChangeToken(GetChangeTokenRequest.builder().build()); return result.changeToken(); } @Test public void testOperations() throws InterruptedException { ipSetId = testCreateIpSet(); testGetIpSet(); testUpdateIpSet(); } private String testCreateIpSet() { final String changeToken = newChangeToken(); CreateIpSetResponse createResult = client.createIPSet(CreateIpSetRequest.builder() .changeToken(changeToken) .name(IP_SET_NAME).build()); Assert.assertEquals(changeToken, createResult.changeToken()); final IPSet ipSet = createResult.ipSet(); Assert.assertNotNull(ipSet); Assert.assertEquals(IP_SET_NAME, ipSet.name()); Assert.assertTrue(ipSet.ipSetDescriptors().isEmpty()); Assert.assertNotNull(ipSet.ipSetId()); return ipSet.ipSetId(); } private void testGetIpSet() { GetIpSetResponse getResult = client.getIPSet(GetIpSetRequest.builder() .ipSetId(ipSetId) .build()); IPSet ipSet = getResult.ipSet(); Assert.assertNotNull(ipSet); Assert.assertEquals(IP_SET_NAME, ipSet.name()); Assert.assertTrue(ipSet.ipSetDescriptors().isEmpty()); Assert.assertNotNull(ipSet.ipSetId()); Assert.assertEquals(ipSetId, ipSet.ipSetId()); ListIpSetsResponse listResult = client.listIPSets(ListIpSetsRequest.builder() .limit(1) .build()); Assert.assertNotNull(listResult.ipSets()); Assert.assertFalse(listResult.ipSets().isEmpty()); } private void testUpdateIpSet() { final IPSetDescriptor ipSetDescriptor = IPSetDescriptor.builder() .type(IPSetDescriptorType.IPV4) .value(IP_ADDRESS_RANGE) .build(); final IPSetUpdate ipToInsert = IPSetUpdate.builder() .ipSetDescriptor(ipSetDescriptor) .action(ChangeAction.INSERT) .build(); client.updateIPSet(UpdateIpSetRequest.builder() .ipSetId(ipSetId) .changeToken(newChangeToken()) .updates(ipToInsert).build()); GetIpSetResponse getResult = client.getIPSet(GetIpSetRequest.builder() .ipSetId(ipSetId).build()); IPSet ipSet = getResult.ipSet(); Assert.assertNotNull(ipSet); Assert.assertEquals(IP_SET_NAME, ipSet.name()); Assert.assertNotNull(ipSet.ipSetId()); Assert.assertEquals(ipSetId, ipSet.ipSetId()); List<IPSetDescriptor> actualList = ipSet.ipSetDescriptors(); Assert.assertFalse(actualList.isEmpty()); Assert.assertEquals(1, actualList.size()); IPSetDescriptor actualIpSetDescriptor = actualList.get(0); Assert.assertEquals(ipSetDescriptor.type(), actualIpSetDescriptor.type()); Assert.assertEquals(ipSetDescriptor.value(), actualIpSetDescriptor.value()); final IPSetUpdate ipToDelete = IPSetUpdate.builder() .ipSetDescriptor(ipSetDescriptor) .action(ChangeAction.DELETE) .build(); client.updateIPSet(UpdateIpSetRequest.builder() .ipSetId(ipSetId) .changeToken(newChangeToken()) .updates(ipToDelete) .build()); } }
5,081
0
Create_ds/aws-sdk-java-v2/services/waf/src/it/java/software/amazon/awssdk/services/waf
Create_ds/aws-sdk-java-v2/services/waf/src/it/java/software/amazon/awssdk/services/waf/regional/WafRegionalIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.waf.regional; import org.junit.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.waf.model.ListResourcesForWebAclRequest; import software.amazon.awssdk.services.waf.model.WafNonexistentItemException; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class WafRegionalIntegrationTest extends AwsIntegrationTestBase { /** * Calls an operation specific to WAF Regional. If we get a modeled exception back then we called the * right service. */ @Test(expected = WafNonexistentItemException.class) public void smokeTest() { final WafRegionalClient client = WafRegionalClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.US_WEST_2) .build(); client.listResourcesForWebACL(ListResourcesForWebAclRequest.builder().webACLId("foo").build()); } }
5,082
0
Create_ds/aws-sdk-java-v2/services/directconnect/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/directconnect/src/it/java/software/amazon/awssdk/services/directconnect/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.directconnect; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; public class IntegrationTestBase extends AwsTestBase { protected static DirectConnectClient dc; @BeforeClass public static void setUp() throws IOException { setUpCredentials(); dc = DirectConnectClient.builder() .region(Region.US_WEST_1) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); } }
5,083
0
Create_ds/aws-sdk-java-v2/services/directconnect/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/directconnect/src/it/java/software/amazon/awssdk/services/directconnect/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.directconnect; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.SdkGlobalTime; import software.amazon.awssdk.services.directconnect.model.CreateConnectionRequest; import software.amazon.awssdk.services.directconnect.model.CreateConnectionResponse; import software.amazon.awssdk.services.directconnect.model.DeleteConnectionRequest; import software.amazon.awssdk.services.directconnect.model.DescribeConnectionsRequest; import software.amazon.awssdk.services.directconnect.model.DescribeConnectionsResponse; import software.amazon.awssdk.services.directconnect.model.DescribeLocationsRequest; import software.amazon.awssdk.services.directconnect.model.DescribeLocationsResponse; import software.amazon.awssdk.services.directconnect.model.DirectConnectException; import software.amazon.awssdk.services.directconnect.model.Location; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.utils.Logger; public class ServiceIntegrationTest extends IntegrationTestBase { private static final Logger log = Logger.loggerFor(ServiceIntegrationTest.class); private static final String CONNECTION_NAME = "test-connection-name"; private static final String EXPECTED_CONNECTION_STATUS = "requested"; private static String connectionId; @BeforeClass public static void setup() { CreateConnectionResponse result = dc.createConnection(CreateConnectionRequest.builder() .connectionName(CONNECTION_NAME) .bandwidth("1Gbps") .location("EqSV5") .build()); connectionId = result.connectionId(); } @AfterClass public static void tearDown() { boolean cleanedUp = Waiter.run(() -> dc.deleteConnection(r -> r.connectionId(connectionId))) .ignoringException(DirectConnectException.class) .orReturnFalse(); if (!cleanedUp) { log.warn(() -> "Failed to clean up connection: " + connectionId); } } @Test public void describeLocations_ReturnsNonEmptyList() { DescribeLocationsResponse describeLocations = dc.describeLocations(DescribeLocationsRequest.builder().build()); assertTrue(describeLocations.locations().size() > 0); for (Location location : describeLocations.locations()) { assertNotNull(location.locationCode()); assertNotNull(location.locationName()); } } @Test public void describeConnections_ReturnsNonEmptyList() { DescribeConnectionsResponse describeConnectionsResult = dc.describeConnections(DescribeConnectionsRequest.builder().build()); assertTrue(describeConnectionsResult.connections().size() > 0); assertNotNull(describeConnectionsResult.connections().get(0).connectionId()); assertNotNull(describeConnectionsResult.connections().get(0).connectionName()); assertNotNull(describeConnectionsResult.connections().get(0).connectionState()); assertNotNull(describeConnectionsResult.connections().get(0).location()); assertNotNull(describeConnectionsResult.connections().get(0).region()); } @Test public void describeConnections_FilteredByCollectionId_ReturnsOnlyOneConnection() { DescribeConnectionsResponse describeConnectionsResult = dc.describeConnections(DescribeConnectionsRequest.builder() .connectionId(connectionId) .build()); assertThat(describeConnectionsResult.connections(), hasSize(1)); assertEquals(connectionId, describeConnectionsResult.connections().get(0).connectionId()); assertEquals(EXPECTED_CONNECTION_STATUS, describeConnectionsResult.connections().get(0).connectionStateAsString()); } /** * In the following test, we purposely setting the time offset to trigger a clock skew error. * The time offset must be fixed and then we validate the global value for time offset has been * update. */ @Test public void testClockSkew() { SdkGlobalTime.setGlobalTimeOffset(3600); DirectConnectClient clockSkewClient = DirectConnectClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); clockSkewClient.describeConnections(DescribeConnectionsRequest.builder().build()); assertTrue(SdkGlobalTime.getGlobalTimeOffset() < 60); } }
5,084
0
Create_ds/aws-sdk-java-v2/services/docdb/src/test/java/software/amazon/awssdk/services/docdb
Create_ds/aws-sdk-java-v2/services/docdb/src/test/java/software/amazon/awssdk/services/docdb/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.docdb.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.net.URI; import java.util.List; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.docdb.DocDbClient; @RunWith(MockitoJUnitRunner.class) public class PresignRequestWireMockTest { @ClassRule public static final WireMockRule WIRE_MOCK = new WireMockRule(0); public static DocDbClient client; @BeforeClass public static void setup() { client = DocDbClient.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"); } }
5,085
0
Create_ds/aws-sdk-java-v2/services/docdb/src/test/java/software/amazon/awssdk/services/docdb
Create_ds/aws-sdk-java-v2/services/docdb/src/test/java/software/amazon/awssdk/services/docdb/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.docdb.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.docdb.model.CopyDbClusterSnapshotRequest; import software.amazon.awssdk.services.docdb.model.DocDbRequest; import software.amazon.awssdk.services.docdb.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, DocDbRequest request, SdkHttpFullRequest httpRequest) { InterceptorContext context = InterceptorContext.builder().request(request).httpRequest(httpRequest).build(); return interceptor.modifyHttpRequest(context, executionAttributes()); } }
5,086
0
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb/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.docdb.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.docdb.model.CopyDbClusterSnapshotRequest; import software.amazon.awssdk.services.docdb.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); } }; } }
5,087
0
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb/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.docdb.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.docdb.model.CreateDbClusterRequest; import software.amazon.awssdk.services.docdb.transform.CreateDbClusterRequestMarshaller; /** * Handler for pre-signing {@link CreateDbClusterRequest}. */ @SdkInternalApi public final class CreateDbClusterPresignInterceptor extends RdsPresignInterceptor<CreateDbClusterRequest> { public static final CreateDbClusterRequestMarshaller MARSHALLER = new CreateDbClusterRequestMarshaller(PROTOCOL_FACTORY); public CreateDbClusterPresignInterceptor() { super(CreateDbClusterRequest.class); } @Override protected PresignableRequest adaptRequest(final CreateDbClusterRequest originalRequest) { return new PresignableRequest() { @Override public String getSourceRegion() { return originalRequest.sourceRegion(); } @Override public SdkHttpFullRequest marshall() { return MARSHALLER.marshall(originalRequest); } }; } }
5,088
0
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb/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.docdb.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.docdb.model.DocDbRequest; 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 DocDbRequest> 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(); } }
5,089
0
Create_ds/aws-sdk-java-v2/services/ses/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ses/src/it/java/software/amazon/awssdk/services/ses/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.ses; import static org.junit.Assert.fail; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.junit.BeforeClass; import software.amazon.awssdk.services.ses.model.ListVerifiedEmailAddressesRequest; import software.amazon.awssdk.services.ses.model.ListVerifiedEmailAddressesResponse; import software.amazon.awssdk.services.ses.model.VerifyEmailAddressRequest; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for AWS Email integration tests; responsible for loading AWS account credentials for * running the tests, instantiating clients, etc. */ public abstract class IntegrationTestBase extends AwsTestBase { public static final String HUDSON_EMAIL_LIST = "no-reply@amazon.com"; protected static final String RAW_MESSAGE_FILE_PATH = "/software/amazon/awssdk/services/email/rawMimeMessage.txt"; public static String DESTINATION; public static String SOURCE; protected static SesClient email; /** * Loads the AWS account info for the integration tests and creates client objects for tests to * use. */ @BeforeClass public static void setUp() throws FileNotFoundException, IOException { setUpCredentials(); if (DESTINATION == null) { DESTINATION = System.getProperty("user.name").equals("webuser") ? HUDSON_EMAIL_LIST : System.getProperty("user.name") + "@amazon.com"; SOURCE = DESTINATION; } email = SesClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } protected static void sendVerificationEmail() { ListVerifiedEmailAddressesResponse verifiedEmails = email.listVerifiedEmailAddresses(ListVerifiedEmailAddressesRequest.builder().build()); for (String email : verifiedEmails.verifiedEmailAddresses()) { if (email.equals(DESTINATION)) { return; } } email.verifyEmailAddress(VerifyEmailAddressRequest.builder().emailAddress(DESTINATION).build()); fail("Please check your email and verify your email address."); } protected String loadRawMessage(String messagePath) throws Exception { String rawMessage = IOUtils.toString(getClass().getResourceAsStream(messagePath)); rawMessage = rawMessage.replace("@DESTINATION@", DESTINATION); rawMessage = rawMessage.replace("@SOURCE@", SOURCE); return rawMessage; } protected InputStream loadRawMessageAsStream(String messagePath) throws Exception { return IOUtils.toInputStream(loadRawMessage(messagePath)); } }
5,090
0
Create_ds/aws-sdk-java-v2/services/ses/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ses/src/it/java/software/amazon/awssdk/services/ses/EmailIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ses; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; 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.ses.model.Body; import software.amazon.awssdk.services.ses.model.Content; import software.amazon.awssdk.services.ses.model.DeleteIdentityRequest; import software.amazon.awssdk.services.ses.model.Destination; import software.amazon.awssdk.services.ses.model.GetIdentityVerificationAttributesRequest; import software.amazon.awssdk.services.ses.model.GetIdentityVerificationAttributesResponse; import software.amazon.awssdk.services.ses.model.GetSendQuotaRequest; import software.amazon.awssdk.services.ses.model.GetSendQuotaResponse; import software.amazon.awssdk.services.ses.model.IdentityType; import software.amazon.awssdk.services.ses.model.IdentityVerificationAttributes; import software.amazon.awssdk.services.ses.model.ListIdentitiesRequest; import software.amazon.awssdk.services.ses.model.Message; import software.amazon.awssdk.services.ses.model.MessageRejectedException; import software.amazon.awssdk.services.ses.model.SendEmailRequest; import software.amazon.awssdk.services.ses.model.VerificationStatus; import software.amazon.awssdk.services.ses.model.VerifyDomainIdentityRequest; import software.amazon.awssdk.services.ses.model.VerifyEmailIdentityRequest; public class EmailIntegrationTest extends IntegrationTestBase { private static final String DOMAIN = "invalid-test-domain"; private static final String EMAIL = "no-reply@amazon.com"; private static String DOMAIN_VERIFICATION_TOKEN; @BeforeClass public static void setup() { email.verifyEmailIdentity(VerifyEmailIdentityRequest.builder().emailAddress(EMAIL).build()); DOMAIN_VERIFICATION_TOKEN = email.verifyDomainIdentity(VerifyDomainIdentityRequest.builder().domain(DOMAIN).build()) .verificationToken(); } @AfterClass public static void tearDown() { email.deleteIdentity(DeleteIdentityRequest.builder().identity(EMAIL).build()); email.deleteIdentity(DeleteIdentityRequest.builder().identity(DOMAIN).build()); } @Test public void getSendQuota_ReturnsNonZeroQuotas() { GetSendQuotaResponse result = email.getSendQuota(GetSendQuotaRequest.builder().build()); assertThat(result.max24HourSend(), greaterThan(0.0)); assertThat(result.maxSendRate(), greaterThan(0.0)); } @Test public void listIdentities_WithNonVerifiedIdentity_ReturnsIdentityInList() { // Don't need to actually verify for it to show up in listIdentities List<String> identities = email.listIdentities(ListIdentitiesRequest.builder().build()).identities(); assertThat(identities, hasItem(EMAIL)); assertThat(identities, hasItem(DOMAIN)); } @Test public void listIdentities_FilteredForDomainIdentities_OnlyHasDomainIdentityInList() { List<String> identities = email.listIdentities( ListIdentitiesRequest.builder().identityType(IdentityType.DOMAIN).build()).identities(); assertThat(identities, not(hasItem(EMAIL))); assertThat(identities, hasItem(DOMAIN)); } @Test public void listIdentities_FilteredForEmailIdentities_OnlyHasEmailIdentityInList() { List<String> identities = email.listIdentities( ListIdentitiesRequest.builder().identityType(IdentityType.EMAIL_ADDRESS).build()).identities(); assertThat(identities, hasItem(EMAIL)); assertThat(identities, not(hasItem(DOMAIN))); } @Test public void listIdentitites_MaxResultsSetToOne_HasNonNullNextToken() { assertNotNull(email.listIdentities(ListIdentitiesRequest.builder().maxItems(1).build()).nextToken()); } @Test(expected = SdkServiceException.class) public void listIdentities_WithInvalidNextToken_ThrowsException() { email.listIdentities(ListIdentitiesRequest.builder().nextToken("invalid-next-token").build()); } @Test(expected = MessageRejectedException.class) public void sendEmail_ToUnverifiedIdentity_ThrowsException() { email.sendEmail(SendEmailRequest.builder().destination(Destination.builder().toAddresses(EMAIL).build()) .message(newMessage("test")).source(EMAIL).build()); } @Test public void getIdentityVerificationAttributes_ForNonVerifiedEmail_ReturnsPendingVerificatonStatus() { GetIdentityVerificationAttributesResponse result = email .getIdentityVerificationAttributes(GetIdentityVerificationAttributesRequest.builder().identities(EMAIL).build()); IdentityVerificationAttributes identityVerificationAttributes = result.verificationAttributes().get(EMAIL); assertEquals(VerificationStatus.PENDING, identityVerificationAttributes.verificationStatus()); // Verificaton token not applicable for email identities assertNull(identityVerificationAttributes.verificationToken()); } @Test public void getIdentityVerificationAttributes_ForNonVerifiedDomain_ReturnsPendingVerificatonStatus() { GetIdentityVerificationAttributesResponse result = email .getIdentityVerificationAttributes(GetIdentityVerificationAttributesRequest.builder() .identities(DOMAIN).build()); IdentityVerificationAttributes identityVerificationAttributes = result.verificationAttributes().get(DOMAIN); assertEquals(VerificationStatus.PENDING, identityVerificationAttributes.verificationStatus()); assertEquals(DOMAIN_VERIFICATION_TOKEN, identityVerificationAttributes.verificationToken()); } private Message newMessage(String subject) { Content content = Content.builder().data(subject).build(); Message message = Message.builder().subject(content).body(Body.builder().text(content).build()).build(); return message; } }
5,091
0
Create_ds/aws-sdk-java-v2/services/autoscaling/src/test/java/software/amazon/awssdk/services/autoscaling
Create_ds/aws-sdk-java-v2/services/autoscaling/src/test/java/software/amazon/awssdk/services/autoscaling/waiters/AutoScalingWaiterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.autoscaling.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 static software.amazon.awssdk.services.autoscaling.model.LifecycleState.IN_SERVICE; import static software.amazon.awssdk.services.autoscaling.model.LifecycleState.PENDING; 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.autoscaling.AutoScalingClient; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse; public class AutoScalingWaiterTest { private AutoScalingClient client; @Before public void setup() { client = mock(AutoScalingClient.class); } @Test(timeout = 30_000) @SuppressWarnings("unchecked") public void waitUntilGroupInServiceWorks() { DescribeAutoScalingGroupsRequest request = DescribeAutoScalingGroupsRequest.builder().build(); DescribeAutoScalingGroupsResponse response1 = DescribeAutoScalingGroupsResponse.builder() .autoScalingGroups(asg -> asg.minSize(2) .instances(i -> i.lifecycleState(PENDING), i -> i.lifecycleState(IN_SERVICE), i -> i.lifecycleState(IN_SERVICE)), asg -> asg.minSize(2) .instances(i -> i.lifecycleState(PENDING), i -> i.lifecycleState(PENDING), i -> i.lifecycleState(IN_SERVICE))) .build(); DescribeAutoScalingGroupsResponse response2 = DescribeAutoScalingGroupsResponse.builder() .autoScalingGroups(asg -> asg.minSize(2) .instances(i -> i.lifecycleState(PENDING), i -> i.lifecycleState(IN_SERVICE), i -> i.lifecycleState(IN_SERVICE)), asg -> asg.minSize(2) .instances(i -> i.lifecycleState(IN_SERVICE), i -> i.lifecycleState(IN_SERVICE), i -> i.lifecycleState(IN_SERVICE))) .build(); when(client.describeAutoScalingGroups(any(DescribeAutoScalingGroupsRequest.class))).thenReturn(response1, response2); AutoScalingWaiter waiter = AutoScalingWaiter.builder() .overrideConfiguration(WaiterOverrideConfiguration.builder() .maxAttempts(3) .backoffStrategy(BackoffStrategy.none()) .build()) .client(client) .build(); WaiterResponse<DescribeAutoScalingGroupsResponse> response = waiter.waitUntilGroupInService(request); assertThat(response.attemptsExecuted()).isEqualTo(2); assertThat(response.matched().response()).hasValueSatisfying(r -> assertThat(r).isEqualTo(response2)); } }
5,092
0
Create_ds/aws-sdk-java-v2/services/autoscaling/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/autoscaling/src/it/java/software/amazon/awssdk/services/autoscaling/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.autoscaling; import java.io.IOException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for AutoScaling integration tests. Provides several convenience methods for creating * test data, test data values, and automatically loads the AWS credentials from a properties file * on disk and instantiates clients for the test subclasses to use. */ public abstract class IntegrationTestBase extends AwsTestBase { private static final Region REGION = Region.US_EAST_1; /** Shared Autoscaling client for all tests to use. */ protected static AutoScalingClient autoscaling; /** Shared Autoscaling async client for tests to use. */ protected static AutoScalingAsyncClient autoscalingAsync; /** Shared SNS client for tests to use. */ /** * Loads the AWS account info for the integration tests and creates an AutoScaling client for * tests to use. */ public static void setUp() throws IOException { setUpCredentials(); autoscaling = AutoScalingClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(REGION) .build(); autoscalingAsync = AutoScalingAsyncClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(REGION) .build(); } }
5,093
0
Create_ds/aws-sdk-java-v2/services/autoscaling/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/autoscaling/src/it/java/software/amazon/awssdk/services/autoscaling/AutoScalingIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.autoscaling; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkGlobalTime; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.autoscaling.model.DescribePoliciesRequest; /** * Smoke tests for Autoscaling service. This class tests query protocol path. * Do not remove until we have generated smoke tests for this service. */ public class AutoScalingIntegrationTest extends IntegrationTestBase { @BeforeAll public static void beforeAll() throws IOException { setUp(); } @Test public void describeAutoScalingGroups() { autoscaling.describeAutoScalingGroups(); autoscalingAsync.describeAutoScalingGroups().join(); } @Test public void describeTerminationPolicyTypes() { autoscaling.describeTerminationPolicyTypes(); autoscalingAsync.describeAutoScalingGroups().join(); } @Test public void testClockSkewAs() { SdkGlobalTime.setGlobalTimeOffset(3600); AutoScalingClient clockSkewClient = AutoScalingClient.builder() .region(Region.US_EAST_1) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); clockSkewClient.describePolicies(DescribePoliciesRequest.builder().build()); assertTrue(SdkGlobalTime.getGlobalTimeOffset() < 60); } }
5,094
0
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services/cloudformation/CloudFormationIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudformation; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for CloudFormation integration tests. Loads AWS credentials from a properties file and * creates a client for callers to use. */ public class CloudFormationIntegrationTestBase extends AwsTestBase { protected static CloudFormationClient cf; /** * Loads the AWS account info for the integration tests and creates an S3 client for tests to * use. */ @BeforeClass public static void setUp() throws Exception { cf = CloudFormationClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.AP_NORTHEAST_1) .build(); } }
5,095
0
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services/cloudformation/ClockSkewIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudformation; import static org.junit.Assert.assertTrue; import org.junit.Test; import software.amazon.awssdk.core.SdkGlobalTime; import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest; public class ClockSkewIntegrationTest extends CloudFormationIntegrationTestBase { /** * In the following test, we purposely setting the time offset to trigger a clock skew error. * The time offset must be fixed and then we validate the global value for time offset has been * update. */ @Test public void testClockSkew() { SdkGlobalTime.setGlobalTimeOffset(3600); // Need to create a new client to have the time offset take affect CloudFormationClient clockSkewClient = CloudFormationClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); clockSkewClient.describeStacks(DescribeStacksRequest.builder().build()); assertTrue(SdkGlobalTime.getGlobalTimeOffset() < 60); } }
5,096
0
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services/cloudformation/SendEmptyListIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudformation; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudformation.model.CreateStackRequest; import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest; import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest; import software.amazon.awssdk.services.cloudformation.model.Tag; import software.amazon.awssdk.services.cloudformation.model.UpdateStackRequest; import software.amazon.awssdk.services.cloudformation.waiters.CloudFormationWaiter; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; /** * See https://github.com/aws/aws-sdk-java/issues/721. Cloudformation treats empty lists as removing * that list of values. */ public class SendEmptyListIntegrationTest extends AwsIntegrationTestBase { private static final String STARTING_TEMPLATE = "{" + " \"AWSTemplateFormatVersion\" : \"2010-09-09\"," + " \"Resources\" : {" + " \"JavaSdkCfSendEmptyListTest\" : {" + " \"Type\" : \"AWS::S3::Bucket\"" + " }" + " }" + "}"; private static final String UPDATED_TEMPLATE = "{" + " \"AWSTemplateFormatVersion\" : \"2010-09-09\"," + " \"Resources\" : {" + " \"JavaSdkCfSendEmptyListTestUpdated\" : {" + " \"Type\" : \"AWS::S3::Bucket\"" + " }" + " }" + "}"; private CloudFormationClient cf; private CloudFormationWaiter waiter; private String stackName; @Before public void setup() { stackName = getClass().getSimpleName() + "-" + System.currentTimeMillis(); cf = CloudFormationClient.builder() .credentialsProvider(StaticCredentialsProvider.create(getCredentials())) .region(Region.US_WEST_2) .build(); cf.createStack(CreateStackRequest.builder() .stackName(stackName) .templateBody(STARTING_TEMPLATE) .tags(Tag.builder().key("FooKey").value("FooValue").build()).build()); waiter = cf.waiter(); waiter.waitUntilStackCreateComplete(b -> b.stackName(stackName)); } @After public void tearDown() { cf.deleteStack(DeleteStackRequest.builder().stackName(stackName).build()); } @Test public void explicitlyEmptyTagList_RemovesTagsFromStack() { assertThat(getTagsForStack(stackName), not(empty())); cf.updateStack(UpdateStackRequest.builder() .stackName(stackName) .templateBody(STARTING_TEMPLATE) .tags(Collections.emptyList()).build()); waiter.waitUntilStackUpdateComplete(b -> b.stackName(stackName)); assertThat(getTagsForStack(stackName), empty()); } @Test public void autoConstructedEmptyTagList_DoesNotRemoveTagsFromStack() { assertThat(getTagsForStack(stackName), not(empty())); cf.updateStack(UpdateStackRequest.builder() .stackName(stackName) .templateBody(UPDATED_TEMPLATE).build()); waiter.waitUntilStackUpdateComplete(b -> b.stackName(stackName)); assertThat(getTagsForStack(stackName), not(empty())); } private List<Tag> getTagsForStack(String stackName) { return cf.describeStacks( DescribeStacksRequest.builder().stackName(stackName).build()) .stacks().get(0) .tags(); } }
5,097
0
Create_ds/aws-sdk-java-v2/services/elasticache/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/elasticache/src/it/java/software/amazon/awssdk/services/elasticache/ElastiCacheIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.elasticache; import org.junit.BeforeClass; import software.amazon.awssdk.testutils.service.AwsTestBase; public class ElastiCacheIntegrationTestBase extends AwsTestBase { protected static final String MEMCACHED_ENGINE = "memcached"; protected static final String REDIS_ENGINE = "redis"; protected static ElastiCacheClient elasticache; @BeforeClass public static void setUp() throws Exception { setUpCredentials(); elasticache = ElastiCacheClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } }
5,098
0
Create_ds/aws-sdk-java-v2/services/elasticache/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/elasticache/src/it/java/software/amazon/awssdk/services/elasticache/ParameterGroupsIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.elasticache; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static software.amazon.awssdk.testutils.SdkAsserts.assertNotEmpty; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Test; import software.amazon.awssdk.services.elasticache.model.CacheNodeTypeSpecificParameter; import software.amazon.awssdk.services.elasticache.model.CacheParameterGroup; import software.amazon.awssdk.services.elasticache.model.CreateCacheParameterGroupRequest; import software.amazon.awssdk.services.elasticache.model.DeleteCacheParameterGroupRequest; import software.amazon.awssdk.services.elasticache.model.DescribeCacheParameterGroupsRequest; import software.amazon.awssdk.services.elasticache.model.DescribeCacheParameterGroupsResponse; import software.amazon.awssdk.services.elasticache.model.DescribeCacheParametersRequest; import software.amazon.awssdk.services.elasticache.model.DescribeCacheParametersResponse; import software.amazon.awssdk.services.elasticache.model.DescribeEngineDefaultParametersRequest; import software.amazon.awssdk.services.elasticache.model.EngineDefaults; import software.amazon.awssdk.services.elasticache.model.ModifyCacheParameterGroupRequest; import software.amazon.awssdk.services.elasticache.model.ModifyCacheParameterGroupResponse; import software.amazon.awssdk.services.elasticache.model.Parameter; import software.amazon.awssdk.services.elasticache.model.ParameterNameValue; import software.amazon.awssdk.services.elasticache.model.ResetCacheParameterGroupRequest; import software.amazon.awssdk.services.elasticache.model.ResetCacheParameterGroupResponse; public class ParameterGroupsIntegrationTest extends ElastiCacheIntegrationTestBase { private static final String DESCRIPTION = "Java SDK integ test param group"; private static final String CACHE_PARAMETER_GROUP_FAMILY = "memcached1.4"; private String cacheParameterGroupName; /** Releases all resources created by tests. */ @After public void tearDown() throws Exception { if (cacheParameterGroupName != null) { try { elasticache.deleteCacheParameterGroup( DeleteCacheParameterGroupRequest.builder().cacheParameterGroupName(cacheParameterGroupName).build()); } catch (Exception e) { // Ignored or expected. } } } /** Tests that we can call the parameter group operations in the ElastiCache API. */ @Test public void testParameterGroupOperations() throws Exception { // Describe Engine Default Parameters EngineDefaults engineDefaults = elasticache .describeEngineDefaultParameters( DescribeEngineDefaultParametersRequest.builder().cacheParameterGroupFamily(CACHE_PARAMETER_GROUP_FAMILY) .build()).engineDefaults(); assertTrue(engineDefaults.cacheNodeTypeSpecificParameters().size() > 0); CacheNodeTypeSpecificParameter cacheNodeParameter = engineDefaults.cacheNodeTypeSpecificParameters().get(0); assertNotEmpty(cacheNodeParameter.parameterName()); assertTrue(cacheNodeParameter.cacheNodeTypeSpecificValues().size() > 0); assertEquals(CACHE_PARAMETER_GROUP_FAMILY, engineDefaults.cacheParameterGroupFamily()); assertTrue(engineDefaults.parameters().size() > 0); Parameter parameter = engineDefaults.parameters().get(0); assertNotEmpty(parameter.parameterName()); assertNotEmpty(parameter.parameterValue()); // Create Cache Parameter Group cacheParameterGroupName = "java-sdk-integ-test-" + System.currentTimeMillis(); CacheParameterGroup cacheParameterGroup = elasticache.createCacheParameterGroup( CreateCacheParameterGroupRequest.builder().cacheParameterGroupName(cacheParameterGroupName) .cacheParameterGroupFamily(CACHE_PARAMETER_GROUP_FAMILY).description(DESCRIPTION) .build()).cacheParameterGroup(); assertEquals(CACHE_PARAMETER_GROUP_FAMILY, cacheParameterGroup.cacheParameterGroupFamily()); assertEquals(cacheParameterGroupName, cacheParameterGroup.cacheParameterGroupName()); assertEquals(DESCRIPTION, cacheParameterGroup.description()); // Describe Cache Parameters DescribeCacheParametersResponse describeCacheParameters = elasticache.describeCacheParameters( DescribeCacheParametersRequest.builder().cacheParameterGroupName(cacheParameterGroupName).build()); assertTrue(describeCacheParameters.cacheNodeTypeSpecificParameters().size() > 0); cacheNodeParameter = describeCacheParameters.cacheNodeTypeSpecificParameters().get(0); assertNotEmpty(cacheNodeParameter.parameterName()); assertTrue(cacheNodeParameter.cacheNodeTypeSpecificValues().size() > 0); assertTrue(describeCacheParameters.parameters().size() > 0); parameter = describeCacheParameters.parameters().get(0); assertNotEmpty(parameter.parameterName()); assertNotEmpty(parameter.parameterValue()); // Modify Cache Parameter Group List<ParameterNameValue> paramsToModify = new ArrayList<ParameterNameValue>(); paramsToModify.add(ParameterNameValue.builder().parameterName("max_item_size").parameterValue("100000").build()); ModifyCacheParameterGroupResponse modifyCacheParameterGroup = elasticache .modifyCacheParameterGroup( ModifyCacheParameterGroupRequest.builder().cacheParameterGroupName(cacheParameterGroupName) .parameterNameValues(paramsToModify).build()); assertEquals(cacheParameterGroupName, modifyCacheParameterGroup.cacheParameterGroupName()); // Reset Cache Parameter Group List<ParameterNameValue> paramsToReset = new ArrayList<ParameterNameValue>(); paramsToReset.add(ParameterNameValue.builder().parameterName("binding_protocol").build()); ResetCacheParameterGroupResponse resetCacheParameterGroup = elasticache.resetCacheParameterGroup( ResetCacheParameterGroupRequest.builder().cacheParameterGroupName(cacheParameterGroupName) .parameterNameValues(paramsToReset).build()); assertEquals(cacheParameterGroupName, resetCacheParameterGroup.cacheParameterGroupName()); // Describe Cache Parameter Groups DescribeCacheParameterGroupsResponse describeCacheParameterGroups = elasticache.describeCacheParameterGroups( DescribeCacheParameterGroupsRequest.builder().cacheParameterGroupName(cacheParameterGroupName).build()); assertEquals(1, describeCacheParameterGroups.cacheParameterGroups().size()); CacheParameterGroup parameterGroup = describeCacheParameterGroups.cacheParameterGroups().get(0); assertEquals(CACHE_PARAMETER_GROUP_FAMILY, parameterGroup.cacheParameterGroupFamily()); assertEquals(cacheParameterGroupName, parameterGroup.cacheParameterGroupName()); assertEquals(DESCRIPTION, parameterGroup.description()); // Delete Cache Parameter Group elasticache.deleteCacheParameterGroup( DeleteCacheParameterGroupRequest.builder().cacheParameterGroupName(cacheParameterGroupName).build()); } }
5,099