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/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientGetV1MapperComparisonBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.model.GetItemResult; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) @Measurement(iterations = 5) @Fork(2) @State(Scope.Benchmark) public class EnhancedClientGetV1MapperComparisonBenchmark { private static final V2ItemFactory V2_ITEM_FACTORY = new V2ItemFactory(); private static final V1ItemFactory V1_ITEM_FACTORY = new V1ItemFactory(); @Benchmark public Object v2Get(TestState s) { return s.v2Table.getItem(s.key); } @Benchmark public Object v1Get(TestState s) { return s.v1DdbMapper.load(s.testItem.v1Key); } private static DynamoDbClient getV2Client(Blackhole bh, GetItemResponse getItemResponse) { return new V2TestDynamoDbGetItemClient(bh, getItemResponse); } private static AmazonDynamoDB getV1Client(Blackhole bh, GetItemResult getItemResult) { return new V1TestDynamoDbGetItemClient(bh, getItemResult); } @State(Scope.Benchmark) public static class TestState { @Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"}) public TestItem testItem; private final Key key = Key.builder().partitionValue("key").build(); private DynamoDbTable<?> v2Table; private DynamoDBMapper v1DdbMapper; @Setup public void setup(Blackhole bh) { DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder() .dynamoDbClient(getV2Client(bh, testItem.v2Response)) .build(); v2Table = v2DdbEnh.table(testItem.name(), testItem.schema); v1DdbMapper = new DynamoDBMapper(getV1Client(bh, testItem.v1Response)); } public enum TestItem { TINY( V2ItemFactory.TINY_BEAN_TABLE_SCHEMA, GetItemResponse.builder().item(V2_ITEM_FACTORY.tiny()).build(), new V1ItemFactory.V1TinyBean("hashKey"), new GetItemResult().withItem(V1_ITEM_FACTORY.tiny()) ), SMALL( V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA, GetItemResponse.builder().item(V2_ITEM_FACTORY.small()).build(), new V1ItemFactory.V1SmallBean("hashKey"), new GetItemResult().withItem(V1_ITEM_FACTORY.small()) ), HUGE( V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA, GetItemResponse.builder().item(V2_ITEM_FACTORY.huge()).build(), new V1ItemFactory.V1HugeBean("hashKey"), new GetItemResult().withItem(V1_ITEM_FACTORY.huge()) ), HUGE_FLAT( V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA, GetItemResponse.builder().item(V2_ITEM_FACTORY.hugeFlat()).build(), new V1ItemFactory.V1HugeBeanFlat("hashKey"), new GetItemResult().withItem(V1_ITEM_FACTORY.hugeFlat()) ), ; // V2 private TableSchema<?> schema; private GetItemResponse v2Response; // V1 private Object v1Key; private GetItemResult v1Response; TestItem(TableSchema<?> schema, GetItemResponse v2Response, Object v1Key, GetItemResult v1Response) { this.schema = schema; this.v2Response = v2Response; this.v1Key = v1Key; this.v1Response = v1Response; } } } }
2,800
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientQueryV1MapperComparisonBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.model.QueryResult; import java.util.Arrays; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) @Measurement(iterations = 5) @Fork(2) @State(Scope.Benchmark) public class EnhancedClientQueryV1MapperComparisonBenchmark { private static final V2ItemFactory V2_ITEM_FACTORY = new V2ItemFactory(); private static final V1ItemFactory V1_ITEM_FACTORY = new V1ItemFactory(); @Benchmark public Object v2Query(TestState s) { return s.v2Table.query(QueryConditional.keyEqualTo(s.key)).iterator().next(); } @Benchmark public Object v1Query(TestState s) { return s.v1DdbMapper.query(s.testItem.getV1BeanClass(), s.testItem.v1QueryExpression).iterator().next(); } private static DynamoDbClient getV2Client(Blackhole bh, QueryResponse queryResponse) { return new V2TestDynamoDbQueryClient(bh, queryResponse); } private static AmazonDynamoDB getV1Client(Blackhole bh, QueryResult queryResult) { return new V1TestDynamoDbQueryClient(bh, queryResult); } @State(Scope.Benchmark) public static class TestState { @Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"}) public TestItem testItem; private DynamoDbTable<?> v2Table; private DynamoDBMapper v1DdbMapper; private final Key key = Key.builder().partitionValue("key").build(); @Setup public void setup(Blackhole bh) { DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder() .dynamoDbClient(getV2Client(bh, testItem.v2Response)) .build(); v2Table = v2DdbEnh.table(testItem.name(), testItem.schema); v1DdbMapper = new DynamoDBMapper(getV1Client(bh, testItem.v1Response)); } public enum TestItem { TINY( V2ItemFactory.TINY_BEAN_TABLE_SCHEMA, QueryResponse.builder() .items(Arrays.asList(V2_ITEM_FACTORY.tiny(), V2_ITEM_FACTORY.tiny(), V2_ITEM_FACTORY.tiny())) .build(), V1ItemFactory.V1TinyBean.class, new DynamoDBQueryExpression().withHashKeyValues(new V1ItemFactory.V1TinyBean("hashKey")), new QueryResult().withItems( Arrays.asList(V1_ITEM_FACTORY.tiny(), V1_ITEM_FACTORY.tiny(), V1_ITEM_FACTORY.tiny())) ), SMALL( V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA, QueryResponse.builder() .items(Arrays.asList(V2_ITEM_FACTORY.small(), V2_ITEM_FACTORY.small(), V2_ITEM_FACTORY.small())) .build(), V1ItemFactory.V1SmallBean.class, new DynamoDBQueryExpression().withHashKeyValues(new V1ItemFactory.V1SmallBean("hashKey")), new QueryResult().withItems( Arrays.asList(V1_ITEM_FACTORY.small(), V1_ITEM_FACTORY.small(), V1_ITEM_FACTORY.small())) ), HUGE( V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA, QueryResponse.builder() .items(Arrays.asList(V2_ITEM_FACTORY.huge(), V2_ITEM_FACTORY.huge(), V2_ITEM_FACTORY.huge())) .build(), V1ItemFactory.V1HugeBean.class, new DynamoDBQueryExpression().withHashKeyValues(new V1ItemFactory.V1HugeBean("hashKey")), new QueryResult().withItems( Arrays.asList(V1_ITEM_FACTORY.huge(), V1_ITEM_FACTORY.huge(), V1_ITEM_FACTORY.huge())) ), HUGE_FLAT( V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA, QueryResponse.builder() .items(Arrays.asList(V2_ITEM_FACTORY.hugeFlat(), V2_ITEM_FACTORY.hugeFlat(), V2_ITEM_FACTORY.hugeFlat())) .build(), V1ItemFactory.V1HugeBeanFlat.class, new DynamoDBQueryExpression().withHashKeyValues(new V1ItemFactory.V1HugeBeanFlat("hashKey")), new QueryResult().withItems( Arrays.asList(V1_ITEM_FACTORY.hugeFlat(), V1_ITEM_FACTORY.hugeFlat(), V1_ITEM_FACTORY.hugeFlat())) ), ; // V2 private TableSchema<?> schema; private QueryResponse v2Response; // V1 private Class<?> v1BeanClass; private DynamoDBQueryExpression v1QueryExpression; private QueryResult v1Response; TestItem(TableSchema<?> schema, QueryResponse v2Response, Class<?> v1BeanClass, DynamoDBQueryExpression v1QueryExpression, QueryResult v1Response) { this.schema = schema; this.v2Response = v2Response; this.v1BeanClass = v1BeanClass; this.v1QueryExpression = v1QueryExpression; this.v1Response = v1Response; } public Class<?> getV1BeanClass() { return v1BeanClass; } } } }
2,801
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbPutItemClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.enhanced.dynamodb; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; public final class V2TestDynamoDbPutItemClient extends V2TestDynamoDbBaseClient { private static final PutItemResponse PUT_ITEM_RESPONSE = PutItemResponse.builder().build(); public V2TestDynamoDbPutItemClient(Blackhole bh) { super(bh); } @Override public PutItemResponse putItem(PutItemRequest putItemRequest) { bh.consume(putItemRequest); return PUT_ITEM_RESPONSE; } }
2,802
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientScanV1MapperComparisonBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression; import com.amazonaws.services.dynamodbv2.model.ScanResult; import java.util.Arrays; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) @Measurement(iterations = 5) @Fork(2) @State(Scope.Benchmark) public class EnhancedClientScanV1MapperComparisonBenchmark { private static final V2ItemFactory V2_ITEM_FACTORY = new V2ItemFactory(); private static final V1ItemFactory V1_ITEM_FACTORY = new V1ItemFactory(); private static final DynamoDBScanExpression V1_SCAN_EXPRESSION = new DynamoDBScanExpression(); @Benchmark public Object v2Scan(TestState s) { return s.v2Table.scan().iterator().next(); } @Benchmark public Object v1Scan(TestState s) { return s.v1DdbMapper.scan(s.testItem.getV1BeanClass(), V1_SCAN_EXPRESSION).iterator().next(); } private static DynamoDbClient getV2Client(Blackhole bh, ScanResponse scanResponse) { return new V2TestDynamoDbScanClient(bh, scanResponse); } private static AmazonDynamoDB getV1Client(Blackhole bh, ScanResult scanResult) { return new V1TestDynamoDbScanClient(bh, scanResult); } @State(Scope.Benchmark) public static class TestState { @Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"}) public TestItem testItem; private DynamoDbTable<?> v2Table; private DynamoDBMapper v1DdbMapper; @Setup public void setup(Blackhole bh) { DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder() .dynamoDbClient(getV2Client(bh, testItem.v2Response)) .build(); v2Table = v2DdbEnh.table(testItem.name(), testItem.schema); v1DdbMapper = new DynamoDBMapper(getV1Client(bh, testItem.v1Response)); } public enum TestItem { TINY( V2ItemFactory.TINY_BEAN_TABLE_SCHEMA, ScanResponse.builder() .items(Arrays.asList(V2_ITEM_FACTORY.tiny(), V2_ITEM_FACTORY.tiny(), V2_ITEM_FACTORY.tiny())) .build(), V1ItemFactory.V1TinyBean.class, new ScanResult().withItems( Arrays.asList(V1_ITEM_FACTORY.tiny(), V1_ITEM_FACTORY.tiny(), V1_ITEM_FACTORY.tiny())) ), SMALL( V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA, ScanResponse.builder() .items(Arrays.asList(V2_ITEM_FACTORY.small(), V2_ITEM_FACTORY.small(), V2_ITEM_FACTORY.small())) .build(), V1ItemFactory.V1SmallBean.class, new ScanResult().withItems( Arrays.asList(V1_ITEM_FACTORY.small(), V1_ITEM_FACTORY.small(), V1_ITEM_FACTORY.small())) ), HUGE( V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA, ScanResponse.builder() .items(Arrays.asList(V2_ITEM_FACTORY.huge(), V2_ITEM_FACTORY.huge(), V2_ITEM_FACTORY.huge())) .build(), V1ItemFactory.V1HugeBean.class, new ScanResult().withItems( Arrays.asList(V1_ITEM_FACTORY.huge(), V1_ITEM_FACTORY.huge(), V1_ITEM_FACTORY.huge())) ), HUGE_FLAT( V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA, ScanResponse.builder() .items(Arrays.asList(V2_ITEM_FACTORY.hugeFlat(), V2_ITEM_FACTORY.hugeFlat(), V2_ITEM_FACTORY.hugeFlat())) .build(), V1ItemFactory.V1HugeBeanFlat.class, new ScanResult().withItems( Arrays.asList(V1_ITEM_FACTORY.hugeFlat(), V1_ITEM_FACTORY.hugeFlat(), V1_ITEM_FACTORY.hugeFlat())) ), ; // V2 private TableSchema<?> schema; private ScanResponse v2Response; // V1 private Class<?> v1BeanClass; private ScanResult v1Response; TestItem(TableSchema<?> schema, ScanResponse v2Response, Class<?> v1BeanClass, ScanResult v1Response) { this.schema = schema; this.v2Response = v2Response; this.v1BeanClass = v1BeanClass; this.v1Response = v1Response; } public Class<?> getV1BeanClass() { return v1BeanClass; } } } }
2,803
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientGetOverheadBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.enhanced.dynamodb; import static software.amazon.awssdk.core.client.config.SdkClientOption.ENDPOINT; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.util.Map; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.benchmark.utils.MockHttpClient; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; 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.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.protocols.json.AwsJsonProtocol; import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.transform.PutItemRequestMarshaller; import software.amazon.awssdk.utils.IoUtils; @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) @Measurement(iterations = 5) @Fork(2) @State(Scope.Benchmark) public class EnhancedClientGetOverheadBenchmark { private static final AwsJsonProtocolFactory JSON_PROTOCOL_FACTORY = AwsJsonProtocolFactory .builder() .clientConfiguration(SdkClientConfiguration.builder() .option(ENDPOINT, URI.create("https://dynamodb.amazonaws.com")) .build()) .defaultServiceExceptionSupplier(DynamoDbException::builder) .protocol(AwsJsonProtocol.AWS_JSON) .protocolVersion("1.0") .build(); private static final PutItemRequestMarshaller PUT_ITEM_REQUEST_MARSHALLER = new PutItemRequestMarshaller(JSON_PROTOCOL_FACTORY); private static final V2ItemFactory ITEM_FACTORY = new V2ItemFactory(); private final Key testKey = Key.builder().partitionValue("key").build(); @Benchmark public Object lowLevelGet(TestState s) { return s.dynamoDb.getItem(GetItemRequest.builder().build()); } @Benchmark public Object enhanceGet(TestState s) { return s.table.getItem(testKey); } @State(Scope.Benchmark) public static class TestState { private DynamoDbClient dynamoDb; @Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"}) private TestItem testItem; private DynamoDbTable table; @Setup public void setup(Blackhole bh) { dynamoDb = DynamoDbClient.builder() .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))) .httpClient(new MockHttpClient(testItem.responseContent, "{}")) .overrideConfiguration(o -> o.addExecutionInterceptor(new ExecutionInterceptor() { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { bh.consume(context); bh.consume(executionAttributes); } })) .build(); DynamoDbEnhancedClient ddbEnh = DynamoDbEnhancedClient.builder() .dynamoDbClient(dynamoDb) .build(); table = ddbEnh.table(testItem.name(), testItem.tableSchema); } } public enum TestItem { TINY(marshall(ITEM_FACTORY.tiny()), V2ItemFactory.TINY_BEAN_TABLE_SCHEMA), SMALL(marshall(ITEM_FACTORY.small()), V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA), HUGE(marshall(ITEM_FACTORY.huge()), V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA), HUGE_FLAT(marshall(ITEM_FACTORY.hugeFlat()), V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA) ; private String responseContent; private TableSchema tableSchema; TestItem(String responseContent, TableSchema tableSchema) { this.responseContent = responseContent; this.tableSchema = tableSchema; } } private static String marshall(Map<String, AttributeValue> item) { return PUT_ITEM_REQUEST_MARSHALLER.marshall(PutItemRequest.builder().item(item).build()) .contentStreamProvider().map(cs -> { try { return IoUtils.toUtf8String(cs.newStream()); } catch (IOException e) { throw new UncheckedIOException(e); } }).orElse(null); } }
2,804
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientDeleteV1MapperComparisonBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) @Measurement(iterations = 5) @Fork(2) @State(Scope.Benchmark) public class EnhancedClientDeleteV1MapperComparisonBenchmark { @Benchmark public void v2Delete(TestState s) { s.v2Table.deleteItem(s.key); } @Benchmark public void v1Delete(TestState s) { s.v1DdbMapper.delete(s.testItem.v1Key); } private static DynamoDbClient getV2Client(Blackhole bh) { return new V2TestDynamoDbDeleteItemClient(bh); } private static AmazonDynamoDB getV1Client(Blackhole bh) { return new V1TestDynamoDbDeleteItemClient(bh); } @State(Scope.Benchmark) public static class TestState { @Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"}) public TestItem testItem; private final Key key = Key.builder().partitionValue("key").build(); private DynamoDbTable v2Table; private DynamoDBMapper v1DdbMapper; @Setup public void setup(Blackhole bh) { DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder() .dynamoDbClient(getV2Client(bh)) .build(); v2Table = v2DdbEnh.table(testItem.name(), testItem.schema); v1DdbMapper = new DynamoDBMapper(getV1Client(bh)); } public enum TestItem { TINY( V2ItemFactory.TINY_BEAN_TABLE_SCHEMA, new V1ItemFactory.V1TinyBean("hashKey") ), SMALL( V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA, new V1ItemFactory.V1SmallBean("hashKey") ), HUGE( V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA, new V1ItemFactory.V1HugeBean("hashKey") ), HUGE_FLAT( V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA, new V1ItemFactory.V1HugeBeanFlat("hashKey") ), ; // V2 private TableSchema schema; // V1 private Object v1Key; TestItem(TableSchema<?> schema, Object v1Key) { this.schema = schema; this.v1Key = v1Key; } } } }
2,805
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientPutOverheadBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.enhanced.dynamodb; import java.util.Map; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.benchmark.utils.MockHttpClient; 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.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) @Measurement(iterations = 5) @Fork(2) @State(Scope.Benchmark) public class EnhancedClientPutOverheadBenchmark { @Benchmark public void lowLevelPut(TestState s) { s.ddb.putItem(r -> r.item(s.testItem.av)); } @Benchmark public void enhancedPut(TestState s) { s.enhTable.putItem(s.testItem.bean); } @State(Scope.Benchmark) public static class TestState { @Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"}) private TestItem testItem; private DynamoDbClient ddb; private DynamoDbTable enhTable; @Setup public void setup(Blackhole bh) { ddb = DynamoDbClient.builder() .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))) .httpClient(new MockHttpClient("{}", "{}")) .overrideConfiguration(c -> c.addExecutionInterceptor(new ExecutionInterceptor() { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { bh.consume(context); bh.consume(executionAttributes); } })) .build(); DynamoDbEnhancedClient ddbEnh = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); enhTable = ddbEnh.table(testItem.name(), testItem.tableSchema); } } public enum TestItem { TINY, SMALL, HUGE, HUGE_FLAT ; private static final V2ItemFactory FACTORY = new V2ItemFactory(); private Map<String, AttributeValue> av; private TableSchema tableSchema; private Object bean; static { TINY.av = FACTORY.tiny(); TINY.tableSchema = V2ItemFactory.TINY_BEAN_TABLE_SCHEMA; TINY.bean = FACTORY.tinyBean(); SMALL.av = FACTORY.small(); SMALL.tableSchema = V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA; SMALL.bean = FACTORY.smallBean(); HUGE.av = FACTORY.huge(); HUGE.tableSchema = V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA; HUGE.bean = FACTORY.hugeBean(); HUGE_FLAT.av = FACTORY.hugeFlat(); HUGE_FLAT.tableSchema = V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA; HUGE_FLAT.bean = FACTORY.hugeBeanFlat(); } } }
2,806
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbQueryClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.model.QueryRequest; import com.amazonaws.services.dynamodbv2.model.QueryResult; import org.openjdk.jmh.infra.Blackhole; public class V1TestDynamoDbQueryClient extends V1TestDynamoDbBaseClient { private final QueryResult queryResult; public V1TestDynamoDbQueryClient(Blackhole bh, QueryResult queryResult) { super(bh); this.queryResult = queryResult; } @Override public QueryResult query(QueryRequest request) { bh.consume(request); return queryResult; } }
2,807
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbBaseClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.enhanced.dynamodb; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; abstract class V2TestDynamoDbBaseClient implements DynamoDbClient { protected final Blackhole bh; protected V2TestDynamoDbBaseClient(Blackhole bh) { this.bh = bh; } @Override public String serviceName() { return "DynamoDB"; } @Override public void close() { } }
2,808
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbScanClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.model.ScanRequest; import com.amazonaws.services.dynamodbv2.model.ScanResult; import org.openjdk.jmh.infra.Blackhole; public class V1TestDynamoDbScanClient extends V1TestDynamoDbBaseClient { private final ScanResult scanResult; public V1TestDynamoDbScanClient(Blackhole bh, ScanResult scanResult) { super(bh); this.scanResult = scanResult; } @Override public ScanResult scan(ScanRequest request) { bh.consume(request); return scanResult; } }
2,809
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/dynamodb/V2ItemFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.marshaller.dynamodb; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public final class V2ItemFactory extends AbstractItemFactory<AttributeValue> { @Override protected AttributeValue av(String val) { return AttributeValue.builder().s(val).build(); } @Override protected AttributeValue av(ByteBuffer val) { return AttributeValue.builder().b(SdkBytes.fromByteBuffer(val)).build(); } @Override protected AttributeValue av(List<AttributeValue> val) { return AttributeValue.builder().l(val).build(); } @Override protected AttributeValue av(Map<String, AttributeValue> val) { return AttributeValue.builder().m(val).build(); } }
2,810
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/dynamodb/V1DynamoDbAttributeValue.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.marshaller.dynamodb; import com.amazonaws.AmazonWebServiceResponse; import com.amazonaws.Request; import com.amazonaws.http.HttpResponse; import com.amazonaws.http.HttpResponseHandler; import com.amazonaws.protocol.json.JsonClientMetadata; import com.amazonaws.protocol.json.JsonOperationMetadata; import com.amazonaws.protocol.json.SdkJsonProtocolFactory; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.GetItemResult; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import com.amazonaws.services.dynamodbv2.model.transform.GetItemResultJsonUnmarshaller; import com.amazonaws.services.dynamodbv2.model.transform.PutItemRequestProtocolMarshaller; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Map; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; @State(Scope.Benchmark) public class V1DynamoDbAttributeValue { private static final SdkJsonProtocolFactory PROTOCOL_FACTORY = protocolFactory(); private static final PutItemRequestProtocolMarshaller PUT_ITEM_REQUEST_MARSHALLER = new PutItemRequestProtocolMarshaller(PROTOCOL_FACTORY); @Benchmark public Object putItem(PutItemState s) { return PUT_ITEM_REQUEST_MARSHALLER.marshall(s.getReq()); } @Benchmark public Object getItem(GetItemState s) { HttpResponse resp = new HttpResponse(null, null); resp.setContent(new ByteArrayInputStream(s.testItem.utf8())); try { return getItemJsonResponseHandler().handle(resp); } catch (Exception e) { throw new RuntimeException(e); } } @State(Scope.Benchmark) public static class PutItemState { @Param({"TINY", "SMALL", "HUGE"}) private TestItem testItem; private PutItemRequest req; @Setup public void setup() { req = new PutItemRequest().withItem(testItem.getValue()); } public PutItemRequest getReq() { return req; } } @State(Scope.Benchmark) public static class GetItemState { @Param( {"TINY", "SMALL", "HUGE"} ) private TestItemUnmarshalling testItem; } public enum TestItem { TINY, SMALL, HUGE; private static final AbstractItemFactory<AttributeValue> FACTORY = new V1ItemFactory(); private Map<String, AttributeValue> av; static { TINY.av = FACTORY.tiny(); SMALL.av = FACTORY.small(); HUGE.av = FACTORY.huge(); } public Map<String, AttributeValue> getValue() { return av; } } public enum TestItemUnmarshalling { TINY, SMALL, HUGE; private byte[] utf8; static { TINY.utf8 = toUtf8ByteArray(TestItem.TINY.av); SMALL.utf8 = toUtf8ByteArray(TestItem.SMALL.av); HUGE.utf8 = toUtf8ByteArray(TestItem.HUGE.av); } public byte[] utf8() { return utf8; } } private static byte[] toUtf8ByteArray(Map<String, AttributeValue> item) { Request<?> resp = PUT_ITEM_REQUEST_MARSHALLER.marshall(new PutItemRequest().withItem(item)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buff = new byte[8192]; int read; try { while ((read = resp.getContent().read(buff)) != -1) { baos.write(buff, 0, read); } } catch (IOException e) { throw new UncheckedIOException(e); } return baos.toByteArray(); } private static HttpResponseHandler<AmazonWebServiceResponse<GetItemResult>> getItemJsonResponseHandler() { return PROTOCOL_FACTORY.createResponseHandler(new JsonOperationMetadata() .withPayloadJson(true) .withHasStreamingSuccessResponse(false), new GetItemResultJsonUnmarshaller()); } private static SdkJsonProtocolFactory protocolFactory() { return new com.amazonaws.protocol.json.SdkJsonProtocolFactory( new JsonClientMetadata() .withProtocolVersion("1.0") .withSupportsCbor(false) .withSupportsIon(false) ); } }
2,811
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/dynamodb/V1ItemFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.marshaller.dynamodb; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; public final class V1ItemFactory extends AbstractItemFactory<AttributeValue> { @Override protected AttributeValue av(String val) { return new AttributeValue() .withS(val); } @Override protected AttributeValue av(ByteBuffer val) { return new AttributeValue() .withB(val); } @Override protected AttributeValue av(List<AttributeValue> val) { return new AttributeValue() .withL(val); } @Override protected AttributeValue av(Map<String, AttributeValue> val) { return new AttributeValue() .withM(val); } }
2,812
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/dynamodb/AbstractItemFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.marshaller.dynamodb; import com.amazonaws.util.ImmutableMapParameter; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Random; abstract class AbstractItemFactory<T> { private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz"; private static final Random RNG = new Random(); final Map<String, T> tiny() { return ImmutableMapParameter.<String, T>builder() .put("stringAttr", av(randomS())) .build(); } final Map<String, T> small() { return ImmutableMapParameter.<String, T>builder() .put("stringAttr", av(randomS())) .put("binaryAttr", av(randomB())) .put("listAttr", av(Arrays.asList( av(randomS()), av(randomB()), av(randomS()) ))) .build(); } final Map<String, T> huge() { return ImmutableMapParameter.<String, T>builder() .put("hashKey", av(randomS())) .put("stringAttr", av(randomS())) .put("binaryAttr", av(randomB())) .put("listAttr", av( Arrays.asList( av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomB()), av(Collections.singletonList(av(randomS()))), av(ImmutableMapParameter.of( "attrOne", av(randomS()) )), av(Arrays.asList( av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(randomB()), (av(randomS())), av(ImmutableMapParameter.of( "attrOne", av(randomS()) )) )) ) )) .put("mapAttr", av( ImmutableMapParameter.<String, T>builder() .put("attrOne", av(randomS())) .put("attrTwo", av(randomB())) .put("attrThree", av( Arrays.asList( av(randomS()), av(randomS()), av(randomS()), av(randomS()), av(ImmutableMapParameter.<String, T>builder() .put("attrOne", av(randomS())) .put("attrTwo", av(randomB())) .put("attrThree", av(Arrays.asList( av(randomS()), av(randomS()), av(randomS()), av(randomS()) )) ) .build()) )) ) .build())) .build(); } protected abstract T av(String val); protected abstract T av(ByteBuffer val); protected abstract T av(List<T> val); protected abstract T av(Map<String, T> val); private String randomS(int len) { StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; ++i) { sb.append(ALPHA.charAt(RNG.nextInt(ALPHA.length()))); } return sb.toString(); } private String randomS() { return randomS(16); } private ByteBuffer randomB(int len) { byte[] b = new byte[len]; RNG.nextBytes(b); return ByteBuffer.wrap(b); } private ByteBuffer randomB() { return randomB(16); } }
2,813
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/dynamodb/V2DynamoDbAttributeValue.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.marshaller.dynamodb; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.Map; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.core.ExceptionMetadata; import software.amazon.awssdk.protocols.json.AwsJsonProtocol; import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory; import software.amazon.awssdk.protocols.json.JsonOperationMetadata; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.BackupInUseException; import software.amazon.awssdk.services.dynamodb.model.BackupNotFoundException; import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; import software.amazon.awssdk.services.dynamodb.model.ContinuousBackupsUnavailableException; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.GlobalTableAlreadyExistsException; import software.amazon.awssdk.services.dynamodb.model.GlobalTableNotFoundException; import software.amazon.awssdk.services.dynamodb.model.IndexNotFoundException; import software.amazon.awssdk.services.dynamodb.model.InternalServerErrorException; import software.amazon.awssdk.services.dynamodb.model.InvalidRestoreTimeException; import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException; import software.amazon.awssdk.services.dynamodb.model.LimitExceededException; import software.amazon.awssdk.services.dynamodb.model.PointInTimeRecoveryUnavailableException; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.ReplicaAlreadyExistsException; import software.amazon.awssdk.services.dynamodb.model.ReplicaNotFoundException; import software.amazon.awssdk.services.dynamodb.model.ResourceInUseException; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.services.dynamodb.model.TableAlreadyExistsException; import software.amazon.awssdk.services.dynamodb.model.TableInUseException; import software.amazon.awssdk.services.dynamodb.model.TableNotFoundException; import software.amazon.awssdk.services.dynamodb.transform.PutItemRequestMarshaller; public class V2DynamoDbAttributeValue { private static final AwsJsonProtocolFactory JSON_PROTOCOL_FACTORY = AwsJsonProtocolFactory .builder() .defaultServiceExceptionSupplier(DynamoDbException::builder) .protocol(AwsJsonProtocol.AWS_JSON) .protocolVersion("1.0") .registerModeledException( ExceptionMetadata.builder().errorCode("ResourceInUseException") .exceptionBuilderSupplier(ResourceInUseException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("TableAlreadyExistsException") .exceptionBuilderSupplier(TableAlreadyExistsException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("GlobalTableAlreadyExistsException") .exceptionBuilderSupplier(GlobalTableAlreadyExistsException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("InvalidRestoreTimeException") .exceptionBuilderSupplier(InvalidRestoreTimeException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ReplicaAlreadyExistsException") .exceptionBuilderSupplier(ReplicaAlreadyExistsException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ConditionalCheckFailedException") .exceptionBuilderSupplier(ConditionalCheckFailedException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("BackupNotFoundException") .exceptionBuilderSupplier(BackupNotFoundException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("IndexNotFoundException") .exceptionBuilderSupplier(IndexNotFoundException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("LimitExceededException") .exceptionBuilderSupplier(LimitExceededException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("GlobalTableNotFoundException") .exceptionBuilderSupplier(GlobalTableNotFoundException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ItemCollectionSizeLimitExceededException") .exceptionBuilderSupplier(ItemCollectionSizeLimitExceededException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ReplicaNotFoundException") .exceptionBuilderSupplier(ReplicaNotFoundException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("TableNotFoundException") .exceptionBuilderSupplier(TableNotFoundException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("BackupInUseException") .exceptionBuilderSupplier(BackupInUseException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ResourceNotFoundException") .exceptionBuilderSupplier(ResourceNotFoundException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ContinuousBackupsUnavailableException") .exceptionBuilderSupplier(ContinuousBackupsUnavailableException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("TableInUseException") .exceptionBuilderSupplier(TableInUseException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ProvisionedThroughputExceededException") .exceptionBuilderSupplier(ProvisionedThroughputExceededException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("PointInTimeRecoveryUnavailableException") .exceptionBuilderSupplier(PointInTimeRecoveryUnavailableException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("InternalServerError") .exceptionBuilderSupplier(InternalServerErrorException::builder).build()) .build(); private static final PutItemRequestMarshaller PUT_ITEM_REQUEST_MARSHALLER = new PutItemRequestMarshaller(getJsonProtocolFactory()); private static HttpResponseHandler<GetItemResponse> getItemResponseJsonResponseHandler() { return JSON_PROTOCOL_FACTORY.createResponseHandler(JsonOperationMetadata.builder() .isPayloadJson(true) .hasStreamingSuccessResponse(false) .build(), GetItemResponse::builder); } @Benchmark public Object putItem(PutItemState s) { return putItemRequestMarshaller().marshall(s.getReq()); } @Benchmark public Object getItem(GetItemState s) throws Exception { SdkHttpFullResponse resp = fullResponse(s.testItem); return getItemResponseJsonResponseHandler().handle(resp, new ExecutionAttributes()); } @State(Scope.Benchmark) public static class PutItemState { @Param({"TINY", "SMALL", "HUGE"}) private TestItem testItem; private PutItemRequest req; @Setup public void setup() { req = PutItemRequest.builder().item(testItem.getValue()).build(); } public PutItemRequest getReq() { return req; } } @State(Scope.Benchmark) public static class GetItemState { @Param({"TINY", "SMALL", "HUGE"}) private TestItemUnmarshalling testItem; } public enum TestItem { TINY, SMALL, HUGE; private static final AbstractItemFactory<AttributeValue> FACTORY = new V2ItemFactory(); private Map<String, AttributeValue> av; static { TINY.av = FACTORY.tiny(); SMALL.av = FACTORY.small(); HUGE.av = FACTORY.huge(); } public Map<String, AttributeValue> getValue() { return av; } } public enum TestItemUnmarshalling { TINY, SMALL, HUGE; private byte[] utf8; static { TINY.utf8 = toUtf8ByteArray(TestItem.TINY.av); SMALL.utf8 = toUtf8ByteArray(TestItem.SMALL.av); HUGE.utf8 = toUtf8ByteArray(TestItem.HUGE.av); } public byte[] utf8() { return utf8; } } private SdkHttpFullResponse fullResponse(TestItemUnmarshalling item) { AbortableInputStream abortableInputStream = AbortableInputStream.create(new ByteArrayInputStream(item.utf8())); return SdkHttpFullResponse.builder() .statusCode(200) .content(abortableInputStream) .build(); } private static byte[] toUtf8ByteArray(Map<String, AttributeValue> item) { SdkHttpFullRequest marshalled = putItemRequestMarshaller().marshall(PutItemRequest.builder().item(item).build()); InputStream content = marshalled.contentStreamProvider().get().newStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buff = new byte[8192]; int read; try { while ((read = content.read(buff)) != -1) { baos.write(buff, 0, read); } } catch (IOException ioe) { throw new UncheckedIOException(ioe); } return baos.toByteArray(); } private static PutItemRequestMarshaller putItemRequestMarshaller() { return PUT_ITEM_REQUEST_MARSHALLER; } private static AwsJsonProtocolFactory getJsonProtocolFactory() { return JSON_PROTOCOL_FACTORY; } }
2,814
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/ec2/V2ItemFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.marshaller.ec2; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import software.amazon.awssdk.services.ec2.model.BlockDeviceMapping; import software.amazon.awssdk.services.ec2.model.ElasticGpuSpecification; import software.amazon.awssdk.services.ec2.model.InstanceNetworkInterfaceSpecification; import software.amazon.awssdk.services.ec2.model.RunInstancesRequest; import software.amazon.awssdk.services.ec2.model.VolumeType; final class V2ItemFactory { private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz"; private static final Random RNG = new Random(); RunInstancesRequest tiny() { return RunInstancesRequest.builder() .additionalInfo(randomS(50)) .disableApiTermination(true) .maxCount(5) .build(); } RunInstancesRequest small() { return RunInstancesRequest.builder() .additionalInfo(randomS(50)) .disableApiTermination(true) .maxCount(5) .blockDeviceMappings(blockDeviceMappings(3)) .cpuOptions(c -> c.coreCount(5).threadsPerCore(5)) .elasticGpuSpecification(elasticGpuSpecification()) .networkInterfaces(networkInterfaces(3)) .build(); } RunInstancesRequest huge() { return RunInstancesRequest.builder() .additionalInfo(randomS(50)) .disableApiTermination(true) .maxCount(5) .blockDeviceMappings(blockDeviceMappings(100)) .cpuOptions(c -> c.coreCount(5).threadsPerCore(5)) .elasticGpuSpecification(elasticGpuSpecification()) .networkInterfaces(networkInterfaces(100)) .build(); } private static ElasticGpuSpecification elasticGpuSpecification() { return ElasticGpuSpecification.builder() .type(randomS(50)) .build(); } private static InstanceNetworkInterfaceSpecification networkInterface() { return InstanceNetworkInterfaceSpecification.builder() .associatePublicIpAddress(true) .deleteOnTermination(true) .deviceIndex(50) .groups(randomS(50), randomS(50), randomS(50)) .description(randomS(50)) .build(); } private static List<InstanceNetworkInterfaceSpecification> networkInterfaces(int num) { return IntStream.of(num) .mapToObj(i -> networkInterface()) .collect(Collectors.toList()); } private static BlockDeviceMapping blockDeviceMapping() { return BlockDeviceMapping.builder() .deviceName(randomS(100)) .virtualName(randomS(50)) .noDevice(randomS(50)) .ebs(e -> e.deleteOnTermination(true) .encrypted(false) .iops(50) .kmsKeyId(randomS(50)) .snapshotId(randomS(50)) .volumeSize(50) .volumeType(VolumeType.GP2)) .build(); } private static List<BlockDeviceMapping> blockDeviceMappings(int num) { return IntStream.of(num) .mapToObj(i -> blockDeviceMapping()) .collect(Collectors.toList()); } private static String randomS(int len) { StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; ++i) { sb.append(ALPHA.charAt(RNG.nextInt(ALPHA.length()))); } return sb.toString(); } }
2,815
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/ec2/V2Ec2MarshallerBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.marshaller.ec2; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import software.amazon.awssdk.protocols.query.AwsEc2ProtocolFactory; import software.amazon.awssdk.services.ec2.model.RunInstancesRequest; import software.amazon.awssdk.services.ec2.transform.RunInstancesRequestMarshaller; public class V2Ec2MarshallerBenchmark { private static final AwsEc2ProtocolFactory PROTOCOL_FACTORY = AwsEc2ProtocolFactory.builder().build(); private static final RunInstancesRequestMarshaller RUN_INSTANCES_REQUEST_MARSHALLER = new RunInstancesRequestMarshaller(PROTOCOL_FACTORY); @Benchmark public Object marshall(MarshallerState s) { return runInstancesRequestMarshaller().marshall(s.getReq()); } @State(Scope.Benchmark) public static class MarshallerState { @Param({"TINY", "SMALL", "HUGE"}) private TestItem testItem; private RunInstancesRequest req; @Setup public void setup() { req = testItem.getValue(); } public RunInstancesRequest getReq() { return req; } } public enum TestItem { TINY, SMALL, HUGE; private static final V2ItemFactory FACTORY = new V2ItemFactory(); private RunInstancesRequest request; static { TINY.request = FACTORY.tiny(); SMALL.request = FACTORY.small(); HUGE.request = FACTORY.huge(); } public RunInstancesRequest getValue() { return request; } } private static RunInstancesRequestMarshaller runInstancesRequestMarshaller() { return RUN_INSTANCES_REQUEST_MARSHALLER; } }
2,816
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/ec2/V1ItemFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.marshaller.ec2; import com.amazonaws.services.ec2.model.BlockDeviceMapping; import com.amazonaws.services.ec2.model.CpuOptionsRequest; import com.amazonaws.services.ec2.model.EbsBlockDevice; import com.amazonaws.services.ec2.model.ElasticGpuSpecification; import com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.VolumeType; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; final class V1ItemFactory { private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz"; private static final Random RNG = new Random(); RunInstancesRequest tiny() { return new RunInstancesRequest() .withAdditionalInfo(randomS(50)) .withDisableApiTermination(true) .withMaxCount(5); } RunInstancesRequest small() { return new RunInstancesRequest() .withAdditionalInfo(randomS(50)) .withDisableApiTermination(true) .withMaxCount(5) .withBlockDeviceMappings(blockDeviceMappings(3)) .withCpuOptions(new CpuOptionsRequest().withCoreCount(5).withThreadsPerCore(5)) .withElasticGpuSpecification(new ElasticGpuSpecification().withType(randomS(50))) .withNetworkInterfaces(networkInterfaces(3)); } RunInstancesRequest huge() { return new RunInstancesRequest() .withAdditionalInfo(randomS(50)) .withDisableApiTermination(true) .withMaxCount(5) .withBlockDeviceMappings(blockDeviceMappings(100)) .withCpuOptions(new CpuOptionsRequest().withCoreCount(5).withThreadsPerCore(5)) .withElasticGpuSpecification(new ElasticGpuSpecification().withType(randomS(50))) .withNetworkInterfaces(networkInterfaces(100)); } static InstanceNetworkInterfaceSpecification networkInterface() { return new InstanceNetworkInterfaceSpecification() .withAssociatePublicIpAddress(true) .withDeleteOnTermination(true) .withDeviceIndex(50) .withGroups(randomS(50), randomS(50), randomS(50)) .withDescription(randomS(50)); } static List<InstanceNetworkInterfaceSpecification> networkInterfaces(int num) { return IntStream.of(num) .mapToObj(i -> networkInterface()) .collect(Collectors.toList()); } private static BlockDeviceMapping blockDeviceMapping() { return new BlockDeviceMapping() .withDeviceName(randomS(100)) .withVirtualName(randomS(50)) .withNoDevice(randomS(50)) .withEbs(new EbsBlockDevice().withDeleteOnTermination(true) .withEncrypted(false) .withIops(50) .withKmsKeyId(randomS(50)) .withSnapshotId(randomS(50)) .withVolumeSize(50) .withVolumeType(VolumeType.Gp2)); } private static List<BlockDeviceMapping> blockDeviceMappings(int num) { return IntStream.of(num) .mapToObj(i -> blockDeviceMapping()) .collect(Collectors.toList()); } private static String randomS(int len) { StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; ++i) { sb.append(ALPHA.charAt(RNG.nextInt(ALPHA.length()))); } return sb.toString(); } }
2,817
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/marshaller/ec2/V1Ec2MarshallerBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.marshaller.ec2; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.transform.RunInstancesRequestMarshaller; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; public class V1Ec2MarshallerBenchmark { private static final RunInstancesRequestMarshaller RUN_INSTANCES_REQUEST_MARSHALLER = new RunInstancesRequestMarshaller(); @Benchmark public Object marshall(MarshallerState s) { return runInstancesRequestMarshaller().marshall(s.getReq()); } @State(Scope.Benchmark) public static class MarshallerState { @Param({"TINY", "SMALL", "HUGE"}) private TestItem testItem; private RunInstancesRequest req; @Setup public void setup() { req = testItem.getValue(); } public RunInstancesRequest getReq() { return req; } } public enum TestItem { TINY, SMALL, HUGE; private static final V1ItemFactory FACTORY = new V1ItemFactory(); private RunInstancesRequest request; static { TINY.request = FACTORY.tiny(); SMALL.request = FACTORY.small(); HUGE.request = FACTORY.huge(); } public RunInstancesRequest getValue() { return request; } } private static RunInstancesRequestMarshaller runInstancesRequestMarshaller() { return RUN_INSTANCES_REQUEST_MARSHALLER; } }
2,818
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/stats/SdkBenchmarkParams.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.stats; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.IOException; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.infra.BenchmarkParams; import software.amazon.awssdk.core.util.VersionInfo; /** * Contains metadata for the benchmark */ public class SdkBenchmarkParams { private String sdkVersion; private String jdkVersion; private String jvmName; private String jvmVersion; private Mode mode; @JsonSerialize(using = ZonedDateSerializer.class) @JsonDeserialize(using = ZonedDateDeserializer.class) private ZonedDateTime date; public SdkBenchmarkParams() { } public SdkBenchmarkParams(BenchmarkParams benchmarkParams) { this.sdkVersion = VersionInfo.SDK_VERSION; this.jdkVersion = benchmarkParams.getJdkVersion(); this.jvmName = benchmarkParams.getVmName(); this.jvmVersion = benchmarkParams.getVmVersion(); this.mode = benchmarkParams.getMode(); this.date = ZonedDateTime.now(); } public String getSdkVersion() { return sdkVersion; } public void setSdkVersion(String sdkVersion) { this.sdkVersion = sdkVersion; } public String getJdkVersion() { return jdkVersion; } public void setJdkVersion(String jdkVersion) { this.jdkVersion = jdkVersion; } public String getJvmName() { return jvmName; } public void setJvmName(String jvmName) { this.jvmName = jvmName; } public String getJvmVersion() { return jvmVersion; } public void setJvmVersion(String jvmVersion) { this.jvmVersion = jvmVersion; } public ZonedDateTime getDate() { return date; } public void setDate(ZonedDateTime date) { this.date = date; } public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; } private static class ZonedDateSerializer extends JsonSerializer<ZonedDateTime> { @Override public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeString(value.format(DateTimeFormatter.ISO_ZONED_DATE_TIME)); } } private static class ZonedDateDeserializer extends JsonDeserializer<ZonedDateTime> { @Override public ZonedDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { return ZonedDateTime.parse(p.getValueAsString()); } } }
2,819
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/stats/SdkBenchmarkResult.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.stats; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * SDK wrapper of benchmark result, created for easy serialization/deserialization. */ public class SdkBenchmarkResult { private String id; private SdkBenchmarkParams params; private SdkBenchmarkStatistics statistics; @JsonCreator public SdkBenchmarkResult(@JsonProperty("id") String benchmarkId, @JsonProperty("params") SdkBenchmarkParams params, @JsonProperty("statistics") SdkBenchmarkStatistics statistics) { this.id = benchmarkId; this.statistics = statistics; this.params = params; } public String getId() { return id; } public void setId(String id) { this.id = id; } public SdkBenchmarkStatistics getStatistics() { return statistics; } public void setStatistics(SdkBenchmarkStatistics statistics) { this.statistics = statistics; } public SdkBenchmarkParams getParams() { return params; } public void setParams(SdkBenchmarkParams params) { this.params = params; } }
2,820
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/stats/SdkBenchmarkStatistics.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.benchmark.stats; import org.apache.commons.math3.stat.descriptive.StatisticalSummary; import org.openjdk.jmh.util.Statistics; /** * SDK wrapper of benchmark statistics, created for easy serialization/deserialization. */ public class SdkBenchmarkStatistics implements StatisticalSummary { private double mean; private double variance; private double standardDeviation; private double max; private double min; private long n; private double sum; public SdkBenchmarkStatistics() { } public SdkBenchmarkStatistics(Statistics statistics) { this.mean = statistics.getMean(); this.variance = statistics.getVariance(); this.standardDeviation = statistics.getStandardDeviation(); this.max = statistics.getMax(); this.min = statistics.getMin(); this.n = statistics.getN(); this.sum = statistics.getSum(); } @Override public double getMean() { return mean; } public void setMean(double mean) { this.mean = mean; } @Override public double getVariance() { return variance; } public void setVariance(double variance) { this.variance = variance; } @Override public double getStandardDeviation() { return standardDeviation; } public void setStandardDeviation(double standardDeviation) { this.standardDeviation = standardDeviation; } @Override public double getMax() { return max; } public void setMax(double max) { this.max = max; } @Override public double getMin() { return min; } public void setMin(double min) { this.min = min; } @Override public long getN() { return n; } public void setN(long n) { this.n = n; } @Override public double getSum() { return sum; } public void setSum(double sum) { this.sum = sum; } }
2,821
0
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/EndpointProviderTestCase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.rules.testing; import java.util.function.Supplier; import software.amazon.awssdk.core.rules.testing.model.Expect; import software.amazon.awssdk.endpoints.Endpoint; public final class EndpointProviderTestCase { private Supplier<Endpoint> testMethod; private Expect expect; public EndpointProviderTestCase(Supplier<Endpoint> testMethod, Expect expect) { this.testMethod = testMethod; this.expect = expect; } public Supplier<Endpoint> getTestMethod() { return testMethod; } public void setTestMethod(Supplier<Endpoint> testMethod) { this.testMethod = testMethod; } public Expect getExpect() { return expect; } public void setExpect(Expect expect) { this.expect = expect; } }
2,822
0
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/AsyncTestCase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.rules.testing; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import software.amazon.awssdk.core.rules.testing.model.Expect; public final class AsyncTestCase { private final String description; private final Supplier<CompletableFuture<?>> operationRunnable; private final Expect expectation; private final String skipReason; public AsyncTestCase(String description, Supplier<CompletableFuture<?>> operationRunnable, Expect expectation) { this(description, operationRunnable, expectation, null); } public AsyncTestCase(String description, Supplier<CompletableFuture<?>> operationRunnable, Expect expectation, String skipReason) { this.description = description; this.operationRunnable = operationRunnable; this.expectation = expectation; this.skipReason = skipReason; } public Supplier<CompletableFuture<?>> operationRunnable() { return operationRunnable; } public Expect expectation() { return expectation; } public String skipReason() { return skipReason; } @Override public String toString() { return description; } }
2,823
0
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/BaseRuleSetClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.rules.testing; 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.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.net.URI; import java.time.Instant; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.auth.token.credentials.StaticTokenProvider; import software.amazon.awssdk.core.rules.testing.model.Expect; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.utils.CompletableFutureUtils; public abstract class BaseRuleSetClientTest { protected static final AwsCredentialsProvider CREDENTIALS_PROVIDER = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")); protected static final SdkTokenProvider TOKEN_PROVIDER = StaticTokenProvider.create(new TestSdkToken()); private static SdkHttpClient syncHttpClient; private static SdkAsyncHttpClient asyncHttpClient; @BeforeAll public static void setup() { syncHttpClient = mock(SdkHttpClient.class); asyncHttpClient = mock(SdkAsyncHttpClient.class); } @BeforeEach public void methodSetup() { reset(syncHttpClient, asyncHttpClient); when(syncHttpClient.prepareRequest(any())).thenThrow(new RuntimeException("Oops")); when(asyncHttpClient.execute(any())).thenAnswer(i -> { AsyncExecuteRequest req = i.getArgument(0, AsyncExecuteRequest.class); SdkAsyncHttpResponseHandler responseHandler = req.responseHandler(); responseHandler.onError(new RuntimeException("Oops")); return CompletableFutureUtils.failedFuture(new RuntimeException("Something went wrong")); }); } protected static void runAndVerify(SyncTestCase testCase) { String skipReason = testCase.skipReason(); Assumptions.assumeTrue(skipReason == null, skipReason); Expect expectation = testCase.expectation(); Runnable r = testCase.operationRunnable(); if (expectation.error() != null) { assertThatThrownBy(r::run).hasMessageContaining(expectation.error()); } else { assertThatThrownBy(r::run).hasMessageContaining("Oops"); ArgumentCaptor<HttpExecuteRequest> requestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(syncHttpClient).prepareRequest(requestCaptor.capture()); URI requestUri = requestCaptor.getValue().httpRequest().getUri(); Endpoint expectedEndpoint = expectation.endpoint(); assertThat(requestUri.getScheme()).isEqualTo(expectedEndpoint.url().getScheme()); assertThat(requestUri.getHost()).isEqualTo(expectedEndpoint.url().getHost()); assertThat(requestUri.getRawPath()).startsWith(expectedEndpoint.url().getRawPath()); } } protected static void runAndVerify(AsyncTestCase testCase) { String skipReason = testCase.skipReason(); Assumptions.assumeTrue(skipReason == null, skipReason); Expect expectation = testCase.expectation(); Supplier<CompletableFuture<?>> r = testCase.operationRunnable(); CompletableFuture<?> executeFuture = r.get(); if (expectation.error() != null) { assertThatThrownBy(executeFuture::get).hasMessageContaining(expectation.error()); } else { assertThatThrownBy(executeFuture::get).hasMessageContaining("Oops"); ArgumentCaptor<AsyncExecuteRequest> requestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); verify(asyncHttpClient).execute(requestCaptor.capture()); URI requestUri = requestCaptor.getValue().request().getUri(); Endpoint expectedEndpoint = expectation.endpoint(); assertThat(requestUri.getScheme()).isEqualTo(expectedEndpoint.url().getScheme()); assertThat(requestUri.getHost()).isEqualTo(expectedEndpoint.url().getHost()); } } protected static SdkHttpClient getSyncHttpClient() { return syncHttpClient; } protected static SdkAsyncHttpClient getAsyncHttpClient() { return asyncHttpClient; } private static class TestSdkToken implements SdkToken { @Override public String token() { return "TOKEN"; } @Override public Optional<Instant> expirationTime() { return Optional.empty(); } } }
2,824
0
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/BaseEndpointProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.rules.testing; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.function.Supplier; import software.amazon.awssdk.awscore.endpoints.AwsEndpointAttribute; import software.amazon.awssdk.core.rules.testing.model.Expect; import software.amazon.awssdk.endpoints.Endpoint; public class BaseEndpointProviderTest { protected final void verify(EndpointProviderTestCase tc) { Expect expect = tc.getExpect(); Supplier<Endpoint> testMethod = tc.getTestMethod(); if (expect.error() != null) { assertThatThrownBy(testMethod::get).hasMessageContaining(expect.error()); } else { Endpoint actualEndpoint = testMethod.get(); Endpoint expectedEndpoint = expect.endpoint(); assertThat(actualEndpoint.url()).isEqualTo(expectedEndpoint.url()); assertThat(actualEndpoint.headers()).isEqualTo(expectedEndpoint.headers()); AwsEndpointAttribute.values().forEach(attr -> { if (expectedEndpoint.attribute(attr) != null) { assertThat(actualEndpoint.attribute(attr)).isEqualTo(expectedEndpoint.attribute(attr)); } else { assertThat(actualEndpoint.attribute(attr)).isNull(); } }); } } }
2,825
0
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/SyncTestCase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.rules.testing; import software.amazon.awssdk.core.rules.testing.model.Expect; public final class SyncTestCase { private final String description; private final Runnable operationRunnable; private final Expect expectation; private final String skipReason; public SyncTestCase(String description, Runnable operationRunnable, Expect expectation) { this(description, operationRunnable, expectation, null); } public SyncTestCase(String description, Runnable operationRunnable, Expect expectation, String skipReason) { this.description = description; this.operationRunnable = operationRunnable; this.expectation = expectation; this.skipReason = skipReason; } public Runnable operationRunnable() { return operationRunnable; } public Expect expectation() { return expectation; } public String skipReason() { return skipReason; } @Override public String toString() { return description; } }
2,826
0
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/util/EmptyPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.rules.testing.util; import io.reactivex.rxjava3.core.Flowable; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; public class EmptyPublisher<T> implements Publisher<T> { @Override public void subscribe(Subscriber<? super T> subscriber) { Publisher<T> empty = Flowable.empty(); empty.subscribe(subscriber); } }
2,827
0
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/model/ParamInfo.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.rules.testing.model; public class ParamInfo { private String builtIn; private ParamInfo(Builder b) { this.builtIn = b.builtIn; } public String builtIn() { return builtIn; } public static Builder builder() { return new Builder(); } public static class Builder { private String builtIn; public Builder builtIn(String builtIn) { this.builtIn = builtIn; return this; } public ParamInfo build() { return new ParamInfo(this); } } }
2,828
0
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/model/Expect.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.rules.testing.model; import software.amazon.awssdk.endpoints.Endpoint; public class Expect { private Endpoint endpoint; private String error; private Expect(Builder b) { this.endpoint = b.endpoint; this.error = b.error; } public Endpoint endpoint() { return endpoint; } public String error() { return error; } public static Builder builder() { return new Builder(); } public static class Builder { private Endpoint endpoint; private String error; public Builder endpoint(Endpoint endpoint) { this.endpoint = endpoint; return this; } public Builder error(String error) { this.error = error; return this; } public Expect build() { return new Expect(this); } } }
2,829
0
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/model/EndpointTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.rules.testing.model; import com.fasterxml.jackson.databind.JsonNode; import java.util.List; import java.util.Map; public class EndpointTest { private String documentation; private Map<String, JsonNode> params; private List<String> tags; private Expect expect; public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public Map<String, JsonNode> getParams() { return params; } public void setParams(Map<String, JsonNode> params) { this.params = params; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags = tags; } public Expect getExpect() { return expect; } public void setExpect(Expect expect) { this.expect = expect; } }
2,830
0
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing
Create_ds/aws-sdk-java-v2/test/ruleset-testing-core/src/main/java/software/amazon/awssdk/core/rules/testing/model/EndpointTestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.rules.testing.model; import java.util.List; public final class EndpointTestSuite { private String service; private String version; private List<EndpointTest> testCases; public String getService() { return service; } public void setService(String service) { this.service = service; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List<EndpointTest> getTestCases() { return testCases; } public void setTestCases(List<EndpointTest> testCases) { this.testCases = testCases; } }
2,831
0
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/module-info.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ module software.amazon.awssdk.modulepath.tests { requires software.amazon.awssdk.regions; requires software.amazon.awssdk.http.urlconnection; requires software.amazon.awssdk.http.apache; requires software.amazon.awssdk.http.nio.netty; requires software.amazon.awssdk.http; requires software.amazon.awssdk.core; requires software.amazon.awssdk.awscore; requires software.amazon.awssdk.auth; requires software.amazon.awssdk.services.s3; requires software.amazon.awssdk.protocol.tests; requires org.reactivestreams; requires software.amazon.awssdk.utils; requires software.amazon.awssdk.testutils.service; requires org.slf4j; requires slf4j.simple; }
2,832
0
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/IntegTestsRunner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.modulepath.tests; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.modulepath.tests.integtests.BaseApiCall; import software.amazon.awssdk.modulepath.tests.integtests.S3ApiCall; /** * Tests runner to test module path on real service. */ public class IntegTestsRunner { private IntegTestsRunner() { } public static void main(String... args) { List<BaseApiCall> tests = new ArrayList<>(); tests.add(new S3ApiCall()); tests.forEach(test -> { test.usingApacheClient(); test.usingUrlConnectionClient(); test.usingNettyClient(); }); } }
2,833
0
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/MockTestsRunner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.modulepath.tests; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.modulepath.tests.mocktests.BaseMockApiCall; import software.amazon.awssdk.modulepath.tests.mocktests.JsonProtocolApiCall; import software.amazon.awssdk.modulepath.tests.mocktests.XmlProtocolApiCall; /** * Executor to run mock tests on module path. */ public class MockTestsRunner { private MockTestsRunner() { } public static void main(String... args) { List<BaseMockApiCall> tests = new ArrayList<>(); tests.add(new XmlProtocolApiCall()); tests.add(new JsonProtocolApiCall()); tests.forEach(t -> { t.successfulApiCall(); t.failedApiCall(); t.successfulAsyncApiCall(); t.failedAsyncApiCall(); }); } }
2,834
0
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/integtests/S3ApiCall.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.modulepath.tests.integtests; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; public class S3ApiCall extends BaseApiCall { private S3Client s3Client = S3Client.builder() .region(Region.US_WEST_2) .httpClient(ApacheHttpClient.builder().build()) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); private S3Client s3ClientWithHttpUrlConnection = S3Client.builder() .region(Region.US_WEST_2) .httpClient(UrlConnectionHttpClient.builder().build()) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); private S3AsyncClient s3ClientWithNettyClient = S3AsyncClient.builder() .region(Region.US_WEST_2) .httpClient(NettyNioAsyncHttpClient.builder().build()) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); public S3ApiCall() { super("s3"); } @Override public Runnable apacheClientRunnable() { return () -> s3Client.listBuckets(); } @Override public Runnable urlHttpConnectionClientRunnable() { return () -> s3ClientWithHttpUrlConnection.listBuckets(); } @Override public Runnable nettyClientRunnable() { return () -> s3ClientWithNettyClient.listBuckets().join(); } }
2,835
0
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/integtests/BaseApiCall.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.modulepath.tests.integtests; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base Api Call class */ public abstract class BaseApiCall extends AwsTestBase { private static final Logger logger = LoggerFactory.getLogger(BaseApiCall.class); private final String serviceName; public BaseApiCall(String serviceName) { this.serviceName = serviceName; } public void usingApacheClient() { logger.info("Starting testing {} client with Apache http client", serviceName); apacheClientRunnable().run(); } public void usingUrlConnectionClient() { logger.info("Starting testing {} client with url connection http client", serviceName); urlHttpConnectionClientRunnable().run(); } public void usingNettyClient() { logger.info("Starting testing {} client with netty client", serviceName); nettyClientRunnable().run(); } public abstract Runnable apacheClientRunnable(); public abstract Runnable urlHttpConnectionClientRunnable(); public abstract Runnable nettyClientRunnable(); }
2,836
0
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/mocktests/JsonProtocolApiCall.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.modulepath.tests.mocktests; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; /** * Protocol tests for json protocol */ public class JsonProtocolApiCall extends BaseMockApiCall { private static final Logger logger = LoggerFactory.getLogger(JsonProtocolApiCall.class); private ProtocolRestJsonClient client; private ProtocolRestJsonAsyncClient asyncClient; public JsonProtocolApiCall() { super("json"); this.client = ProtocolRestJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create( "akid", "skid"))) .region(Region.US_EAST_1) .httpClient(mockHttpClient) .build(); this.asyncClient = ProtocolRestJsonAsyncClient.builder() .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create( "akid", "skid"))) .region(Region.US_EAST_1) .httpClient(mockAyncHttpClient) .build(); } @Override Runnable runnable() { return () -> client.allTypes(); } @Override Runnable asyncRunnable() { return () -> asyncClient.allTypes().join(); } }
2,837
0
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/mocktests/XmlProtocolApiCall.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.modulepath.tests.mocktests; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient; /** * Protocol tests for xml protocol */ public class XmlProtocolApiCall extends BaseMockApiCall { private ProtocolRestXmlClient client; private ProtocolRestXmlAsyncClient asyncClient; public XmlProtocolApiCall() { super("xml"); client = ProtocolRestXmlClient.builder().httpClient(mockHttpClient).build(); asyncClient = ProtocolRestXmlAsyncClient.builder().httpClient(mockAyncHttpClient).build(); } @Override Runnable runnable() { return () -> client.allTypes(); } @Override Runnable asyncRunnable() { return () -> asyncClient.allTypes().join(); } }
2,838
0
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/mocktests/MockHttpClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.modulepath.tests.mocktests; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpRequest; /** * Mock implementation of {@link SdkHttpClient}. */ public final class MockHttpClient implements SdkHttpClient { private final List<SdkHttpRequest> capturedRequests = new ArrayList<>(); private HttpExecuteResponse nextResponse; @Override public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) { capturedRequests.add(request.httpRequest()); return new ExecutableHttpRequest() { @Override public HttpExecuteResponse call() { return nextResponse; } @Override public void abort() { } }; } @Override public void close() { } /** * Resets this mock by clearing any captured requests and wiping any stubbed responses. */ public void reset() { this.capturedRequests.clear(); this.nextResponse = null; } /** * Sets up the next HTTP response that will be returned by the mock. * * @param nextResponse Next {@link HttpExecuteResponse} to return from * {@link #prepareRequest(HttpExecuteRequest)} */ public void stubNextResponse(HttpExecuteResponse nextResponse) { this.nextResponse = nextResponse; } /** * @return The last executed request that went through this mock client. * @throws IllegalStateException If no requests have been captured. */ public SdkHttpRequest getLastRequest() { if (capturedRequests.isEmpty()) { throw new IllegalStateException("No requests were captured by the mock"); } return capturedRequests.get(capturedRequests.size() - 1); } }
2,839
0
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/mocktests/BaseMockApiCall.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.modulepath.tests.mocktests; import java.io.ByteArrayInputStream; import java.util.concurrent.CompletionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpResponse; /** * Base classes to mock sync and async api calls. */ public abstract class BaseMockApiCall { private static final Logger logger = LoggerFactory.getLogger(BaseMockApiCall.class); protected final MockHttpClient mockHttpClient; protected final MockAyncHttpClient mockAyncHttpClient; private final String protocol; public BaseMockApiCall(String protocol) { this.protocol = protocol; this.mockHttpClient = new MockHttpClient(); this.mockAyncHttpClient = new MockAyncHttpClient(); } public void successfulApiCall() { logger.info("stubing successful api call for {} protocol", protocol); mockHttpClient.stubNextResponse(successResponse(protocol)); runnable().run(); mockHttpClient.reset(); } public void failedApiCall() { logger.info("stubing failed api call for {} protocol", protocol); mockHttpClient.stubNextResponse(errorResponse(protocol)); try { runnable().run(); } catch (AwsServiceException e) { logger.info("Received expected service exception", e.getMessage()); } mockHttpClient.reset(); } public void successfulAsyncApiCall() { logger.info("stubing successful async api call for {} protocol", protocol); mockAyncHttpClient.stubNextResponse(successResponse(protocol)); asyncRunnable().run(); mockAyncHttpClient.reset(); } public void failedAsyncApiCall() { logger.info("stubing failed async api call for {} protocol", protocol); mockAyncHttpClient.stubNextResponse(errorResponse(protocol)); try { asyncRunnable().run(); } catch (CompletionException e) { if (e.getCause() instanceof AwsServiceException) { logger.info("expected service exception {}", e.getMessage()); } else { throw new RuntimeException("Unexpected exception is thrown"); } } mockAyncHttpClient.reset(); } abstract Runnable runnable(); abstract Runnable asyncRunnable(); private HttpExecuteResponse successResponse(String protocol) { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(200) .build()) .responseBody(generateContent(protocol)) .build(); } private HttpExecuteResponse errorResponse(String protocol) { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(500) .build()) .responseBody(generateContent(protocol)) .build(); } private AbortableInputStream generateContent(String protocol) { String content; switch (protocol) { case "xml": content = "<foo></foo>"; break; default: case "json": content = "{}"; } return AbortableInputStream.create(new ByteArrayInputStream(content.getBytes())); } }
2,840
0
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests
Create_ds/aws-sdk-java-v2/test/module-path-tests/src/main/java/software/amazon/awssdk/modulepath/tests/mocktests/MockAyncHttpClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.modulepath.tests.mocktests; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.utils.IoUtils; /** * Mock implementation of {@link SdkAsyncHttpClient}. */ public final class MockAyncHttpClient implements SdkAsyncHttpClient { private final List<SdkHttpRequest> capturedRequests = new ArrayList<>(); private HttpExecuteResponse nextResponse; @Override public CompletableFuture<Void> execute(AsyncExecuteRequest request) { capturedRequests.add(request.request()); request.responseHandler().onHeaders(nextResponse.httpResponse()); request.responseHandler().onStream(new SdkHttpContentPublisher() { byte[] content = nextResponse.responseBody().map(p -> invokeSafely(() -> IoUtils.toByteArray(p))) .orElseGet(() -> new byte[0]); @Override public Optional<Long> contentLength() { return Optional.of((long) content.length); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { s.onSubscribe(new Subscription() { private boolean running = true; @Override public void request(long n) { if (n <= 0) { running = false; s.onError(new IllegalArgumentException("Demand must be positive")); } else if (running) { running = false; s.onNext(ByteBuffer.wrap(content)); s.onComplete(); } } @Override public void cancel() { running = false; } }); } }); return CompletableFuture.completedFuture(null); } @Override public void close() { } /** * Resets this mock by clearing any captured requests and wiping any stubbed responses. */ public void reset() { this.capturedRequests.clear(); this.nextResponse = null; } public void stubNextResponse(HttpExecuteResponse nextResponse) { this.nextResponse = nextResponse; } }
2,841
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/SraIdentityResolutionUsingPluginsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.concurrent.CompletableFuture; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.SdkServiceClientConfiguration; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.ResolveIdentityRequest; import software.amazon.awssdk.services.protocolquery.ProtocolQueryClient; import software.amazon.awssdk.services.protocolquery.ProtocolQueryServiceClientConfiguration; import software.amazon.awssdk.utils.Validate; @RunWith(MockitoJUnitRunner.class) public class SraIdentityResolutionUsingPluginsTest { @Mock private AwsCredentialsProvider credentialsProvider; @Test public void testIdentityBasedPluginsResolutionIsUsedAndNotAnotherIdentityResolution() { SdkHttpClient mockClient = mock(SdkHttpClient.class); when(mockClient.prepareRequest(any())).thenThrow(new RuntimeException("boom")); when(credentialsProvider.identityType()).thenReturn(AwsCredentialsIdentity.class); when(credentialsProvider.resolveIdentity(any(ResolveIdentityRequest.class))) .thenReturn(CompletableFuture.completedFuture(AwsBasicCredentials.create("akid1", "skid2"))); ProtocolQueryClient syncClient = ProtocolQueryClient .builder() .httpClient(mockClient) .addPlugin(new TestPlugin(credentialsProvider)) // Below is necessary to create the test case where, addCredentialsToExecutionAttributes was getting called before .overrideConfiguration(ClientOverrideConfiguration.builder().build()) .build(); assertThatThrownBy(() -> syncClient.allTypes(r -> {})).hasMessageContaining("boom"); verify(credentialsProvider, atLeastOnce()).identityType(); // This asserts that the identity used is the one from resolveIdentity() called by SRA AuthSchemeInterceptor and not // from another call like from AwsCredentialsAuthorizationStrategy.addCredentialsToExecutionAttributes, asserted by // combination of times(1) and verifyNoMoreInteractions. verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class)); verifyNoMoreInteractions(credentialsProvider); } static class TestPlugin implements SdkPlugin { private final AwsCredentialsProvider credentialsProvider; TestPlugin(AwsCredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; } @Override public void configureClient(SdkServiceClientConfiguration.Builder config) { ProtocolQueryServiceClientConfiguration.Builder builder = Validate.isInstanceOf(ProtocolQueryServiceClientConfiguration.Builder.class, config, "Expecting an instance of " + ProtocolQueryServiceClientConfiguration.class); builder.credentialsProvider(credentialsProvider); } } }
2,842
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/FipsEndpointTest.java
package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.StringInputStream; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class FipsEndpointTest { @Parameterized.Parameter public TestCase testCase; @Test public void resolvesCorrectEndpoint() { String systemPropertyBeforeTest = System.getProperty(SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.property()); EnvironmentVariableHelper helper = new EnvironmentVariableHelper(); try { ProtocolRestJsonClientBuilder builder = ProtocolRestJsonClient.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()); if (testCase.clientSetting != null) { builder.fipsEnabled(testCase.clientSetting); } if (testCase.systemPropSetting != null) { System.setProperty(SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.property(), testCase.systemPropSetting); } if (testCase.envVarSetting != null) { helper.set(SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.environmentVariable(), testCase.envVarSetting); } ProfileFile.Builder profileFile = ProfileFile.builder().type(ProfileFile.Type.CONFIGURATION); if (testCase.profileSetting != null) { profileFile.content(new StringInputStream("[default]\n" + ProfileProperty.USE_FIPS_ENDPOINT + " = " + testCase.profileSetting)); } else { profileFile.content(new StringInputStream("")); } EndpointCapturingInterceptor interceptor = new EndpointCapturingInterceptor(); builder.overrideConfiguration(c -> c.defaultProfileFile(profileFile.build()) .defaultProfileName("default") .addExecutionInterceptor(interceptor)); if (testCase instanceof SuccessCase) { ProtocolRestJsonClient client = builder.build(); try { client.allTypes(); } catch (EndpointCapturingInterceptor.CaptureCompletedException e) { // Expected } boolean expectedFipsEnabled = ((SuccessCase) testCase).expectedValue; String expectedEndpoint = expectedFipsEnabled ? "https://customresponsemetadata-fips.us-west-2.amazonaws.com/2016-03-11/allTypes" : "https://customresponsemetadata.us-west-2.amazonaws.com/2016-03-11/allTypes"; assertThat(interceptor.endpoints()).singleElement().isEqualTo(expectedEndpoint); } else { FailureCase failure = Validate.isInstanceOf(FailureCase.class, testCase, "Unexpected test case type."); assertThatThrownBy(builder::build).hasMessageContaining(failure.exceptionMessage); } } finally { if (systemPropertyBeforeTest != null) { System.setProperty(SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.property(), systemPropertyBeforeTest); } else { System.clearProperty(SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.property()); } helper.reset(); } } @Parameterized.Parameters(name = "{0}") public static Iterable<TestCase> testCases() { return Arrays.asList(new SuccessCase(true, "false", "false", "false", true, "Client highest priority (true)"), new SuccessCase(false, "true", "true", "true", false, "Client highest priority (false)"), new SuccessCase(null, "true", "false", "false", true, "System property second priority (true)"), new SuccessCase(null, "false", "true", "true", false, "System property second priority (false)"), new SuccessCase(null, null, "true", "false", true, "Env var third priority (true)"), new SuccessCase(null, null, "false", "true", false, "Env var third priority (false)"), new SuccessCase(null, null, null, "true", true, "Profile last priority (true)"), new SuccessCase(null, null, null, "false", false, "Profile last priority (false)"), new SuccessCase(null, null, null, null, false, "Default is false."), new SuccessCase(null, "tRuE", null, null, true, "System property is not case sensitive."), new SuccessCase(null, null, "tRuE", null, true, "Env var is not case sensitive."), new SuccessCase(null, null, null, "tRuE", true, "Profile property is not case sensitive."), new FailureCase(null, "FOO", null, null, "FOO", "Invalid system property values fail."), new FailureCase(null, null, "FOO", null, "FOO", "Invalid env var values fail."), new FailureCase(null, null, null, "FOO", "FOO", "Invalid profile values fail.")); } public static class TestCase { private final Boolean clientSetting; private final String envVarSetting; private final String systemPropSetting; private final String profileSetting; private final String caseName; public TestCase(Boolean clientSetting, String systemPropSetting, String envVarSetting, String profileSetting, String caseName) { this.clientSetting = clientSetting; this.envVarSetting = envVarSetting; this.systemPropSetting = systemPropSetting; this.profileSetting = profileSetting; this.caseName = caseName; } @Override public String toString() { return caseName; } } public static class SuccessCase extends TestCase { private final boolean expectedValue; public SuccessCase(Boolean clientSetting, String systemPropSetting, String envVarSetting, String profileSetting, boolean expectedValue, String caseName) { super(clientSetting, systemPropSetting, envVarSetting, profileSetting, caseName); this.expectedValue = expectedValue; } } private static class FailureCase extends TestCase { private final String exceptionMessage; public FailureCase(Boolean clientSetting, String systemPropSetting, String envVarSetting, String profileSetting, String exceptionMessage, String caseName) { super(clientSetting, systemPropSetting, envVarSetting, profileSetting, caseName); this.exceptionMessage = exceptionMessage; } } }
2,843
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/HostPrefixTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; import software.amazon.awssdk.utils.StringInputStream; import software.amazon.awssdk.utils.builder.SdkBuilder; public class HostPrefixTest { private MockSyncHttpClient mockHttpClient; private ProtocolRestJsonClient client; private MockAsyncHttpClient mockAsyncClient; private ProtocolRestJsonAsyncClient asyncClient; @BeforeEach public void setupClient() { mockHttpClient = new MockSyncHttpClient(); mockAsyncClient = new MockAsyncHttpClient(); client = ProtocolRestJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost")) .httpClient(mockHttpClient) .build(); asyncClient = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost")) .httpClient(mockAsyncClient) .build(); } @Test public void invalidHostPrefix_shouldThrowException() { assertThatThrownBy(() -> client.operationWithHostPrefix(b -> b.stringMember("123#"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The provided operationWithHostPrefixRequest is not valid: the 'StringMember' component must " + "match the pattern \"[A-Za-z0-9\\-]+\"."); assertThatThrownBy(() -> asyncClient.operationWithHostPrefix(b -> b.stringMember("123#")).join()) .hasCauseInstanceOf(IllegalArgumentException.class).hasMessageContaining("The provided operationWithHostPrefixRequest is not valid: the 'StringMember' component must match the pattern \"[A-Za-z0-9\\-]+\"."); } @Test public void nullHostPrefix_shouldThrowException() { assertThatThrownBy(() -> client.operationWithHostPrefix(SdkBuilder::build)) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("component is missing"); assertThatThrownBy(() -> asyncClient.operationWithHostPrefix(SdkBuilder::build).join()) .hasCauseInstanceOf(IllegalArgumentException.class).hasMessageContaining("component is missing"); } @Test public void syncValidHostPrefix_shouldPrefixEndpoint() { mockHttpClient.stubNextResponse(HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200) .build()) .responseBody(AbortableInputStream.create(new StringInputStream(""))) .build()); client.operationWithHostPrefix(b -> b.stringMember("123")); assertThat(mockHttpClient.getLastRequest().getUri().getHost()).isEqualTo("123-foo.localhost"); } @Test public void asyncValidHostPrefix_shouldPrefixEndpoint() { mockAsyncClient.stubNextResponse(HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200) .build()) .responseBody(AbortableInputStream.create(new StringInputStream(""))) .build()); asyncClient.operationWithHostPrefix(b -> b.stringMember("123")).join(); assertThat(mockAsyncClient.getLastRequest().getUri().getHost()).isEqualTo("123-foo.localhost"); } }
2,844
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/EndpointDiscoveryAndEndpointOverrideTest.java
package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletionException; import java.util.function.Consumer; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.core.client.builder.SdkClientBuilder; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.endpointdiscoveryrequiredtest.EndpointDiscoveryRequiredTestAsyncClient; import software.amazon.awssdk.services.endpointdiscoveryrequiredtest.EndpointDiscoveryRequiredTestClient; import software.amazon.awssdk.services.endpointdiscoveryrequiredwithcustomizationtest.EndpointDiscoveryRequiredWithCustomizationTestAsyncClient; import software.amazon.awssdk.services.endpointdiscoveryrequiredwithcustomizationtest.EndpointDiscoveryRequiredWithCustomizationTestClient; import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestAsyncClient; import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestClient; /** * Verify the behavior of endpoint discovery when combined with endpoint override configuration. */ @RunWith(Parameterized.class) public class EndpointDiscoveryAndEndpointOverrideTest { private static final String OPTIONAL_SERVICE_ENDPOINT = "https://awsendpointdiscoverytestservice.us-west-2.amazonaws.com"; private static final String REQUIRED_SERVICE_ENDPOINT = "https://awsendpointdiscoveryrequiredtestservice.us-west-2.amazonaws.com"; private static final String REQUIRED_CUSTOMIZED_SERVICE_ENDPOINT = "https://awsendpointdiscoveryrequiredwithcustomizationtestservice.us-west-2.amazonaws.com"; private static final String ENDPOINT_OVERRIDE = "https://endpointoverride"; private static final List<TestCase<?>> ALL_TEST_CASES = new ArrayList<>(); private final TestCase<?> testCase; static { // This first case (case 0/1) is different than other SDKs/the SEP. This should probably actually throw an exception. ALL_TEST_CASES.addAll(endpointDiscoveryOptionalCases(true, true, ENDPOINT_OVERRIDE + "/DescribeEndpoints", ENDPOINT_OVERRIDE + "/TestDiscoveryOptional")); ALL_TEST_CASES.addAll(endpointDiscoveryOptionalCases(true, false, OPTIONAL_SERVICE_ENDPOINT + "/DescribeEndpoints", OPTIONAL_SERVICE_ENDPOINT + "/TestDiscoveryOptional")); ALL_TEST_CASES.addAll(endpointDiscoveryOptionalCases(false, true, ENDPOINT_OVERRIDE + "/TestDiscoveryOptional")); ALL_TEST_CASES.addAll(endpointDiscoveryOptionalCases(false, false, OPTIONAL_SERVICE_ENDPOINT + "/TestDiscoveryOptional")); ALL_TEST_CASES.addAll(endpointDiscoveryRequiredCases(true, true)); ALL_TEST_CASES.addAll(endpointDiscoveryRequiredCases(true, false, REQUIRED_SERVICE_ENDPOINT + "/DescribeEndpoints")); ALL_TEST_CASES.addAll(endpointDiscoveryRequiredCases(false, true)); ALL_TEST_CASES.addAll(endpointDiscoveryRequiredCases(false, false)); // These cases are different from what one would expect. Even though endpoint discovery is required (based on the model), // if the customer specifies an endpoint override AND the service is customized, we actually bypass endpoint discovery. ALL_TEST_CASES.addAll(endpointDiscoveryRequiredAndCustomizedCases(true, true, ENDPOINT_OVERRIDE + "/TestDiscoveryRequired")); ALL_TEST_CASES.addAll(endpointDiscoveryRequiredAndCustomizedCases(true, false, REQUIRED_CUSTOMIZED_SERVICE_ENDPOINT + "/DescribeEndpoints")); ALL_TEST_CASES.addAll(endpointDiscoveryRequiredAndCustomizedCases(false, true, ENDPOINT_OVERRIDE + "/TestDiscoveryRequired")); ALL_TEST_CASES.addAll(endpointDiscoveryRequiredAndCustomizedCases(false, false)); } public EndpointDiscoveryAndEndpointOverrideTest(TestCase<?> testCase) { this.testCase = testCase; } @Before public void reset() { EndpointCapturingInterceptor.reset(); } @Parameterized.Parameters(name = "{index} - {0}") public static List<TestCase<?>> testCases() { return ALL_TEST_CASES; } @Test(timeout = 5_000) public void invokeTestCase() { try { testCase.callClient(); Assert.fail(); } catch (Throwable e) { // Unwrap async exceptions so that they can be tested the same as async ones. if (e instanceof CompletionException) { e = e.getCause(); } if (testCase.expectedPaths.length > 0) { // We're using fake endpoints, so we expect even "valid" requests to fail because of unknown host exceptions. assertThat(e.getCause()).hasRootCauseInstanceOf(UnknownHostException.class); } else { // If the requests are not expected to go through, we expect to see illegal state exceptions because the // client is configured incorrectly. assertThat(e).isInstanceOf(IllegalStateException.class); } } if (testCase.enforcePathOrder) { assertThat(EndpointCapturingInterceptor.ENDPOINTS).containsExactly(testCase.expectedPaths); } else { // Async is involved when order doesn't matter, so wait a little while until the expected number of paths arrive. while (EndpointCapturingInterceptor.ENDPOINTS.size() < testCase.expectedPaths.length) { Thread.yield(); } assertThat(EndpointCapturingInterceptor.ENDPOINTS).containsExactlyInAnyOrder(testCase.expectedPaths); } } private static List<TestCase<?>> endpointDiscoveryOptionalCases(boolean endpointDiscoveryEnabled, boolean endpointOverridden, String... expectedEndpoints) { TestCase<?> syncCase = new TestCase<>(createClient(EndpointDiscoveryTestClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled), endpointOverridden), c -> c.testDiscoveryOptional(r -> {}), caseName(EndpointDiscoveryTestClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints), false, expectedEndpoints); TestCase<?> asyncCase = new TestCase<>(createClient(EndpointDiscoveryTestAsyncClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled), endpointOverridden), c -> c.testDiscoveryOptional(r -> {}).join(), caseName(EndpointDiscoveryTestAsyncClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints), false, expectedEndpoints); return Arrays.asList(syncCase, asyncCase); } private static List<TestCase<?>> endpointDiscoveryRequiredCases(boolean endpointDiscoveryEnabled, boolean endpointOverridden, String... expectedEndpoints) { TestCase<?> syncCase = new TestCase<>(createClient(EndpointDiscoveryRequiredTestClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled), endpointOverridden), c -> c.testDiscoveryRequired(r -> {}), caseName(EndpointDiscoveryRequiredTestClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints), true, expectedEndpoints); TestCase<?> asyncCase = new TestCase<>(createClient(EndpointDiscoveryRequiredTestAsyncClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled), endpointOverridden), c -> c.testDiscoveryRequired(r -> {}).join(), caseName(EndpointDiscoveryRequiredTestAsyncClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints), true, expectedEndpoints); return Arrays.asList(syncCase, asyncCase); } private static List<TestCase<?>> endpointDiscoveryRequiredAndCustomizedCases(boolean endpointDiscoveryEnabled, boolean endpointOverridden, String... expectedEndpoints) { TestCase<?> syncCase = new TestCase<>(createClient(EndpointDiscoveryRequiredWithCustomizationTestClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled), endpointOverridden), c -> c.testDiscoveryRequired(r -> {}), caseName(EndpointDiscoveryRequiredWithCustomizationTestClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints), true, expectedEndpoints); TestCase<?> asyncCase = new TestCase<>(createClient(EndpointDiscoveryRequiredWithCustomizationTestAsyncClient.builder().endpointDiscoveryEnabled(endpointDiscoveryEnabled), endpointOverridden), c -> c.testDiscoveryRequired(r -> {}).join(), caseName(EndpointDiscoveryRequiredWithCustomizationTestAsyncClient.class, endpointDiscoveryEnabled, endpointOverridden, expectedEndpoints), true, expectedEndpoints); return Arrays.asList(syncCase, asyncCase); } private static <T> T createClient(AwsClientBuilder<?, T> clientBuilder, boolean endpointOverridden) { return clientBuilder.region(Region.US_WEST_2) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .applyMutation(c -> addEndpointOverride(c, endpointOverridden)) .overrideConfiguration(c -> c.retryPolicy(p -> p.numRetries(0)) .addExecutionInterceptor(new EndpointCapturingInterceptor())) .build(); } private static String caseName(Class<?> client, boolean endpointDiscoveryEnabled, boolean endpointOverridden, String... expectedEndpoints) { return "(Client=" + client.getSimpleName() + ", DiscoveryEnabled=" + endpointDiscoveryEnabled + ", EndpointOverridden=" + endpointOverridden + ") => (ExpectedEndpoints=" + Arrays.toString(expectedEndpoints) + ")"; } private static void addEndpointOverride(SdkClientBuilder<?, ?> builder, boolean endpointOverridden) { if (endpointOverridden) { builder.endpointOverride(URI.create(ENDPOINT_OVERRIDE)); } } private static class TestCase<T> { private final T client; private final Consumer<T> methodCall; private final String caseName; private final boolean enforcePathOrder; private final String[] expectedPaths; private TestCase(T client, Consumer<T> methodCall, String caseName, boolean enforcePathOrder, String... expectedPaths) { this.client = client; this.methodCall = methodCall; this.caseName = caseName; this.enforcePathOrder = enforcePathOrder; this.expectedPaths = expectedPaths; } private void callClient() { methodCall.accept(client); } @Override public String toString() { return caseName; } } private static class EndpointCapturingInterceptor implements ExecutionInterceptor { private static final List<String> ENDPOINTS = Collections.synchronizedList(new ArrayList<>()); @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { ENDPOINTS.add(context.httpRequest().getUri().toString()); } private static void reset() { ENDPOINTS.clear(); } } }
2,845
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/EndpointCapturingInterceptor.java
package software.amazon.awssdk.services; import java.util.ArrayList; import java.util.Collections; import java.util.List; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; public class EndpointCapturingInterceptor implements ExecutionInterceptor { private final List<String> endpoints = Collections.synchronizedList(new ArrayList<>()); @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { endpoints.add(context.httpRequest().getUri().toString()); throw new CaptureCompletedException(); } public List<String> endpoints() { return endpoints; } private void reset() { endpoints.clear(); } public class CaptureCompletedException extends RuntimeException { } }
2,846
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/ProfileFileConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.StringInputStream; public class ProfileFileConfigurationTest { @Test public void profileIsHonoredForCredentialsAndRegion() { EnvironmentVariableHelper.run(env -> { env.remove(SdkSystemSetting.AWS_REGION); env.remove(SdkSystemSetting.AWS_ACCESS_KEY_ID); env.remove(SdkSystemSetting.AWS_SECRET_ACCESS_KEY); String profileContent = "[profile foo]\n" + "region = us-banana-46\n" + "aws_access_key_id = profileIsHonoredForCredentials_akid\n" + "aws_secret_access_key = profileIsHonoredForCredentials_skid"; String profileName = "foo"; Signer signer = mock(Signer.class); ProtocolRestJsonClient client = ProtocolRestJsonClient.builder() .overrideConfiguration(overrideConfig(profileContent, profileName, signer)) .build(); Mockito.when(signer.sign(any(), any())).thenReturn(SdkHttpFullRequest.builder() .protocol("https") .host("test") .method(SdkHttpMethod.GET) .build()); try { client.allTypes(); } catch (SdkClientException e) { // expected } ArgumentCaptor<SdkHttpFullRequest> httpRequest = ArgumentCaptor.forClass(SdkHttpFullRequest.class); ArgumentCaptor<ExecutionAttributes> attributes = ArgumentCaptor.forClass(ExecutionAttributes.class); Mockito.verify(signer).sign(httpRequest.capture(), attributes.capture()); AwsCredentials credentials = attributes.getValue().getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS); assertThat(credentials.accessKeyId()).isEqualTo("profileIsHonoredForCredentials_akid"); assertThat(credentials.secretAccessKey()).isEqualTo("profileIsHonoredForCredentials_skid"); Region region = attributes.getValue().getAttribute(AwsExecutionAttribute.AWS_REGION); assertThat(region.id()).isEqualTo("us-banana-46"); assertThat(httpRequest.getValue().getUri().getHost()).contains("us-banana-46"); }); } private ClientOverrideConfiguration overrideConfig(String profileContent, String profileName, Signer signer) { return ClientOverrideConfiguration.builder() .defaultProfileFile(profileFile(profileContent)) .defaultProfileName(profileName) .retryPolicy(r -> r.numRetries(0)) .putAdvancedOption(SdkAdvancedClientOption.SIGNER, signer) .build(); } private ProfileFile profileFile(String content) { return ProfileFile.builder() .content(new StringInputStream(content)) .type(ProfileFile.Type.CONFIGURATION) .build(); } // TODO(sra-identity-and-auth): Should add test for the same using SRA way, to assert the identity in SignRequest and // region SignerProperty are per profile. // To do this, need ability to inject AuthScheme which uses mock HttpSigner. This is pending https://i.amazon.com/SMITHY-1450 }
2,847
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/TraceIdTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.awscore.interceptor.TraceIdExecutionInterceptor; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; import software.amazon.awssdk.utils.StringInputStream; /** * Verifies that the {@link TraceIdExecutionInterceptor} is actually wired up for AWS services. */ public class TraceIdTest { @Test public void traceIdInterceptorIsEnabled() { EnvironmentVariableHelper.run(env -> { env.set("AWS_LAMBDA_FUNCTION_NAME", "foo"); env.set("_X_AMZN_TRACE_ID", "bar"); try (MockSyncHttpClient mockHttpClient = new MockSyncHttpClient(); ProtocolRestJsonClient client = ProtocolRestJsonClient.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .httpClient(mockHttpClient) .build()) { mockHttpClient.stubNextResponse(HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(200) .build()) .responseBody(AbortableInputStream.create(new StringInputStream("{}"))) .build()); client.allTypes(); assertThat(mockHttpClient.getLastRequest().firstMatchingHeader("X-Amzn-Trace-Id")).hasValue("bar"); } }); } }
2,848
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/BlockingAsyncRequestResponseBodyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.allRequests; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.http.Fault; import com.github.tomakehurst.wiremock.stubbing.Scenario; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.lang.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.BlockingInputStreamAsyncRequestBody; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.async.BlockingOutputStreamAsyncRequestBody; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationRequest; import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationResponse; import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationRequest; import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationResponse; import software.amazon.awssdk.utils.StringInputStream; import software.amazon.awssdk.utils.ThreadFactoryBuilder; @Timeout(5) public class BlockingAsyncRequestResponseBodyTest { private final WireMockServer wireMock = new WireMockServer(0); private ProtocolRestJsonAsyncClient client; @BeforeEach public void setup() { wireMock.start(); client = ProtocolRestJsonAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); } @Test public void blockingWithExecutor_inputStreamWithMark_shouldRetry() { ExecutorService executorService = Executors.newSingleThreadExecutor(); int length = 1 << 20; String content = RandomStringUtils.randomAscii(length); StringInputStream stringInputStream = new StringInputStream(content); BufferedInputStream bufferedInputStream = new BufferedInputStream(stringInputStream); try { wireMock.stubFor(post(anyUrl()) .inScenario("retry at connect reset") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER))); wireMock.stubFor(post(anyUrl()) .inScenario("retry at connect reset") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody("{}"))); client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), AsyncRequestBody.fromInputStream(b -> b.inputStream(bufferedInputStream).contentLength( (long) length).executor(executorService).maxReadLimit(length + 1))).join(); List<LoggedRequest> requests = wireMock.findAll(allRequests()); assertThat(requests.get(0)) .extracting(LoggedRequest::getBody) .extracting(String::new) .isEqualTo(content); } finally { executorService.shutdownNow(); } } @Test public void blockingWithExecutor_sendsRightValues() { ExecutorService executorService = Executors.newSingleThreadExecutor(); try { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), AsyncRequestBody.fromInputStream(new StringInputStream("Hello"), 5L, executorService)) .join(); List<LoggedRequest> requests = wireMock.findAll(allRequests()); assertThat(requests).singleElement() .extracting(LoggedRequest::getBody) .extracting(String::new) .isEqualTo("Hello"); } finally { executorService.shutdownNow(); } } @Test public void blockingWithExecutor_canUnderUpload() { ExecutorService executorService = Executors.newSingleThreadExecutor(); try { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), AsyncRequestBody.fromInputStream(new StringInputStream("Hello"), 4L, executorService)) .join(); List<LoggedRequest> requests = wireMock.findAll(allRequests()); assertThat(requests).singleElement() .extracting(LoggedRequest::getBody) .extracting(String::new) .isEqualTo("Hell"); } finally { executorService.shutdownNow(); } } @Test public void blockingWithExecutor_canUnderUploadOneByteAtATime() { ExecutorService executorService = Executors.newSingleThreadExecutor(); try { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), AsyncRequestBody.fromInputStream(new TrickleInputStream(new StringInputStream("Hello")), 4L, executorService)) .join(); List<LoggedRequest> requests = wireMock.findAll(allRequests()); assertThat(requests).singleElement() .extracting(LoggedRequest::getBody) .extracting(String::new) .isEqualTo("Hell"); } finally { executorService.shutdownNow(); } } @Test public void blockingWithExecutor_propagatesReadFailures() { ExecutorService executorService = Executors.newSingleThreadExecutor(); try { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); CompletableFuture<StreamingInputOperationResponse> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), AsyncRequestBody.fromInputStream(new FailOnReadInputStream(), 5L, executorService)); assertThatThrownBy(responseFuture::join).hasRootCauseInstanceOf(IOException.class); } finally { executorService.shutdownNow(); } } @Test public void blockingWithExecutor_propagates400Failures() { ExecutorService executorService = Executors.newSingleThreadExecutor(); try { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(404).withBody("{}"))); CompletableFuture<?> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), AsyncRequestBody.fromInputStream(new StringInputStream("Hello"), 5L, executorService)); assertThatThrownBy(responseFuture::join).hasCauseInstanceOf(SdkServiceException.class); } finally { executorService.shutdownNow(); } } @Test public void blockingWithExecutor_propagates500Failures() { ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().daemonThreads(true).build()); try { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(500).withBody("{}"))); CompletableFuture<?> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), AsyncRequestBody.fromInputStream(new StringInputStream("Hello"), 5L, executorService)); assertThatThrownBy(responseFuture::join).hasCauseInstanceOf(SdkServiceException.class); } finally { executorService.shutdownNow(); } } @Test public void blockingInputStreamWithoutExecutor_sendsRightValues() { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(5L); CompletableFuture<?> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); body.writeInputStream(new StringInputStream("Hello")); responseFuture.join(); List<LoggedRequest> requests = wireMock.findAll(allRequests()); assertThat(requests).singleElement() .extracting(LoggedRequest::getBody) .extracting(String::new) .isEqualTo("Hello"); } @Test public void blockingInputStreamWithoutExecutor_canUnderUpload() { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(4L); CompletableFuture<?> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); body.writeInputStream(new StringInputStream("Hello")); responseFuture.join(); List<LoggedRequest> requests = wireMock.findAll(allRequests()); assertThat(requests).singleElement() .extracting(LoggedRequest::getBody) .extracting(String::new) .isEqualTo("Hell"); } @Test public void blockingInputStreamWithoutExecutor_canUnderUploadOneByteAtATime() { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(4L); CompletableFuture<?> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); body.writeInputStream(new TrickleInputStream(new StringInputStream("Hello"))); responseFuture.join(); List<LoggedRequest> requests = wireMock.findAll(allRequests()); assertThat(requests).singleElement() .extracting(LoggedRequest::getBody) .extracting(String::new) .isEqualTo("Hell"); } @Test public void blockingInputStreamWithoutExecutor_propagatesReadFailures() { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(5L); CompletableFuture<StreamingInputOperationResponse> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); assertThatThrownBy(() -> body.writeInputStream(new FailOnReadInputStream())).hasRootCauseInstanceOf(IOException.class); assertThatThrownBy(responseFuture::get) .hasCauseInstanceOf(SdkClientException.class) .hasMessageContaining("AsyncRequestBody.forBlockingInputStream does not support retries"); } @Test public void blockingInputStreamWithoutExecutor_propagates400Failures() { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(404).withBody("{}"))); BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(5L); CompletableFuture<?> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); body.writeInputStream(new StringInputStream("Hello")); assertThatThrownBy(responseFuture::join).hasCauseInstanceOf(SdkServiceException.class); } @Test public void blockingInputStreamWithoutExecutor_propagates500Failures() { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(500).withBody("{}"))); BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(5L); CompletableFuture<StreamingInputOperationResponse> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); body.writeInputStream(new StringInputStream("Hello")); assertThatThrownBy(responseFuture::get) .hasCauseInstanceOf(SdkClientException.class) .hasMessageContaining("AsyncRequestBody.forBlockingInputStream does not support retries"); } @Test public void blockingResponseTransformer_readsRightValue() { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("hello"))); CompletableFuture<ResponseInputStream<StreamingOutputOperationResponse>> responseFuture = client.streamingOutputOperation(StreamingOutputOperationRequest.builder().build(), AsyncResponseTransformer.toBlockingInputStream()); ResponseInputStream<StreamingOutputOperationResponse> responseStream = responseFuture.join(); assertThat(responseStream).asString(StandardCharsets.UTF_8).isEqualTo("hello"); assertThat(responseStream.response().sdkHttpResponse().statusCode()).isEqualTo(200); } @Test public void blockingResponseTransformer_abortCloseDoesNotThrow() throws IOException { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("hello"))); CompletableFuture<ResponseInputStream<StreamingOutputOperationResponse>> responseFuture = client.streamingOutputOperation(StreamingOutputOperationRequest.builder().build(), AsyncResponseTransformer.toBlockingInputStream()); ResponseInputStream<StreamingOutputOperationResponse> responseStream = responseFuture.join(); responseStream.abort(); responseStream.close(); } @Test public void blockingResponseTransformer_closeDoesNotThrow() throws IOException { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("hello"))); CompletableFuture<ResponseInputStream<StreamingOutputOperationResponse>> responseFuture = client.streamingOutputOperation(StreamingOutputOperationRequest.builder().build(), AsyncResponseTransformer.toBlockingInputStream()); ResponseInputStream<StreamingOutputOperationResponse> responseStream = responseFuture.join(); responseStream.close(); } @Test public void blockingOutputStreamWithoutExecutor_sendsRightValues() throws IOException { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(5L); CompletableFuture<?> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); try (OutputStream stream = body.outputStream()) { stream.write("Hello".getBytes(StandardCharsets.UTF_8)); } responseFuture.join(); List<LoggedRequest> requests = wireMock.findAll(allRequests()); assertThat(requests).singleElement() .extracting(LoggedRequest::getBody) .extracting(String::new) .isEqualTo("Hello"); } @Test public void blockingOutputStreamWithoutExecutor_canUnderUpload() throws IOException { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(4L); CompletableFuture<?> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); try (OutputStream stream = body.outputStream()) { stream.write("Hello".getBytes(StandardCharsets.UTF_8)); } responseFuture.join(); List<LoggedRequest> requests = wireMock.findAll(allRequests()); assertThat(requests).singleElement() .extracting(LoggedRequest::getBody) .extracting(String::new) .isEqualTo("Hell"); } @Test public void blockingOutputStreamWithoutExecutor_canUnderUploadOneByteAtATime() throws IOException { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(4L); CompletableFuture<?> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); try (OutputStream stream = body.outputStream()) { stream.write('H'); stream.write('e'); stream.write('l'); stream.write('l'); stream.write('o'); } responseFuture.join(); List<LoggedRequest> requests = wireMock.findAll(allRequests()); assertThat(requests).singleElement() .extracting(LoggedRequest::getBody) .extracting(String::new) .isEqualTo("Hell"); } @Test public void blockingOutputStreamWithoutExecutor_propagatesCancellations() { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(5L); CompletableFuture<StreamingInputOperationResponse> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); body.outputStream().cancel(); assertThatThrownBy(responseFuture::get).hasRootCauseInstanceOf(CancellationException.class); } @Test public void blockingOutputStreamWithoutExecutor_propagates400Failures() throws IOException { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(404).withBody("{}"))); BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(5L); CompletableFuture<?> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); try (OutputStream stream = body.outputStream()) { stream.write("Hello".getBytes(StandardCharsets.UTF_8)); } assertThatThrownBy(responseFuture::join).hasCauseInstanceOf(SdkServiceException.class); } @Test public void blockingOutputStreamWithoutExecutor_propagates500Failures() throws IOException { wireMock.stubFor(post(anyUrl()).willReturn(aResponse().withStatus(500).withBody("{}"))); BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(5L); CompletableFuture<StreamingInputOperationResponse> responseFuture = client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), body); try (OutputStream stream = body.outputStream()) { stream.write("Hello".getBytes(StandardCharsets.UTF_8)); } assertThatThrownBy(responseFuture::get) .hasCauseInstanceOf(SdkClientException.class) .hasMessageContaining("AsyncRequestBody.forBlockingOutputStream does not support retries"); } private static class FailOnReadInputStream extends InputStream { @Override public int read() throws IOException { throw new IOException("Intentionally failed to read."); } } private static class TrickleInputStream extends InputStream { private final InputStream delegate; private TrickleInputStream(InputStream delegate) { this.delegate = delegate; } @Override public int read() throws IOException { return delegate.read(); } @Override public int read(byte[] b) throws IOException { if (b.length == 0) { return 0; } return delegate.read(b, 0, 1); } @Override public int read(byte[] b, int off, int len) throws IOException { if (len == 0) { return 0; } return delegate.read(b, off, 1); } } }
2,849
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/EndpointDiscoveryRequestOverrideConfigTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; 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.AwsCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestAsyncClient; import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestClient; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; import software.amazon.awssdk.utils.StringInputStream; /** * Verifies that request-level overrides work with endpoint discovery. */ public class EndpointDiscoveryRequestOverrideConfigTest { private EndpointDiscoveryTestClient client; private EndpointDiscoveryTestAsyncClient asyncClient; private MockSyncHttpClient httpClient; private MockAsyncHttpClient asyncHttpClient; private static final AwsBasicCredentials CLIENT_CREDENTIALS = AwsBasicCredentials.create("ca", "cs"); private static final AwsBasicCredentials REQUEST_CREDENTIALS = AwsBasicCredentials.create("ra", "rs"); @BeforeEach public void setupClient() { httpClient = new MockSyncHttpClient(); asyncHttpClient = new MockAsyncHttpClient(); client = EndpointDiscoveryTestClient.builder() .credentialsProvider(StaticCredentialsProvider.create(CLIENT_CREDENTIALS)) .region(Region.US_EAST_1) .endpointDiscoveryEnabled(true) .httpClient(httpClient) .build(); asyncClient = EndpointDiscoveryTestAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(CLIENT_CREDENTIALS)) .region(Region.US_EAST_1) .endpointDiscoveryEnabled(true) .httpClient(asyncHttpClient) .build(); } @AfterEach public void cleanup() { httpClient.reset(); asyncHttpClient.reset(); } @Test public void syncClientCredentialsUsedByDefault() { httpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse()); client.testDiscoveryRequired(r -> {}); assertRequestsUsedCredentials(httpClient.getRequests(), CLIENT_CREDENTIALS); } @Test public void asyncClientCredentialsUsedByDefault() throws Exception { asyncHttpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse()); asyncClient.testDiscoveryRequired(r -> {}).get(10, TimeUnit.SECONDS); assertRequestsUsedCredentials(asyncHttpClient.getRequests(), CLIENT_CREDENTIALS); } @Test public void syncClientRequestCredentialsUsedIfOverridden() { httpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse()); client.testDiscoveryRequired(r -> r.overrideConfiguration(c -> c.credentialsProvider(() -> REQUEST_CREDENTIALS))); assertRequestsUsedCredentials(httpClient.getRequests(), REQUEST_CREDENTIALS); } @Test public void asyncClientRequestCredentialsUsedIfOverridden() throws Exception { asyncHttpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse()); asyncClient.testDiscoveryRequired(r -> r.overrideConfiguration(c -> c.credentialsProvider(() -> REQUEST_CREDENTIALS))) .get(10, TimeUnit.SECONDS); assertRequestsUsedCredentials(asyncHttpClient.getRequests(), REQUEST_CREDENTIALS); } @Test public void syncClientRequestHeadersUsed() { httpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse()); client.testDiscoveryRequired(r -> r.overrideConfiguration(c -> c.putHeader("Foo", "Bar"))); assertRequestsHadHeader(httpClient.getRequests(), "Foo", "Bar"); } @Test public void asyncClientRequestHeadersUsed() throws Exception { asyncHttpClient.stubResponses(successfulEndpointDiscoveryResponse(), successfulResponse()); asyncClient.testDiscoveryRequired(r -> r.overrideConfiguration(c -> c.putHeader("Foo", "Bar"))) .get(10, TimeUnit.SECONDS); assertRequestsHadHeader(asyncHttpClient.getRequests(), "Foo", "Bar"); } private void assertRequestsHadHeader(List<SdkHttpRequest> requests, String headerName, String headerValue) { assertThat(requests).hasSize(2); assertThat(requests).allSatisfy(request -> { assertThat(request.firstMatchingHeader(headerName)).hasValue(headerValue); }); } private void assertRequestsUsedCredentials(List<SdkHttpRequest> requests, AwsBasicCredentials clientCredentials) { assertThat(requests).hasSize(2); assertRequestUsedCredentials(requests.get(0), clientCredentials); assertRequestUsedCredentials(requests.get(1), clientCredentials); } private void assertRequestUsedCredentials(SdkHttpRequest request, AwsCredentials expectedCredentials) { assertThat(request.firstMatchingHeader("Authorization")).isPresent().hasValueSatisfying(authorizationHeader -> { assertThat(authorizationHeader).contains(" Credential=" + expectedCredentials.accessKeyId() + "/"); }); } private HttpExecuteResponse successfulEndpointDiscoveryResponse() { String responseData = "{" + " \"Endpoints\": [{" + " \"Address\": \"something\"," + " \"CachePeriodInMinutes\": 30" + " }]" + "}"; AbortableInputStream responseStream = AbortableInputStream.create(new StringInputStream(responseData), () -> {}); return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(200) .appendHeader("Content-Length", Integer.toString(responseData.length())) .build()) .responseBody(responseStream) .build(); } private HttpExecuteResponse successfulResponse() { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); } }
2,850
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/DualstackEndpointTest.java
package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.StringInputStream; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class DualstackEndpointTest { @Parameterized.Parameter public TestCase testCase; @Test public void resolvesCorrectEndpoint() { String systemPropertyBeforeTest = System.getProperty(SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.property()); EnvironmentVariableHelper helper = new EnvironmentVariableHelper(); try { ProtocolRestJsonClientBuilder builder = ProtocolRestJsonClient.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()); if (testCase.clientSetting != null) { builder.dualstackEnabled(testCase.clientSetting); } if (testCase.systemPropSetting != null) { System.setProperty(SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.property(), testCase.systemPropSetting); } if (testCase.envVarSetting != null) { helper.set(SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.environmentVariable(), testCase.envVarSetting); } ProfileFile.Builder profileFile = ProfileFile.builder().type(ProfileFile.Type.CONFIGURATION); if (testCase.profileSetting != null) { profileFile.content(new StringInputStream("[default]\n" + ProfileProperty.USE_DUALSTACK_ENDPOINT + " = " + testCase.profileSetting)); } else { profileFile.content(new StringInputStream("")); } EndpointCapturingInterceptor interceptor = new EndpointCapturingInterceptor(); builder.overrideConfiguration(c -> c.defaultProfileFile(profileFile.build()) .defaultProfileName("default") .addExecutionInterceptor(interceptor)); if (testCase instanceof SuccessCase) { ProtocolRestJsonClient client = builder.build(); try { client.allTypes(); } catch (EndpointCapturingInterceptor.CaptureCompletedException e) { // Expected } boolean expectedDualstackEnabled = ((SuccessCase) testCase).expectedValue; String expectedEndpoint = expectedDualstackEnabled ? "https://customresponsemetadata.us-west-2.api.aws/2016-03-11/allTypes" : "https://customresponsemetadata.us-west-2.amazonaws.com/2016-03-11/allTypes"; assertThat(interceptor.endpoints()).singleElement().isEqualTo(expectedEndpoint); } else { FailureCase failure = Validate.isInstanceOf(FailureCase.class, testCase, "Unexpected test case type."); assertThatThrownBy(builder::build).hasMessageContaining(failure.exceptionMessage); } } finally { if (systemPropertyBeforeTest != null) { System.setProperty(SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.property(), systemPropertyBeforeTest); } else { System.clearProperty(SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.property()); } helper.reset(); } } @Parameterized.Parameters(name = "{0}") public static Iterable<TestCase> testCases() { return Arrays.asList(new SuccessCase(true, "false", "false", "false", true, "Client highest priority (true)"), new SuccessCase(false, "true", "true", "true", false, "Client highest priority (false)"), new SuccessCase(null, "true", "false", "false", true, "System property second priority (true)"), new SuccessCase(null, "false", "true", "true", false, "System property second priority (false)"), new SuccessCase(null, null, "true", "false", true, "Env var third priority (true)"), new SuccessCase(null, null, "false", "true", false, "Env var third priority (false)"), new SuccessCase(null, null, null, "true", true, "Profile last priority (true)"), new SuccessCase(null, null, null, "false", false, "Profile last priority (false)"), new SuccessCase(null, null, null, null, false, "Default is false."), new SuccessCase(null, "tRuE", null, null, true, "System property is not case sensitive."), new SuccessCase(null, null, "tRuE", null, true, "Env var is not case sensitive."), new SuccessCase(null, null, null, "tRuE", true, "Profile property is not case sensitive."), new FailureCase(null, "FOO", null, null, "FOO", "Invalid system property values fail."), new FailureCase(null, null, "FOO", null, "FOO", "Invalid env var values fail."), new FailureCase(null, null, null, "FOO", "FOO", "Invalid profile values fail.")); } public static class TestCase { private final Boolean clientSetting; private final String envVarSetting; private final String systemPropSetting; private final String profileSetting; private final String caseName; public TestCase(Boolean clientSetting, String systemPropSetting, String envVarSetting, String profileSetting, String caseName) { this.clientSetting = clientSetting; this.envVarSetting = envVarSetting; this.systemPropSetting = systemPropSetting; this.profileSetting = profileSetting; this.caseName = caseName; } @Override public String toString() { return caseName; } } public static class SuccessCase extends TestCase { private final boolean expectedValue; public SuccessCase(Boolean clientSetting, String systemPropSetting, String envVarSetting, String profileSetting, boolean expectedValue, String caseName) { super(clientSetting, systemPropSetting, envVarSetting, profileSetting, caseName); this.expectedValue = expectedValue; } } private static class FailureCase extends TestCase { private final String exceptionMessage; public FailureCase(Boolean clientSetting, String systemPropSetting, String envVarSetting, String profileSetting, String exceptionMessage, String caseName) { super(clientSetting, systemPropSetting, envVarSetting, profileSetting, caseName); this.exceptionMessage = exceptionMessage; } } }
2,851
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/ModelSerializationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.IOException; import java.time.Instant; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest; import software.amazon.awssdk.services.protocolrestjson.model.BaseType; import software.amazon.awssdk.services.protocolrestjson.model.RecursiveStructType; import software.amazon.awssdk.services.protocolrestjson.model.SimpleStruct; import software.amazon.awssdk.services.protocolrestjson.model.StructWithNestedBlobType; import software.amazon.awssdk.services.protocolrestjson.model.StructWithTimestamp; import software.amazon.awssdk.services.protocolrestjson.model.SubTypeOne; /** * Verify that modeled objects can be marshalled using Jackson. */ public class ModelSerializationTest { @Test public void jacksonSerializationWorksForEmptyRequestObjects() throws IOException { validateJacksonSerialization(AllTypesRequest.builder().build()); } @Test public void jacksonSerialization_mapWithNullValue_shouldWork() throws IOException { Map<String, SimpleStruct> mapOfStringToStruct = new HashMap<>(); mapOfStringToStruct.put("test1", null); mapOfStringToStruct.put("test2", null); validateJacksonSerialization(AllTypesRequest.builder().mapOfStringToStruct(mapOfStringToStruct).build()); } @Test public void jacksonSerializationWorksForPopulatedRequestModels() throws IOException { SdkBytes blob = SdkBytes.fromUtf8String("foo"); SimpleStruct simpleStruct = SimpleStruct.builder().stringMember("foo").build(); StructWithTimestamp structWithTimestamp = StructWithTimestamp.builder().nestedTimestamp(Instant.EPOCH).build(); StructWithNestedBlobType structWithNestedBlob = StructWithNestedBlobType.builder().nestedBlob(blob).build(); RecursiveStructType recursiveStruct = RecursiveStructType.builder() .recursiveStruct(RecursiveStructType.builder().build()) .build(); BaseType baseType = BaseType.builder().baseMember("foo").build(); SubTypeOne subtypeOne = SubTypeOne.builder().subTypeOneMember("foo").build(); validateJacksonSerialization(AllTypesRequest.builder() .stringMember("foo") .integerMember(5) .booleanMember(true) .floatMember(5F) .doubleMember(5D) .longMember(5L) .simpleList("foo", "bar") .listOfMaps(singletonList(singletonMap("foo", "bar"))) .listOfMapsOfStringToStruct(singletonList(singletonMap("bar", simpleStruct))) .listOfListOfMapsOfStringToStruct( singletonList(singletonList(singletonMap("bar", simpleStruct)))) .listOfStructs(simpleStruct) .mapOfStringToIntegerList(singletonMap("foo", singletonList(5))) .mapOfStringToStruct(singletonMap("foo", simpleStruct)) .timestampMember(Instant.EPOCH) .structWithNestedTimestampMember(structWithTimestamp) .blobArg(blob) .structWithNestedBlob(structWithNestedBlob) .blobMap(singletonMap("foo", blob)) .listOfBlobs(blob, blob) .recursiveStruct(recursiveStruct) .polymorphicTypeWithSubTypes(baseType) .polymorphicTypeWithoutSubTypes(subtypeOne) .enumMember("foo") .listOfEnumsWithStrings("foo", "bar") .mapOfEnumToEnumWithStrings(singletonMap("foo", "bar")) .build()); } private void validateJacksonSerialization(AllTypesRequest original) throws IOException { SimpleModule instantModule = new SimpleModule(); instantModule.addSerializer(Instant.class, new InstantSerializer()); instantModule.addDeserializer(Instant.class, new InstantDeserializer()); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(instantModule); String serialized = mapper.writeValueAsString(original.toBuilder()); AllTypesRequest deserialized = mapper.readValue(serialized, AllTypesRequest.serializableBuilderClass()).build(); assertThat(deserialized).isEqualTo(original); } private class InstantSerializer extends JsonSerializer<Instant> { @Override public void serialize(Instant t, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(t.toString()); } } private class InstantDeserializer extends JsonDeserializer<Instant> { @Override public Instant deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { return Instant.parse(jsonParser.getText()); } } }
2,852
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/ExecutionAttributesTest.java
package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import java.util.concurrent.CompletionException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest; public class ExecutionAttributesTest { private static final ConcurrentMap<String, ExecutionAttribute<Object>> ATTR_POOL = new ConcurrentHashMap<>(); private static ExecutionAttribute<Object> attr(String name) { name = ExecutionAttributesTest.class.getName() + ":" + name; return ATTR_POOL.computeIfAbsent(name, ExecutionAttribute::new); } @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void syncClient_disableHostPrefixInjection_isPresent() { ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class); ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture()); ProtocolRestJsonClient sync = ProtocolRestJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar"))) .region(Region.US_WEST_2) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor) .putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true)) .build(); thrown.expect(RuntimeException.class); try { sync.allTypes(); } finally { ExecutionAttributes attributes = attributesCaptor.getValue(); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.DISABLE_HOST_PREFIX_INJECTION)).isTrue(); sync.close(); } } @Test public void asyncClient_disableHostPrefixInjection_isPresent() { ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class); ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture()); ProtocolRestJsonAsyncClient async = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar"))) .region(Region.US_WEST_2) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor) .putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true)) .build(); thrown.expect(CompletionException.class); try { async.allTypes().join(); } finally { ExecutionAttributes attributes = attributesCaptor.getValue(); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.DISABLE_HOST_PREFIX_INJECTION)).isTrue(); async.close(); } } @Test public void asyncClient_clientOverrideExecutionAttribute() { ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class); ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture()); ExecutionAttribute testAttribute = attr("TestAttribute"); String testValue = "TestValue"; ProtocolRestJsonAsyncClient async = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar"))) .region(Region.US_WEST_2) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor) .putExecutionAttribute(testAttribute, testValue)) .build(); thrown.expect(CompletionException.class); try { async.allTypes().join(); } finally { ExecutionAttributes attributes = attributesCaptor.getValue(); assertThat(attributes.getAttribute(testAttribute)).isEqualTo(testValue); async.close(); } } @Test public void asyncClient_requestOverrideExecutionAttribute() { ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class); ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture()); ExecutionAttribute testAttribute = attr("TestAttribute"); String testValue = "TestValue"; ProtocolRestJsonAsyncClient async = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar"))) .region(Region.US_WEST_2) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)) .build(); AllTypesRequest request = AllTypesRequest.builder().overrideConfiguration( c -> c.putExecutionAttribute(testAttribute, testValue)) .build(); thrown.expect(CompletionException.class); try { async.allTypes(request).join(); } finally { ExecutionAttributes attributes = attributesCaptor.getValue(); assertThat(attributes.getAttribute(testAttribute)).isEqualTo(testValue); async.close(); } } @Test public void asyncClient_requestOverrideExecutionAttributesHavePrecedence() { ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class); ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture()); ExecutionAttribute testAttribute = attr("TestAttribute"); String testValue = "TestValue"; ProtocolRestJsonAsyncClient async = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar"))) .region(Region.US_WEST_2) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor).putExecutionAttribute(testAttribute, testValue)) .build(); String overwrittenValue = "TestValue2"; AllTypesRequest request = AllTypesRequest.builder().overrideConfiguration( c -> c.putExecutionAttribute(testAttribute, overwrittenValue)) .build(); thrown.expect(CompletionException.class); try { async.allTypes(request).join(); } finally { ExecutionAttributes attributes = attributesCaptor.getValue(); assertThat(attributes.getAttribute(testAttribute)).isEqualTo(overwrittenValue); async.close(); } } @Test public void syncClient_requestOverrideExecutionAttribute() { ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class); ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture()); ExecutionAttribute testAttribute = attr("TestAttribute"); String testValue = "TestValue"; ProtocolRestJsonClient sync = ProtocolRestJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar"))) .region(Region.US_WEST_2) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)) .build(); AllTypesRequest request = AllTypesRequest.builder().overrideConfiguration( c -> c.putExecutionAttribute(testAttribute, testValue)) .build(); thrown.expect(RuntimeException.class); try { sync.allTypes(request); } finally { ExecutionAttributes attributes = attributesCaptor.getValue(); assertThat(attributes.getAttribute(testAttribute)).isEqualTo(testValue); sync.close(); } } @Test public void syncClient_requestOverrideExecutionAttributesHavePrecedence() { ExecutionInterceptor interceptor = mock(ExecutionInterceptor.class); ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); doThrow(new RuntimeException("BOOM")).when(interceptor).beforeExecution(any(Context.BeforeExecution.class), attributesCaptor.capture()); ExecutionAttribute testAttribute = attr("TestAttribute"); String testValue = "TestValue"; ProtocolRestJsonClient sync = ProtocolRestJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar"))) .region(Region.US_WEST_2) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor).putExecutionAttribute(testAttribute, testValue)) .build(); String overwrittenValue = "TestValue2"; AllTypesRequest request = AllTypesRequest.builder().overrideConfiguration( c -> c.putExecutionAttribute(testAttribute, overwrittenValue)) .build(); thrown.expect(RuntimeException.class); try { sync.allTypes(request); } finally { ExecutionAttributes attributes = attributesCaptor.getValue(); assertThat(attributes.getAttribute(testAttribute)).isEqualTo(overwrittenValue); sync.close(); } } @Test public void testExecutionAttributesMerge() { ExecutionAttributes lowerPrecedence = new ExecutionAttributes(); for (int i = 0; i < 3; i++) { lowerPrecedence.putAttribute(getAttribute(i), 1); } ExecutionAttributes higherPrecendence = new ExecutionAttributes(); for (int i = 2; i < 4; i++) { higherPrecendence.putAttribute(getAttribute(i), 2); } ExecutionAttributes expectedAttributes = new ExecutionAttributes(); for (int i = 0; i < 4; i++) { expectedAttributes.putAttribute(getAttribute(i), i >= 2 ? 2 : 1); } ExecutionAttributes merged = higherPrecendence.merge(lowerPrecedence); assertThat(merged.getAttributes()).isEqualTo(expectedAttributes.getAttributes()); } @Test public void testCopyBuilder() { ExecutionAttributes testAttributes = new ExecutionAttributes(); for (int i = 0; i < 3; i++) { testAttributes.putAttribute(getAttribute(i), 1); } ExecutionAttributes copy = testAttributes.copy(); assertThat(copy.getAttributes()).isEqualTo(testAttributes.getAttributes()); } @Test public void testAttributeEquals() { ExecutionAttribute attribute1 = getAttribute(0); ExecutionAttribute attribute2 = getAttribute(0); assertThat(attribute1).isEqualTo(attribute1); assertThat(attribute1).isEqualTo(attribute2); assertThat(attribute1).isNotEqualTo(null); } private ExecutionAttribute getAttribute(int i) { return attr("TestAttribute" + i); } }
2,853
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/HttpChecksumValidationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.util.concurrent.CompletionException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumValidation; 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.core.sync.RequestBody; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.model.ChecksumAlgorithm; import software.amazon.awssdk.services.protocolrestjson.model.ChecksumMode; import software.amazon.awssdk.services.protocolrestjson.model.GetOperationWithChecksumResponse; import software.amazon.awssdk.services.protocolrestjson.model.OperationWithChecksumNonStreamingResponse; public class HttpChecksumValidationTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private ProtocolRestJsonClient client; private ProtocolRestJsonAsyncClient asyncClient; @Before public void setupClient() { client = ProtocolRestJsonClient.builder() .credentialsProvider(AnonymousCredentialsProvider.create()) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .overrideConfiguration( // TODO(sra-identity-and-auth): we should remove these // overrides once we set up codegen to set chunk-encoding to true // for requests that are streaming and checksum-enabled o -> o.addExecutionInterceptor(new CaptureChecksumValidationInterceptor()) .putExecutionAttribute( ENABLE_CHUNKED_ENCODING, true )) .build(); asyncClient = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .overrideConfiguration(o -> o.addExecutionInterceptor(new CaptureChecksumValidationInterceptor())) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); } @After public void clear() { CaptureChecksumValidationInterceptor.reset(); } @Test public void syncClientValidateStreamingResponse() { String expectedChecksum = "i9aeUg=="; stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32"); client.putOperationWithChecksum(r -> r .checksumAlgorithm(ChecksumAlgorithm.CRC32), RequestBody.fromString("Hello world"), ResponseTransformer.toBytes()); verify(putRequestedFor(urlEqualTo("/")).withHeader("x-amz-trailer", equalTo("x-amz-checksum-crc32"))); verify(putRequestedFor(urlEqualTo("/")).withRequestBody(containing("x-amz-checksum-crc32:" + expectedChecksum))); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = client.getOperationWithChecksum(r -> r.checksumMode(ChecksumMode.ENABLED), ResponseTransformer.toBytes()); assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32); } @Test public void syncClientValidateStreamingResponseZeroByte() { String expectedChecksum = "AAAAAA=="; stubWithCRC32AndSha256Checksum("", expectedChecksum, "crc32"); client.putOperationWithChecksum(r -> r .checksumAlgorithm(ChecksumAlgorithm.CRC32), RequestBody.fromString(""), ResponseTransformer.toBytes()); verify(putRequestedFor(urlEqualTo("/")).withHeader("x-amz-trailer", equalTo("x-amz-checksum-crc32"))); verify(putRequestedFor(urlEqualTo("/")).withRequestBody(containing("x-amz-checksum-crc32:" + expectedChecksum))); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = client.getOperationWithChecksum(r -> r.checksumMode(ChecksumMode.ENABLED), ResponseTransformer.toBytes()); assertThat(responseBytes.asUtf8String()).isEmpty(); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32); } @Test public void syncClientValidateNonStreamingResponse() { String expectedChecksum = "lzlLIA=="; stubWithCRC32AndSha256Checksum("{\"stringMember\":\"Hello world\"}", expectedChecksum, "crc32"); client.operationWithChecksumNonStreaming( r -> r.stringMember("Hello world").checksumAlgorithm(ChecksumAlgorithm.CRC32) // TODO(sra-identity-and-auth): we should remove these // overrides once we set up codegen to set chunk-encoding to true // for requests that are streaming and checksum-enabled .overrideConfiguration(c -> c.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, false)) ); verify(postRequestedFor(urlEqualTo("/")).withHeader("x-amz-checksum-crc32", equalTo(expectedChecksum))); OperationWithChecksumNonStreamingResponse operationWithChecksumNonStreamingResponse = client.operationWithChecksumNonStreaming(o -> o.checksumMode(ChecksumMode.ENABLED)); assertThat(operationWithChecksumNonStreamingResponse.stringMember()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32); } @Test public void syncClientValidateNonStreamingResponseZeroByte() { String expectedChecksum = "o6a/Qw=="; stubWithCRC32AndSha256Checksum("{}", expectedChecksum, "crc32"); client.operationWithChecksumNonStreaming( r -> r.checksumAlgorithm(ChecksumAlgorithm.CRC32) // TODO(sra-identity-and-auth): we should remove these // overrides once we set up codegen to set chunk-encoding to true // for requests that are streaming and checksum-enabled .overrideConfiguration(c -> c.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, false)) ); verify(postRequestedFor(urlEqualTo("/")).withHeader("x-amz-checksum-crc32", equalTo(expectedChecksum))); OperationWithChecksumNonStreamingResponse operationWithChecksumNonStreamingResponse = client.operationWithChecksumNonStreaming(o -> o.checksumMode(ChecksumMode.ENABLED)); assertThat(operationWithChecksumNonStreamingResponse.stringMember()).isNull(); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32); } @Test public void syncClientValidateStreamingResponseForceSkip() { String expectedChecksum = "i9aeUg=="; stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32"); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = client.getOperationWithChecksum( r -> r.checksumMode(ChecksumMode.ENABLED).overrideConfiguration( o -> o.putExecutionAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION, ChecksumValidation.FORCE_SKIP)), ResponseTransformer.toBytes()); assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.FORCE_SKIP); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull(); } @Test public void syncClientValidateStreamingResponseNoAlgorithmInResponse() { stubWithNoChecksum(); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = client.getOperationWithChecksum( r -> r.checksumMode(ChecksumMode.ENABLED), ResponseTransformer.toBytes()); assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull(); } @Test public void syncClientValidateStreamingResponseNoAlgorithmFoundInClient() { String expectedChecksum = "someNewAlgorithmCalculatedValue"; stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc64"); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = client.getOperationWithChecksum( r -> r.checksumMode(ChecksumMode.ENABLED), ResponseTransformer.toBytes()); assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull(); } @Test public void syncClientValidateStreamingResponseWithValidationFailed() { String expectedChecksum = "i9aeUg="; stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32"); assertThatExceptionOfType(SdkClientException.class) .isThrownBy(() -> client.getOperationWithChecksum( r -> r.checksumMode(ChecksumMode.ENABLED), ResponseTransformer.toBytes())) .withMessage("Unable to unmarshall response (Data read has a different checksum than expected. Was i9aeUg==, " + "but expected i9aeUg=). Response Code: 200, Response Text: OK"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32); } @Test public void syncClientSkipsValidationWhenFeatureDisabled() { String expectedChecksum = "i9aeUg=="; stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32"); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = client.getOperationWithChecksum(r -> r.stringMember("foo"), ResponseTransformer.toBytes()); assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isNull(); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull(); } //Async @Test public void asyncClientValidateStreamingResponse() { String expectedChecksum = "i9aeUg=="; stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32"); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = asyncClient.getOperationWithChecksum(r -> r.checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()).join(); assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32); } @Test public void asyncClientValidateStreamingResponseZeroByte() { String expectedChecksum = "AAAAAA=="; stubWithCRC32AndSha256Checksum("", expectedChecksum, "crc32"); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = asyncClient.getOperationWithChecksum(r -> r.checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()).join(); assertThat(responseBytes.asUtf8String()).isEmpty(); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32); } @Test public void asyncClientValidateNonStreamingResponse() { String expectedChecksum = "lzlLIA=="; stubWithCRC32AndSha256Checksum("{\"stringMember\":\"Hello world\"}", expectedChecksum, "crc32"); OperationWithChecksumNonStreamingResponse response = asyncClient.operationWithChecksumNonStreaming( o -> o.checksumMode(ChecksumMode.ENABLED) // TODO(sra-identity-and-auth): we should remove these // overrides once we set up codegen to set chunk-encoding to true // for requests that are streaming and checksum-enabled .overrideConfiguration(c -> c.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, false))).join(); assertThat(response.stringMember()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32); } @Test public void asyncClientValidateNonStreamingResponseZeroByte() { String expectedChecksum = "o6a/Qw=="; stubWithCRC32AndSha256Checksum("{}", expectedChecksum, "crc32"); OperationWithChecksumNonStreamingResponse operationWithChecksumNonStreamingResponse = asyncClient.operationWithChecksumNonStreaming( o -> o.checksumMode(ChecksumMode.ENABLED) // TODO(sra-identity-and-auth): we should remove these // overrides once we set up codegen to set chunk-encoding to true // for requests that are streaming and checksum-enabled .overrideConfiguration(c -> c.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, false))).join(); assertThat(operationWithChecksumNonStreamingResponse.stringMember()).isNull(); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32); } @Test public void asyncClientValidateStreamingResponseForceSkip() { String expectedChecksum = "i9aeUg=="; stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32"); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = asyncClient.getOperationWithChecksum( r -> r.checksumMode(ChecksumMode.ENABLED).overrideConfiguration( o -> o.putExecutionAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION, ChecksumValidation.FORCE_SKIP)), AsyncResponseTransformer.toBytes()).join(); assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.FORCE_SKIP); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull(); } @Test public void asyncClientValidateStreamingResponseNoAlgorithmInResponse() { stubWithNoChecksum(); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = asyncClient.getOperationWithChecksum( r -> r.checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()).join(); assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull(); } @Test public void asyncClientValidateStreamingResponseNoAlgorithmFoundInClient() { String expectedChecksum = "someNewAlgorithmCalculatedValue"; stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc64"); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = asyncClient.getOperationWithChecksum( r -> r.checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()).join(); assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull(); } @Test public void asyncClientValidateStreamingResponseWithValidationFailed() { String expectedChecksum = "i9aeUg="; stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32"); assertThatExceptionOfType(CompletionException.class) .isThrownBy(() -> asyncClient.getOperationWithChecksum( r -> r.checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()).join()) .withMessage("software.amazon.awssdk.core.exception.SdkClientException: Data read has a different checksum" + " than expected. Was i9aeUg==, but expected i9aeUg="); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isEqualTo(ChecksumValidation.VALIDATED); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isEqualTo(Algorithm.CRC32); } @Test public void asyncClientSkipsValidationWhenFeatureDisabled() { String expectedChecksum = "i9aeUg=="; stubWithCRC32AndSha256Checksum("Hello world", expectedChecksum, "crc32"); ResponseBytes<GetOperationWithChecksumResponse> responseBytes = asyncClient.getOperationWithChecksum(r -> r.stringMember("foo"), AsyncResponseTransformer.toBytes()).join(); assertThat(responseBytes.asUtf8String()).isEqualTo("Hello world"); assertThat(CaptureChecksumValidationInterceptor.checksumValidation).isNull(); assertThat(CaptureChecksumValidationInterceptor.expectedAlgorithm).isNull(); } private void stubWithCRC32AndSha256Checksum(String body, String checksumValue, String algorithmName) { ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(200) .withHeader("x-amz-checksum-" + algorithmName, checksumValue) .withHeader("content-length", String.valueOf(body.length())) .withBody(body); stubFor(get(anyUrl()).willReturn(responseBuilder)); stubFor(put(anyUrl()).willReturn(responseBuilder)); stubFor(post(anyUrl()).willReturn(responseBuilder)); } private void stubWithNoChecksum() { ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(200) .withHeader("content-length", String.valueOf("Hello world".length())) .withBody("Hello world"); stubFor(get(anyUrl()).willReturn(responseBuilder)); stubFor(put(anyUrl()).willReturn(responseBuilder)); stubFor(post(anyUrl()).willReturn(responseBuilder)); } private static class CaptureChecksumValidationInterceptor implements ExecutionInterceptor { private static Algorithm expectedAlgorithm; private static ChecksumValidation checksumValidation; public static void reset() { expectedAlgorithm = null; checksumValidation = null; } @Override public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) { expectedAlgorithm = executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_CHECKSUM_VALIDATION_ALGORITHM).orElse(null); checksumValidation = executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION).orElse(null); } @Override public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) { expectedAlgorithm = executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_CHECKSUM_VALIDATION_ALGORITHM).orElse(null); checksumValidation = executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION).orElse(null); } } }
2,854
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/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; 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.mock; import static org.mockito.Mockito.when; import com.github.tomakehurst.wiremock.junit.WireMockRule; import io.reactivex.Flowable; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.assertj.core.api.AbstractThrowableAssert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.stubbing.Answer; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryFailedException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.SdkInternalTestAdvancedClientOption; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestAsyncClient; import software.amazon.awssdk.services.endpointdiscoverytest.EndpointDiscoveryTestClient; import software.amazon.awssdk.services.endpointdiscoverytest.model.EndpointDiscoveryTestException; public class EndpointDiscoveryTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private SdkHttpClient mockSyncClient; private SdkAsyncHttpClient mockAsyncClient; private EndpointDiscoveryTestClient client; private EndpointDiscoveryTestAsyncClient asyncClient; @Before public void setupClient() { mockSyncClient = mock(SdkHttpClient.class); client = EndpointDiscoveryTestClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create( "akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .endpointDiscoveryEnabled(true) .overrideConfiguration(c -> c.putAdvancedOption( SdkInternalTestAdvancedClientOption.ENDPOINT_OVERRIDDEN_OVERRIDE, false)) .httpClient(mockSyncClient) .build(); mockAsyncClient = mock(SdkAsyncHttpClient.class); asyncClient = EndpointDiscoveryTestAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .endpointDiscoveryEnabled(true) .overrideConfiguration(c -> c.putAdvancedOption( SdkInternalTestAdvancedClientOption.ENDPOINT_OVERRIDDEN_OVERRIDE, false)) .httpClient(mockAsyncClient) .build(); } @Test public void syncRequiredOperation_EmptyEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() { stubResponse(mockSyncClient, 200, "{}"); assertThatThrownBy(() -> client.testDiscoveryRequired(r -> { })) .isInstanceOf(EndpointDiscoveryFailedException.class); } @Test public void asyncRequiredOperation_EmptyEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() { stubResponse(mockAsyncClient, 200, "{}"); assertAsyncRequiredOperationCallThrowable() .isInstanceOf(EndpointDiscoveryFailedException.class) .hasCauseInstanceOf(IllegalArgumentException.class); } @Test public void syncRequiredOperation_NonRetryableEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() { stubResponse(mockSyncClient, 404, "localhost", 60); assertThatThrownBy(() -> client.testDiscoveryRequired(r -> { })) .isInstanceOf(EndpointDiscoveryFailedException.class) .hasCauseInstanceOf(EndpointDiscoveryTestException.class); } @Test public void asyncRequiredOperation_NonRetryableEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() { stubResponse(mockAsyncClient, 404, "localhost", 60); assertAsyncRequiredOperationCallThrowable() .isInstanceOf(EndpointDiscoveryFailedException.class); } @Test public void syncRequiredOperation_RetryableEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() { stubResponse(mockSyncClient, 500, "localhost", 60); assertThatThrownBy(() -> client.testDiscoveryRequired(r -> { })) .isInstanceOf(EndpointDiscoveryFailedException.class) .hasCauseInstanceOf(EndpointDiscoveryTestException.class); } @Test public void asyncRequiredOperation_RetryableEndpointDiscoveryResponse_CausesEndpointDiscoveryFailedException() { stubResponse(mockAsyncClient, 500, "localhost", 60); assertAsyncRequiredOperationCallThrowable() .isInstanceOf(EndpointDiscoveryFailedException.class) .hasCauseInstanceOf(EndpointDiscoveryTestException.class); } @Test public void syncRequiredOperation_InvalidEndpointEndpointDiscoveryResponse_CausesSdkException() { stubResponse(mockSyncClient, 500, "invalid", 15); assertThatThrownBy(() -> client.testDiscoveryRequired(r -> { })) .isInstanceOf(SdkClientException.class); } @Test public void asyncRequiredOperation_InvalidEndpointEndpointDiscoveryResponse_CausesSdkException() { stubResponse(mockAsyncClient, 500, "invalid", 15); assertAsyncRequiredOperationCallThrowable() .isInstanceOf(SdkClientException.class); } private AbstractThrowableAssert<?, ? extends Throwable> assertAsyncRequiredOperationCallThrowable() { try { asyncClient.testDiscoveryRequired(r -> { }).get(); throw new AssertionError(); } catch (InterruptedException e) { return assertThat(e); } catch (ExecutionException e) { return assertThat(e.getCause()); } } private static class TestExecutableHttpRequest implements ExecutableHttpRequest { private final HttpExecuteResponse response; TestExecutableHttpRequest(HttpExecuteResponse response) { this.response = response; } @Override public void abort() { } @Override public HttpExecuteResponse call() throws IOException { return response; } } private void stubResponse(SdkAsyncHttpClient mockClient, int statusCode, String address, long cachePeriod) { String responseBody = "{" + " \"Endpoints\": [{" + " \"Address\": \"" + address + "\"," + " \"CachePeriodInMinutes\": " + cachePeriod + " }]" + "}"; stubResponse(mockClient, statusCode, responseBody); } private void stubResponse(SdkAsyncHttpClient mockClient, int statusCode, String responseBody) { when(mockClient.execute(any())).thenAnswer( stubAsyncResponse(SdkHttpResponse.builder().statusCode(statusCode).build(), ByteBuffer.wrap(responseBody.getBytes(StandardCharsets.UTF_8)))); } private void stubResponse(SdkHttpClient mockClient, int statusCode, String address, long cachePeriod) { String responseBody = "{" + " \"Endpoints\": [{" + " \"Address\": \"" + address + "\"," + " \"CachePeriodInMinutes\": " + cachePeriod + " }]" + "}"; stubResponse(mockClient, statusCode, responseBody); } private void stubResponse(SdkHttpClient mockClient, int statusCode, String responseBody) { when(mockClient.prepareRequest(any())).thenReturn(new TestExecutableHttpRequest( HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(statusCode) .build()) .responseBody(AbortableInputStream.create( new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)))) .build() )); } private Answer<CompletableFuture<Void>> stubAsyncResponse(SdkHttpResponse response, ByteBuffer content) { return (i) -> { AsyncExecuteRequest request = i.getArgument(0, AsyncExecuteRequest.class); request.responseHandler().onHeaders(response); request.responseHandler().onStream(Flowable.just(content)); CompletableFuture<Void> cf = new CompletableFuture<>(); cf.complete(null); return cf; }; } }
2,855
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/InvalidRegionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; public class InvalidRegionTest { @Test public void invalidClientRegionGivesHelpfulMessage() { assertThatThrownBy(() -> ProtocolRestJsonClient.builder() .region(Region.of("US_EAST_1")) .credentialsProvider(AnonymousCredentialsProvider.create()) .build()) .isInstanceOf(SdkClientException.class) .hasMessageContaining("US_EAST_1") .hasMessageContaining("region"); } }
2,856
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/NoneAuthTypeRequestTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.reactivex.Flowable; import java.io.IOException; import java.util.concurrent.CompletableFuture; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.awscore.client.builder.AwsAsyncClientBuilder; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.ResolveIdentityRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient; /** * Verify that the "authtype" C2J trait for request type is honored for each requests. */ public class NoneAuthTypeRequestTest { private AwsCredentialsProvider credentialsProvider; private SdkHttpClient httpClient; private SdkAsyncHttpClient httpAsyncClient; private ProtocolRestJsonClient jsonClient; private ProtocolRestJsonAsyncClient jsonAsyncClient; private ProtocolRestXmlClient xmlClient; private ProtocolRestXmlAsyncClient xmlAsyncClient; @Before public void setup() throws IOException { credentialsProvider = spy(AwsCredentialsProvider.class); when(credentialsProvider.identityType()).thenReturn(AwsCredentialsIdentity.class); when(credentialsProvider.resolveIdentity(any(ResolveIdentityRequest.class))).thenAnswer( invocationOnMock -> CompletableFuture.completedFuture(AwsBasicCredentials.create("123", "12344"))); httpClient = mock(SdkHttpClient.class); httpAsyncClient = mock(SdkAsyncHttpClient.class); jsonClient = initializeSync(ProtocolRestJsonClient.builder()).build(); jsonAsyncClient = initializeAsync(ProtocolRestJsonAsyncClient.builder()).build(); xmlClient = initializeSync(ProtocolRestXmlClient.builder()).build(); xmlAsyncClient = initializeAsync(ProtocolRestXmlAsyncClient.builder()).build(); SdkHttpFullResponse successfulHttpResponse = SdkHttpResponse.builder() .statusCode(200) .putHeader("Content-Length", "0") .build(); ExecutableHttpRequest request = mock(ExecutableHttpRequest.class); when(request.call()).thenReturn(HttpExecuteResponse.builder() .response(successfulHttpResponse) .build()); when(httpClient.prepareRequest(any())).thenReturn(request); when(httpAsyncClient.execute(any())).thenAnswer(invocation -> { AsyncExecuteRequest asyncExecuteRequest = invocation.getArgument(0, AsyncExecuteRequest.class); asyncExecuteRequest.responseHandler().onHeaders(successfulHttpResponse); asyncExecuteRequest.responseHandler().onStream(Flowable.empty()); return CompletableFuture.completedFuture(null); }); } @Test public void sync_json_authorization_is_absent_for_noneAuthType() { jsonClient.operationWithNoneAuthType(o -> o.booleanMember(true)); assertThat(getSyncRequest().firstMatchingHeader("Authorization")).isNotPresent(); verify(credentialsProvider, times(0)).resolveIdentity(any(ResolveIdentityRequest.class)); } @Test public void sync_json_authorization_is_present_for_defaultAuth() { jsonClient.jsonValuesOperation(); assertThat(getSyncRequest().firstMatchingHeader("Authorization")).isPresent(); verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class)); } @Test public void async_json_authorization_is_absent_for_noneAuthType() { jsonAsyncClient.operationWithNoneAuthType(o -> o.booleanMember(true)); assertThat(getAsyncRequest().firstMatchingHeader("Authorization")).isNotPresent(); verify(credentialsProvider, times(0)).resolveIdentity(any(ResolveIdentityRequest.class)); } @Test public void async_json_authorization_is_present_for_defaultAuth() { jsonAsyncClient.jsonValuesOperation(); assertThat(getAsyncRequest().firstMatchingHeader("Authorization")).isPresent(); verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class)); } @Test public void sync_xml_authorization_is_absent_for_noneAuthType() { xmlClient.operationWithNoneAuthType(o -> o.booleanMember(true)); assertThat(getSyncRequest().firstMatchingHeader("Authorization")).isNotPresent(); verify(credentialsProvider, times(0)).resolveIdentity(any(ResolveIdentityRequest.class)); } @Test public void sync_xml_authorization_is_present_for_defaultAuth() { xmlClient.jsonValuesOperation(json -> json.jsonValueMember("one")); assertThat(getSyncRequest().firstMatchingHeader("Authorization")).isPresent(); verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class)); } @Test public void async_xml_authorization_is_absent_for_noneAuthType() { xmlAsyncClient.operationWithNoneAuthType(o -> o.booleanMember(true)); assertThat(getAsyncRequest().firstMatchingHeader("Authorization")).isNotPresent(); verify(credentialsProvider, times(0)).resolveIdentity(any(ResolveIdentityRequest.class)); } @Test public void async_xml_authorization_is_present_for_defaultAuth() { xmlAsyncClient.jsonValuesOperation(json -> json.jsonValueMember("one")); assertThat(getAsyncRequest().firstMatchingHeader("Authorization")).isPresent(); verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class)); } private SdkHttpRequest getSyncRequest() { ArgumentCaptor<HttpExecuteRequest> captor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(httpClient).prepareRequest(captor.capture()); return captor.getValue().httpRequest(); } private SdkHttpRequest getAsyncRequest() { ArgumentCaptor<AsyncExecuteRequest> captor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); verify(httpAsyncClient).execute(captor.capture()); return captor.getValue().request(); } private <T extends AwsSyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeSync(T syncClientBuilder) { return initialize(syncClientBuilder.httpClient(httpClient).credentialsProvider(credentialsProvider)); } private <T extends AwsAsyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeAsync(T asyncClientBuilder) { return initialize(asyncClientBuilder.httpClient(httpAsyncClient).credentialsProvider(credentialsProvider)); } private <T extends AwsClientBuilder<T, ?>> T initialize(T clientBuilder) { return clientBuilder.region(Region.US_WEST_2); } }
2,857
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/OverrideConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; 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.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.regions.Region; import software.amazon.awssdk.services.endpointproviders.EndpointInterceptorTests; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClient; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClientBuilder; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClientBuilder; public class OverrideConfigurationTest { private CapturingInterceptor interceptor; @BeforeEach public void setup() { this.interceptor = new CapturingInterceptor(); } @Test public void sync_clientOverrideConfiguration_isAddedToRequest() { RestJsonEndpointProvidersClient syncClient = syncClientBuilder() .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor) .putHeader("K1", "V1")) .build(); assertThatThrownBy(() -> syncClient.allTypes(r -> {})) .hasMessageContaining("stop"); assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1")); } @Test public void sync_requestOverrideConfiguration_isAddedToRequest() { RestJsonEndpointProvidersClient syncClient = syncClientBuilder().build(); assertThatThrownBy(() -> syncClient.allTypes(r -> r.overrideConfiguration(c -> c.putHeader("K1", "V1") .putRawQueryParameter("K2", "V2")))) .hasMessageContaining("stop"); assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1")); assertThat(interceptor.context.httpRequest().rawQueryParameters()).containsEntry("K2", singletonList("V2")); } @Test public void async_clientOverrideConfiguration_isAddedToRequest() { RestJsonEndpointProvidersAsyncClient syncClient = asyncClientBuilder() .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor) .putHeader("K1", "V1")) .build(); assertThatThrownBy(() -> syncClient.allTypes(r -> {}).join()) .hasMessageContaining("stop"); assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1")); } @Test public void async_requestOverrideConfiguration_isAddedToRequest() { RestJsonEndpointProvidersAsyncClient syncClient = asyncClientBuilder().build(); assertThatThrownBy(() -> syncClient.allTypes(r -> r.overrideConfiguration(c -> c.putHeader("K1", "V1") .putRawQueryParameter("K2", "V2"))) .join()) .hasMessageContaining("stop"); assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1")); assertThat(interceptor.context.httpRequest().rawQueryParameters()).containsEntry("K2", singletonList("V2")); } private RestJsonEndpointProvidersClientBuilder syncClientBuilder() { return RestJsonEndpointProvidersClient.builder() .region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)); } private RestJsonEndpointProvidersAsyncClientBuilder asyncClientBuilder() { return RestJsonEndpointProvidersAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)); } public static class CapturingInterceptor implements ExecutionInterceptor { private Context.BeforeTransmission context; private ExecutionAttributes executionAttributes; @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { this.context = context; this.executionAttributes = executionAttributes; throw new RuntimeException("stop"); } public ExecutionAttributes executionAttributes() { return executionAttributes; } public class CaptureCompletedException extends RuntimeException { CaptureCompletedException(String message) { super(message); } } } }
2,858
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/SraIdentityResolutionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.concurrent.CompletableFuture; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.ResolveIdentityRequest; import software.amazon.awssdk.services.protocolquery.ProtocolQueryClient; @RunWith(MockitoJUnitRunner.class) public class SraIdentityResolutionTest { @Mock private AwsCredentialsProvider credsProvider; @Test public void testIdentityPropertyBasedResolutionIsUsedAndNotAnotherIdentityResolution() { SdkHttpClient mockClient = mock(SdkHttpClient.class); when(mockClient.prepareRequest(any())).thenThrow(new RuntimeException("boom")); when(credsProvider.identityType()).thenReturn(AwsCredentialsIdentity.class); when(credsProvider.resolveIdentity(any(ResolveIdentityRequest.class))) .thenReturn(CompletableFuture.completedFuture(AwsBasicCredentials.create("akid1", "skid2"))); ProtocolQueryClient syncClient = ProtocolQueryClient .builder() .httpClient(mockClient) .credentialsProvider(credsProvider) // Below is necessary to create the test case where, addCredentialsToExecutionAttributes was getting called before .overrideConfiguration(ClientOverrideConfiguration.builder().build()) .build(); assertThatThrownBy(() -> syncClient.allTypes(r -> {})).hasMessageContaining("boom"); verify(credsProvider, times(2)).identityType(); // This asserts that the identity used is the one from resolveIdentity() called by SRA AuthSchemeInterceptor and not from // from another call like from AwsCredentialsAuthorizationStrategy.addCredentialsToExecutionAttributes, asserted by // combination of times(1) and verifyNoMoreInteractions. verify(credsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class)); verifyNoMoreInteractions(credsProvider); } }
2,859
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/OverrideConfigurationPluginsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; 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.SdkPlugin; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClient; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClientBuilder; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClientBuilder; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersServiceClientConfiguration; import software.amazon.awssdk.utils.Validate; public class OverrideConfigurationPluginsTest { private CapturingInterceptor interceptor; @BeforeEach void setup() { this.interceptor = new CapturingInterceptor(); } @Test void sync_pluginsClientOverrideConfiguration_isAddedToRequest() { RestJsonEndpointProvidersClient syncClient = syncClientBuilder() .addPlugin(config -> config.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor) .putHeader("K1", "V1"))) .build(); assertThatThrownBy(() -> syncClient.allTypes(r -> { })) .hasMessageContaining("boom!"); assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1")); } @Test void sync_pluginsRequestOverrideConfiguration_isAddedToRequest() { RestJsonEndpointProvidersClient syncClient = syncClientBuilder().build(); SdkPlugin plugin = config -> config.overrideConfiguration(c -> c.putHeader("K1", "V1")); assertThatThrownBy(() -> syncClient.allTypes(r -> r.overrideConfiguration(c -> c.addPlugin(plugin)))) .hasMessageContaining("boom!"); assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1")); } @Test void async_pluginsClientOverrideConfiguration_isAddedToRequest() { RestJsonEndpointProvidersAsyncClient syncClient = asyncClientBuilder() .addPlugin(config -> config.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor) .putHeader("K1", "V1"))) .build(); assertThatThrownBy(() -> syncClient.allTypes(r -> { }).join()) .hasMessageContaining("boom!"); assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1")); } @Test void async_pluginsRequestOverrideConfiguration_isAddedToRequest() { RestJsonEndpointProvidersAsyncClient syncClient = asyncClientBuilder().build(); SdkPlugin plugin = config -> config.overrideConfiguration(c -> c.putHeader("K1", "V1")); assertThatThrownBy(() -> syncClient.allTypes(r -> r.overrideConfiguration(c -> c.addPlugin(plugin))) .join()) .hasMessageContaining("boom!"); assertThat(interceptor.context.httpRequest().headers()).containsEntry("K1", singletonList("V1")); } private RestJsonEndpointProvidersClientBuilder syncClientBuilder() { return RestJsonEndpointProvidersClient .builder() .addPlugin(c -> { RestJsonEndpointProvidersServiceClientConfiguration.Builder config = Validate.isInstanceOf(RestJsonEndpointProvidersServiceClientConfiguration.Builder.class, c, "\uD83E\uDD14"); config.region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))) .overrideConfiguration(oc -> oc.addExecutionInterceptor(interceptor)); }); } private RestJsonEndpointProvidersAsyncClientBuilder asyncClientBuilder() { return RestJsonEndpointProvidersAsyncClient .builder() .addPlugin(c -> { RestJsonEndpointProvidersServiceClientConfiguration.Builder config = Validate.isInstanceOf(RestJsonEndpointProvidersServiceClientConfiguration.Builder.class, c, "\uD83E\uDD14"); config.region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))) .overrideConfiguration(oc -> oc.addExecutionInterceptor(interceptor)); }); } public static class CapturingInterceptor implements ExecutionInterceptor { private Context.BeforeTransmission context; private ExecutionAttributes executionAttributes; @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { this.context = context; this.executionAttributes = executionAttributes; throw new RuntimeException("boom!"); } public ExecutionAttributes executionAttributes() { return executionAttributes; } public class CaptureCompletedException extends RuntimeException { CaptureCompletedException(String message) { super(message); } } } }
2,860
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/RequestCompressionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.ByteArrayInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.internal.compression.Compressor; import software.amazon.awssdk.core.internal.compression.GzipCompressor; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.model.PutOperationWithRequestCompressionRequest; import software.amazon.awssdk.services.protocolrestjson.model.PutOperationWithStreamingRequestCompressionRequest; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; public class RequestCompressionTest { private static final String UNCOMPRESSED_BODY = "RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest"; private String compressedBody; private int compressedLen; private MockSyncHttpClient mockHttpClient; private ProtocolRestJsonClient syncClient; private Compressor compressor; private RequestBody requestBody; @BeforeEach public void setUp() { mockHttpClient = new MockSyncHttpClient(); syncClient = ProtocolRestJsonClient.builder() .credentialsProvider(AnonymousCredentialsProvider.create()) .region(Region.US_EAST_1) .httpClient(mockHttpClient) .build(); compressor = new GzipCompressor(); byte[] compressedBodyBytes = compressor.compress(UNCOMPRESSED_BODY.getBytes()); compressedLen = compressedBodyBytes.length; compressedBody = new String(compressedBodyBytes); TestContentProvider provider = new TestContentProvider(UNCOMPRESSED_BODY.getBytes()); requestBody = RequestBody.fromContentProvider(provider, "binary/octet-stream"); } @AfterEach public void reset() { mockHttpClient.reset(); } @Test public void syncNonStreamingOperation_compressionEnabledThresholdOverridden_compressesCorrectly() { mockHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); PutOperationWithRequestCompressionRequest request = PutOperationWithRequestCompressionRequest.builder() .body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY)) .overrideConfiguration(o -> o.compressionConfiguration( c -> c.minimumCompressionThresholdInBytes(1))) .build(); syncClient.putOperationWithRequestCompression(request); SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockHttpClient.getLastRequest(); InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream(); String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray()); int loggedSize = Integer.valueOf(loggedRequest.firstMatchingHeader("Content-Length").get()); assertThat(loggedBody).isEqualTo(compressedBody); assertThat(loggedSize).isEqualTo(compressedLen); assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip"); } @Test public void syncNonStreamingOperation_payloadSizeLessThanCompressionThreshold_doesNotCompress() { mockHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); PutOperationWithRequestCompressionRequest request = PutOperationWithRequestCompressionRequest.builder() .body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY)) .build(); syncClient.putOperationWithRequestCompression(request); SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockHttpClient.getLastRequest(); InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream(); String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray()); assertThat(loggedBody).isEqualTo(UNCOMPRESSED_BODY); assertThat(loggedRequest.firstMatchingHeader("Content-encoding")).isEmpty(); } @Test public void syncStreamingOperation_compressionEnabled_compressesCorrectly() { mockHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); PutOperationWithStreamingRequestCompressionRequest request = PutOperationWithStreamingRequestCompressionRequest.builder().build(); syncClient.putOperationWithStreamingRequestCompression(request, requestBody, ResponseTransformer.toBytes()); SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockHttpClient.getLastRequest(); InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream(); String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray()); assertThat(loggedBody).isEqualTo(compressedBody); assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip"); assertThat(loggedRequest.matchingHeaders("Content-Length")).isEmpty(); assertThat(loggedRequest.firstMatchingHeader("Transfer-Encoding").get()).isEqualTo("chunked"); } @Test public void syncNonStreamingOperation_compressionEnabledThresholdOverriddenWithRetry_compressesCorrectly() { mockHttpClient.stubNextResponse(mockErrorResponse(), Duration.ofMillis(500)); mockHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); PutOperationWithRequestCompressionRequest request = PutOperationWithRequestCompressionRequest.builder() .body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY)) .overrideConfiguration(o -> o.compressionConfiguration( c -> c.minimumCompressionThresholdInBytes(1))) .build(); syncClient.putOperationWithRequestCompression(request); SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockHttpClient.getLastRequest(); InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream(); String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray()); int loggedSize = Integer.valueOf(loggedRequest.firstMatchingHeader("Content-Length").get()); assertThat(loggedBody).isEqualTo(compressedBody); assertThat(loggedSize).isEqualTo(compressedLen); assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip"); } @Test public void syncStreamingOperation_compressionEnabledWithRetry_compressesCorrectly() { mockHttpClient.stubNextResponse(mockErrorResponse(), Duration.ofMillis(500)); mockHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); PutOperationWithStreamingRequestCompressionRequest request = PutOperationWithStreamingRequestCompressionRequest.builder().build(); syncClient.putOperationWithStreamingRequestCompression(request, requestBody, ResponseTransformer.toBytes()); SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockHttpClient.getLastRequest(); InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream(); String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray()); assertThat(loggedBody).isEqualTo(compressedBody); assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip"); assertThat(loggedRequest.matchingHeaders("Content-Length")).isEmpty(); assertThat(loggedRequest.firstMatchingHeader("Transfer-Encoding").get()).isEqualTo("chunked"); } private HttpExecuteResponse mockResponse() { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200).build()) .build(); } private HttpExecuteResponse mockErrorResponse() { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(500).build()) .build(); } private static final class TestContentProvider implements ContentStreamProvider { private final byte[] content; private final List<CloseTrackingInputStream> createdStreams = new ArrayList<>(); private CloseTrackingInputStream currentStream; private TestContentProvider(byte[] content) { this.content = content; } @Override public InputStream newStream() { if (currentStream != null) { invokeSafely(currentStream::close); } currentStream = new CloseTrackingInputStream(new ByteArrayInputStream(content)); createdStreams.add(currentStream); return currentStream; } List<CloseTrackingInputStream> getCreatedStreams() { return createdStreams; } } private static class CloseTrackingInputStream extends FilterInputStream { private boolean isClosed = false; CloseTrackingInputStream(InputStream in) { super(in); } @Override public void close() throws IOException { super.close(); isClosed = true; } boolean isClosed() { return isClosed; } } }
2,861
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/UnionTypeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; import java.time.Instant; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructList; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructMap; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesUnionStructure; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesUnionStructure.Type; import software.amazon.awssdk.services.protocolrestjson.model.BaseType; import software.amazon.awssdk.services.protocolrestjson.model.EnumType; import software.amazon.awssdk.services.protocolrestjson.model.RecursiveStructType; import software.amazon.awssdk.services.protocolrestjson.model.StructWithNestedBlobType; import software.amazon.awssdk.services.protocolrestjson.model.StructWithTimestamp; import software.amazon.awssdk.services.protocolrestjson.model.SubTypeOne; public class UnionTypeTest { public static List<TestCase<?>> testCases() { List<TestCase<?>> tests = new ArrayList<>(); tests.add(new TestCase<>(Type.STRING_MEMBER, "foo", AllTypesUnionStructure::fromStringMember, AllTypesUnionStructure::stringMember, AllTypesUnionStructure.Builder::stringMember)); tests.add(new TestCase<>(Type.INTEGER_MEMBER, 5, AllTypesUnionStructure::fromIntegerMember, AllTypesUnionStructure::integerMember, AllTypesUnionStructure.Builder::integerMember)); tests.add(new TestCase<>(Type.BOOLEAN_MEMBER, true, AllTypesUnionStructure::fromBooleanMember, AllTypesUnionStructure::booleanMember, AllTypesUnionStructure.Builder::booleanMember)); tests.add(new TestCase<>(Type.FLOAT_MEMBER, 0.1f, AllTypesUnionStructure::fromFloatMember, AllTypesUnionStructure::floatMember, AllTypesUnionStructure.Builder::floatMember)); tests.add(new TestCase<>(Type.DOUBLE_MEMBER, 0.1d, AllTypesUnionStructure::fromDoubleMember, AllTypesUnionStructure::doubleMember, AllTypesUnionStructure.Builder::doubleMember)); tests.add(new TestCase<>(Type.LONG_MEMBER, 5L, AllTypesUnionStructure::fromLongMember, AllTypesUnionStructure::longMember, AllTypesUnionStructure.Builder::longMember)); tests.add(new TestCase<>(Type.SHORT_MEMBER, (short) 5, AllTypesUnionStructure::fromShortMember, AllTypesUnionStructure::shortMember, AllTypesUnionStructure.Builder::shortMember)); tests.add(new TestCase<>(Type.ENUM_MEMBER, EnumType.ENUM_VALUE1, AllTypesUnionStructure::fromEnumMember, AllTypesUnionStructure::enumMember, AllTypesUnionStructure.Builder::enumMember)); tests.add(new TestCase<>(Type.SIMPLE_LIST, emptyList(), AllTypesUnionStructure::fromSimpleList, AllTypesUnionStructure::simpleList, AllTypesUnionStructure.Builder::simpleList)); tests.add(new TestCase<>(Type.LIST_OF_ENUMS, emptyList(), AllTypesUnionStructure::fromListOfEnums, AllTypesUnionStructure::listOfEnums, AllTypesUnionStructure.Builder::listOfEnums)); tests.add(new TestCase<>(Type.LIST_OF_MAPS, emptyList(), AllTypesUnionStructure::fromListOfMaps, AllTypesUnionStructure::listOfMaps, AllTypesUnionStructure.Builder::listOfMaps)); tests.add(new TestCase<>(Type.LIST_OF_LIST_OF_MAPS_OF_STRING_TO_STRUCT, emptyList(), AllTypesUnionStructure::fromListOfListOfMapsOfStringToStruct, AllTypesUnionStructure::listOfListOfMapsOfStringToStruct, AllTypesUnionStructure.Builder::listOfListOfMapsOfStringToStruct)); tests.add(new TestCase<>(Type.LIST_OF_MAPS_OF_STRING_TO_STRUCT, emptyList(), AllTypesUnionStructure::fromListOfMapsOfStringToStruct, AllTypesUnionStructure::listOfMapsOfStringToStruct, AllTypesUnionStructure.Builder::listOfMapsOfStringToStruct)); tests.add(new TestCase<>(Type.LIST_OF_STRUCTS, emptyList(), AllTypesUnionStructure::fromListOfStructs, AllTypesUnionStructure::listOfStructs, AllTypesUnionStructure.Builder::listOfStructs)); tests.add(new TestCase<>(Type.MAP_OF_STRING_TO_INTEGER_LIST, emptyMap(), AllTypesUnionStructure::fromMapOfStringToIntegerList, AllTypesUnionStructure::mapOfStringToIntegerList, AllTypesUnionStructure.Builder::mapOfStringToIntegerList)); tests.add(new TestCase<>(Type.MAP_OF_STRING_TO_STRING, emptyMap(), AllTypesUnionStructure::fromMapOfStringToString, AllTypesUnionStructure::mapOfStringToString, AllTypesUnionStructure.Builder::mapOfStringToString)); tests.add(new TestCase<>(Type.MAP_OF_STRING_TO_STRUCT, emptyMap(), AllTypesUnionStructure::fromMapOfStringToStruct, AllTypesUnionStructure::mapOfStringToStruct, AllTypesUnionStructure.Builder::mapOfStringToStruct)); tests.add(new TestCase<>(Type.MAP_OF_ENUM_TO_ENUM, emptyMap(), AllTypesUnionStructure::fromMapOfEnumToEnum, AllTypesUnionStructure::mapOfEnumToEnum, AllTypesUnionStructure.Builder::mapOfEnumToEnum)); tests.add(new TestCase<>(Type.TIMESTAMP_MEMBER, Instant.now(), AllTypesUnionStructure::fromTimestampMember, AllTypesUnionStructure::timestampMember, AllTypesUnionStructure.Builder::timestampMember)); tests.add(new TestCase<>(Type.STRUCT_WITH_NESTED_TIMESTAMP_MEMBER, StructWithTimestamp.builder().build(), AllTypesUnionStructure::fromStructWithNestedTimestampMember, AllTypesUnionStructure::structWithNestedTimestampMember, AllTypesUnionStructure.Builder::structWithNestedTimestampMember)); tests.add(new TestCase<>(Type.BLOB_ARG, SdkBytes.fromUtf8String(""), AllTypesUnionStructure::fromBlobArg, AllTypesUnionStructure::blobArg, AllTypesUnionStructure.Builder::blobArg)); tests.add(new TestCase<>(Type.STRUCT_WITH_NESTED_BLOB, StructWithNestedBlobType.builder().build(), AllTypesUnionStructure::fromStructWithNestedBlob, AllTypesUnionStructure::structWithNestedBlob, AllTypesUnionStructure.Builder::structWithNestedBlob)); tests.add(new TestCase<>(Type.BLOB_MAP, emptyMap(), AllTypesUnionStructure::fromBlobMap, AllTypesUnionStructure::blobMap, AllTypesUnionStructure.Builder::blobMap)); tests.add(new TestCase<>(Type.LIST_OF_BLOBS, emptyList(), AllTypesUnionStructure::fromListOfBlobs, AllTypesUnionStructure::listOfBlobs, AllTypesUnionStructure.Builder::listOfBlobs)); tests.add(new TestCase<>(Type.RECURSIVE_STRUCT, RecursiveStructType.builder().build(), AllTypesUnionStructure::fromRecursiveStruct, AllTypesUnionStructure::recursiveStruct, AllTypesUnionStructure.Builder::recursiveStruct)); tests.add(new TestCase<>(Type.POLYMORPHIC_TYPE_WITH_SUB_TYPES, BaseType.builder().build(), AllTypesUnionStructure::fromPolymorphicTypeWithSubTypes, AllTypesUnionStructure::polymorphicTypeWithSubTypes, AllTypesUnionStructure.Builder::polymorphicTypeWithSubTypes)); tests.add(new TestCase<>(Type.POLYMORPHIC_TYPE_WITHOUT_SUB_TYPES, SubTypeOne.builder().build(), AllTypesUnionStructure::fromPolymorphicTypeWithoutSubTypes, AllTypesUnionStructure::polymorphicTypeWithoutSubTypes, AllTypesUnionStructure.Builder::polymorphicTypeWithoutSubTypes)); tests.add(new TestCase<>(Type.SET_PREFIXED_MEMBER, "foo", AllTypesUnionStructure::fromSetPrefixedMember, AllTypesUnionStructure::setPrefixedMember, AllTypesUnionStructure.Builder::setPrefixedMember)); tests.add(new TestCase<>(Type.UNION_MEMBER, AllTypesUnionStructure.builder().build(), AllTypesUnionStructure::fromUnionMember, AllTypesUnionStructure::unionMember, AllTypesUnionStructure.Builder::unionMember)); return tests; } @Test public void allTypesTested() { Set<Type> types = EnumSet.allOf(Type.class); types.remove(Type.UNKNOWN_TO_SDK_VERSION); Set<Type> testedTypes = testCases().stream().map(t -> t.type).collect(Collectors.toSet()); assertThat(testedTypes).isEqualTo(types); // If this fails, it means you need to add a test case above } @Test public void noMembersIsUnknownType() { assertThat(AllTypesUnionStructure.builder().build().type()).isEqualTo(Type.UNKNOWN_TO_SDK_VERSION); } @ParameterizedTest @MethodSource("testCases") public <T> void twoMembersIsNull(TestCase<T> testCase) { AllTypesUnionStructure.Builder builder = AllTypesUnionStructure.builder(); testCase.setter.apply(builder, testCase.value); if (testCase.type == Type.STRING_MEMBER) { builder.integerMember(5); } else { builder.stringMember("foo"); } assertThat(builder.build().type()).isNull(); } @ParameterizedTest @MethodSource("testCases") public <T> void twoMinusOneMemberIsKnownType(TestCase<T> testCase) { AllTypesUnionStructure.Builder builder = AllTypesUnionStructure.builder(); if (testCase.type == Type.STRING_MEMBER) { builder.integerMember(5); } else { builder.stringMember("foo"); } testCase.setter.apply(builder, testCase.value); if (testCase.type == Type.STRING_MEMBER) { builder.integerMember(null); } else { builder.stringMember(null); } assertThat(builder.build().type()).isEqualTo(testCase.type); } @ParameterizedTest @MethodSource("testCases") public <T> void staticConstructorsWork(TestCase<T> testCase) { AllTypesUnionStructure structure = testCase.constructor.apply(testCase.value); T valuePassedThrough = testCase.getter.apply(structure); assertThat(valuePassedThrough).isEqualTo(testCase.value); assertThat(structure.type()).isEqualTo(testCase.type); } @ParameterizedTest @MethodSource("testCases") public <T> void typeIsPreservedThroughToBuilder(TestCase<T> testCase) { AllTypesUnionStructure structure = testCase.constructor.apply(testCase.value); assertThat(structure.toBuilder().build().type()).isEqualTo(testCase.type); } @Test public void autoConstructListsArentCountedForType() { assertThat(AllTypesUnionStructure.builder() .stringMember("foo") .listOfMaps(DefaultSdkAutoConstructList.getInstance()) .build() .type()) .isEqualTo(Type.STRING_MEMBER); assertThat(AllTypesUnionStructure.builder() .listOfMaps(DefaultSdkAutoConstructList.getInstance()) .stringMember("foo") .build() .type()) .isEqualTo(Type.STRING_MEMBER); } @Test public void autoConstructMapsArentCountedForType() { assertThat(AllTypesUnionStructure.builder() .stringMember("foo") .mapOfEnumToEnum(DefaultSdkAutoConstructMap.getInstance()) .build() .type()) .isEqualTo(Type.STRING_MEMBER); assertThat(AllTypesUnionStructure.builder() .mapOfEnumToEnum(DefaultSdkAutoConstructMap.getInstance()) .stringMember("foo") .build() .type()) .isEqualTo(Type.STRING_MEMBER); } private static class TestCase<T> { private final Type type; private final T value; private final Function<T, AllTypesUnionStructure> constructor; private final Function<AllTypesUnionStructure, T> getter; private final BiFunction<AllTypesUnionStructure.Builder, T, AllTypesUnionStructure.Builder> setter; public TestCase(Type type, T value, Function<T, AllTypesUnionStructure> constructor, Function<AllTypesUnionStructure, T> getter, BiFunction<AllTypesUnionStructure.Builder, T, AllTypesUnionStructure.Builder> setter) { this.type = type; this.value = value; this.constructor = constructor; this.getter = getter; this.setter = setter; } @Override public String toString() { return type + " test"; } } }
2,862
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/SraIdentityResolutionUsingRequestPluginsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.concurrent.CompletableFuture; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.SdkServiceClientConfiguration; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.ResolveIdentityRequest; import software.amazon.awssdk.services.protocolquery.ProtocolQueryClient; import software.amazon.awssdk.services.protocolquery.ProtocolQueryServiceClientConfiguration; import software.amazon.awssdk.services.protocolquery.model.AllTypesRequest; import software.amazon.awssdk.utils.Validate; @RunWith(MockitoJUnitRunner.class) public class SraIdentityResolutionUsingRequestPluginsTest { @Mock private AwsCredentialsProvider credentialsProvider; @Test public void testIdentityBasedPluginsResolutionIsUsedAndNotAnotherIdentityResolution() { SdkHttpClient mockClient = mock(SdkHttpClient.class); when(mockClient.prepareRequest(any())).thenThrow(new RuntimeException("boom")); when(credentialsProvider.identityType()).thenReturn(AwsCredentialsIdentity.class); when(credentialsProvider.resolveIdentity(any(ResolveIdentityRequest.class))) .thenReturn(CompletableFuture.completedFuture(AwsBasicCredentials.create("akid1", "skid2"))); ProtocolQueryClient syncClient = ProtocolQueryClient .builder() .httpClient(mockClient) .build(); AllTypesRequest request = AllTypesRequest.builder() .overrideConfiguration(c -> c.addPlugin(new TestPlugin(credentialsProvider))) .build(); assertThatThrownBy(() -> syncClient.allTypes(request)) .hasMessageContaining("boom"); verify(credentialsProvider, times(2)).identityType(); // This asserts that the identity used is the one from resolveIdentity() called by SRA AuthSchemeInterceptor and not // from another call like from AwsCredentialsAuthorizationStrategy.addCredentialsToExecutionAttributes, asserted by // combination of times(1) and verifyNoMoreInteractions. verify(credentialsProvider, times(1)).resolveIdentity(any(ResolveIdentityRequest.class)); verifyNoMoreInteractions(credentialsProvider); } static class TestPlugin implements SdkPlugin { private final AwsCredentialsProvider credentialsProvider; TestPlugin(AwsCredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; } @Override public void configureClient(SdkServiceClientConfiguration.Builder config) { ProtocolQueryServiceClientConfiguration.Builder builder = Validate.isInstanceOf(ProtocolQueryServiceClientConfiguration.Builder.class, config, "Expecting an instance of " + ProtocolQueryServiceClientConfiguration.class); builder.credentialsProvider(credentialsProvider); } } }
2,863
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/EndpointVariantResolutionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder; public class EndpointVariantResolutionTest { @Test public void dualstackEndpointResolution() { EndpointCapturingInterceptor interceptor = new EndpointCapturingInterceptor(); try { clientBuilder(interceptor).dualstackEnabled(true).build().allTypes(); } catch (EndpointCapturingInterceptor.CaptureCompletedException e) { // Expected } assertThat(interceptor.endpoints()) .singleElement() .isEqualTo("https://customresponsemetadata.us-west-2.api.aws/2016-03-11/allTypes"); } @Test public void fipsEndpointResolution() { EndpointCapturingInterceptor interceptor = new EndpointCapturingInterceptor(); try { clientBuilder(interceptor).fipsEnabled(true).build().allTypes(); } catch (EndpointCapturingInterceptor.CaptureCompletedException e) { // Expected } assertThat(interceptor.endpoints()) .singleElement() .isEqualTo("https://customresponsemetadata-fips.us-west-2.amazonaws.com/2016-03-11/allTypes"); } @Test public void dualstackFipsEndpointResolution() { EndpointCapturingInterceptor interceptor = new EndpointCapturingInterceptor(); try { clientBuilder(interceptor).dualstackEnabled(true).fipsEnabled(true).build().allTypes(); } catch (EndpointCapturingInterceptor.CaptureCompletedException e) { // Expected } assertThat(interceptor.endpoints()) .singleElement() .isEqualTo("https://customresponsemetadata-fips.us-west-2.api.aws/2016-03-11/allTypes"); } private ProtocolRestJsonClientBuilder clientBuilder(EndpointCapturingInterceptor interceptor) { return ProtocolRestJsonClient.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)); } }
2,864
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/AsyncSignerOverrideTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationRequest; /** * Test to ensure that operations that use the {@link software.amazon.awssdk.auth.signer.AsyncAws4Signer} don't apply * the override when the signer is overridden by the customer. */ @RunWith(MockitoJUnitRunner.class) public class AsyncSignerOverrideTest { @Mock public Signer mockSigner; @Test public void test_signerOverriddenForStreamingInput_takesPrecedence() { ProtocolRestJsonAsyncClient asyncClient = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2) .overrideConfiguration(o -> o.putAdvancedOption(SIGNER, mockSigner)) .build(); try { asyncClient.streamingInputOperation(StreamingInputOperationRequest.builder().build(), AsyncRequestBody.fromString("test")).join(); } catch (Exception expected) { } verify(mockSigner).sign(any(SdkHttpFullRequest.class), any(ExecutionAttributes.class)); } // TODO(sra-identity-and-auth): Add test for SRA way of overriding signer to assert that overridden signer is used. // At that point, rename this class to SignerOverrideTest, not specific to AsyncSignerOverride (which was for operation // level codegen changes). }
2,865
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/HttpChecksumInHeaderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import io.reactivex.Flowable; import java.io.IOException; import java.util.Arrays; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.awscore.client.builder.AwsAsyncClientBuilder; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.model.ChecksumAlgorithm; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient; /** * Verify that the "HttpChecksum" C2J trait results in a valid checksum of the payload being included in the HTTP * request. */ public class HttpChecksumInHeaderTest { public static Set<String> VALID_CHECKSUM_HEADERS = Arrays.stream(Algorithm.values()).map(x -> "x-amz-checksum-" + x).collect(Collectors.toSet()); private SdkHttpClient httpClient; private SdkAsyncHttpClient httpAsyncClient; private ProtocolRestJsonClient jsonClient; private ProtocolRestJsonAsyncClient jsonAsyncClient; private ProtocolRestXmlClient xmlClient; private ProtocolRestXmlAsyncClient xmlAsyncClient; @Before public void setup() throws IOException { httpClient = Mockito.mock(SdkHttpClient.class); httpAsyncClient = Mockito.mock(SdkAsyncHttpClient.class); jsonClient = initializeSync(ProtocolRestJsonClient.builder()).build(); jsonAsyncClient = initializeAsync(ProtocolRestJsonAsyncClient.builder()).build(); xmlClient = initializeSync(ProtocolRestXmlClient.builder()).build(); xmlAsyncClient = initializeAsync(ProtocolRestXmlAsyncClient.builder()).build(); SdkHttpFullResponse successfulHttpResponse = SdkHttpResponse.builder() .statusCode(200) .putHeader("Content-Length", "0") .build(); ExecutableHttpRequest request = Mockito.mock(ExecutableHttpRequest.class); Mockito.when(request.call()).thenReturn(HttpExecuteResponse.builder() .response(successfulHttpResponse) .build()); Mockito.when(httpClient.prepareRequest(any())).thenReturn(request); Mockito.when(httpAsyncClient.execute(any())).thenAnswer(invocation -> { AsyncExecuteRequest asyncExecuteRequest = invocation.getArgument(0, AsyncExecuteRequest.class); asyncExecuteRequest.responseHandler().onHeaders(successfulHttpResponse); asyncExecuteRequest.responseHandler().onStream(Flowable.empty()); return CompletableFuture.completedFuture(null); }); } @Test public void sync_json_nonStreaming_unsignedPayload_with_Sha1_in_header() { // jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world")); jsonClient.operationWithChecksumNonStreaming( r -> r.stringMember("Hello world").checksumAlgorithm(ChecksumAlgorithm.SHA1).build()); assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent(); //Note that content will be of form "{"stringMember":"Hello world"}" assertThat(getSyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("M68rRwFal7o7B3KEMt3m0w39TaA="); } @Test public void aync_json_nonStreaming_unsignedPayload_with_Sha1_in_header() { // jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world")); jsonAsyncClient.operationWithChecksumNonStreaming( r -> r.checksumAlgorithm(ChecksumAlgorithm.SHA1).stringMember("Hello world").build()); assertThat(getAsyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent(); //Note that content will be of form "{"stringMember":"Hello world"}" assertThat(getAsyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("M68rRwFal7o7B3KEMt3m0w39TaA="); } @Test public void sync_xml_nonStreaming_unsignedPayload_with_Sha1_in_header() { // jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world")); xmlClient.operationWithChecksumNonStreaming(r -> r.stringMember("Hello world") .checksumAlgorithm(software.amazon.awssdk.services.protocolrestxml.model.ChecksumAlgorithm.SHA1).build()); assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent(); //Note that content will be of form "<?xml version="1.0" encoding="UTF-8"?><stringMember>Hello world</stringMember>" // TODO(sra-identity-and-auth): Uncomment once sra is set to true // assertThat(getSyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("FB/utBbwFLbIIt5ul3Ojuy5dKgU="); } @Test public void sync_xml_nonStreaming_unsignedEmptyPayload_with_Sha1_in_header() { // jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world")); xmlClient.operationWithChecksumNonStreaming(r -> r.checksumAlgorithm(software.amazon.awssdk.services.protocolrestxml.model.ChecksumAlgorithm.SHA1).build()); assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent(); //Note that content will be of form "<?xml version="1.0" encoding="UTF-8"?><stringMember>Hello world</stringMember>" // TODO(sra-identity-and-auth): Uncomment once sra is set to true // assertThat(getSyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("2jmj7l5rSw0yVb/vlWAYkK/YBwk="); } @Test public void aync_xml_nonStreaming_unsignedPayload_with_Sha1_in_header() { // jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world")); xmlAsyncClient.operationWithChecksumNonStreaming(r -> r.stringMember("Hello world") .checksumAlgorithm(software.amazon.awssdk.services.protocolrestxml.model.ChecksumAlgorithm.SHA1).build()).join(); assertThat(getAsyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent(); //Note that content will be of form <?xml version="1.0" encoding="UTF-8"?><stringMember>Hello world</stringMember>" assertThat(getAsyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("FB/utBbwFLbIIt5ul3Ojuy5dKgU="); } @Test public void aync_xml_nonStreaming_unsignedEmptyPayload_with_Sha1_in_header() { // jsonClient.flexibleCheckSumOperationWithShaChecksum(r -> r.stringMember("Hello world")); xmlAsyncClient.operationWithChecksumNonStreaming(r -> r.checksumAlgorithm(software.amazon.awssdk.services.protocolrestxml.model.ChecksumAlgorithm.SHA1).build()).join(); assertThat(getAsyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent(); //Note that content will be of form <?xml version="1.0" encoding="UTF-8"?><stringMember>Hello world</stringMember>" // TODO(sra-identity-and-auth): Uncomment once sra is set to true // assertThat(getAsyncRequest().firstMatchingHeader("x-amz-checksum-sha1")).hasValue("2jmj7l5rSw0yVb/vlWAYkK/YBwk="); } private SdkHttpRequest getSyncRequest() { ArgumentCaptor<HttpExecuteRequest> captor = ArgumentCaptor.forClass(HttpExecuteRequest.class); Mockito.verify(httpClient).prepareRequest(captor.capture()); return captor.getValue().httpRequest(); } private SdkHttpRequest getAsyncRequest() { ArgumentCaptor<AsyncExecuteRequest> captor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); Mockito.verify(httpAsyncClient).execute(captor.capture()); return captor.getValue().request(); } private <T extends AwsSyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeSync(T syncClientBuilder) { return initialize(syncClientBuilder.httpClient(httpClient)); } private <T extends AwsAsyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeAsync(T asyncClientBuilder) { return initialize(asyncClientBuilder.httpClient(httpAsyncClient)); } private <T extends AwsClientBuilder<T, ?>> T initialize(T clientBuilder) { return clientBuilder.credentialsProvider(AnonymousCredentialsProvider.create()) .region(Region.US_WEST_2); } }
2,866
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/SyncHttpChecksumInTrailerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.stubbing.Scenario; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.core.HttpChecksumConstant; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.model.ChecksumAlgorithm; public class SyncHttpChecksumInTrailerTest { private static final String CRLF = "\r\n"; private static final String SCENARIO = "scenario"; private static final String PATH = "/"; private static final String JSON_BODY = "{\"StringMember\":\"foo\"}"; @Rule public WireMockRule wireMock = new WireMockRule(0); private ProtocolRestJsonClient client; @Before public void setupClient() { client = ProtocolRestJsonClient.builder() .credentialsProvider(AnonymousCredentialsProvider.create()) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) // TODO(sra-identity-and-auth): we should remove these // overrides once we set up codegen to set chunk-encoding to true // for requests that are streaming and checksum-enabled .overrideConfiguration(c -> c.putExecutionAttribute( ENABLE_CHUNKED_ENCODING, true )) .build(); } @Test public void sync_streaming_NoSigner_appends_trailer_checksum() { stubResponseWithHeaders(); client.putOperationWithChecksum(r -> r.checksumAlgorithm(ChecksumAlgorithm.CRC32), RequestBody.fromString("Hello world") , ResponseTransformer.toBytes()); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo("52"))); verify(putRequestedFor(anyUrl()).withHeader(HttpChecksumConstant.HEADER_FOR_TRAILER_REFERENCE, equalTo("x-amz-checksum-crc32"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo("11"))); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked"))); //b is hex value of 11. verify(putRequestedFor(anyUrl()).withRequestBody( containing( "b" + CRLF + "Hello world" + CRLF + "0" + CRLF + "x-amz-checksum-crc32:i9aeUg==" + CRLF + CRLF))); } @Test public void sync_streaming_NoSigner_appends_trailer_checksum_withContentEncodingSetByUser() { stubResponseWithHeaders(); client.putOperationWithChecksum(r -> r.checksumAlgorithm(ChecksumAlgorithm.CRC32) .contentEncoding("deflate"), RequestBody.fromString("Hello world"), ResponseTransformer.toBytes()); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked"))); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("deflate"))); //b is hex value of 11. verify(putRequestedFor(anyUrl()).withRequestBody( containing( "b" + CRLF + "Hello world" + CRLF + "0" + CRLF + "x-amz-checksum-crc32:i9aeUg==" + CRLF + CRLF))); } @Test public void sync_streaming_specifiedLengthIsLess_NoSigner_appends_trailer_checksum() { stubResponseWithHeaders(); ContentStreamProvider provider = () -> new ByteArrayInputStream("Hello world".getBytes(StandardCharsets.UTF_8)); // length of 5 truncates to "Hello" RequestBody requestBody = RequestBody.fromContentProvider(provider, 5, "text/plain"); client.putOperationWithChecksum(r -> r.checksumAlgorithm(ChecksumAlgorithm.CRC32), requestBody, ResponseTransformer.toBytes()); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo("46"))); verify(putRequestedFor(anyUrl()).withHeader(HttpChecksumConstant.HEADER_FOR_TRAILER_REFERENCE, equalTo("x-amz-checksum-crc32"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo("5"))); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked"))); verify(putRequestedFor(anyUrl()).withRequestBody( containing( "5" + CRLF + "Hello" + CRLF + "0" + CRLF // 99GJgg== is the base64 encoded CRC32 of "Hello" + "x-amz-checksum-crc32:99GJgg==" + CRLF + CRLF))); } @Test public void syncStreaming_withRetry_NoSigner_shouldContainChecksum_fromInterceptors() { stubForFailureThenSuccess(500, "500"); final String expectedRequestBody = "3" + CRLF + "abc" + CRLF + "0" + CRLF + "x-amz-checksum-sha256:ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=" + CRLF + CRLF; client.putOperationWithChecksum(r -> r.checksumAlgorithm(ChecksumAlgorithm.SHA256), RequestBody.fromString("abc"), ResponseTransformer.toBytes()); List<LoggedRequest> requests = getRecordedRequests(); assertThat(requests.size()).isEqualTo(2); assertThat(requests.get(0).getBody()).contains(expectedRequestBody.getBytes()); assertThat(requests.get(1).getBody()).contains(expectedRequestBody.getBytes()); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo("text/plain; charset=UTF-8"))); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo("81"))); verify(putRequestedFor(anyUrl()).withHeader(HttpChecksumConstant.HEADER_FOR_TRAILER_REFERENCE, equalTo("x-amz-checksum-sha256"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo("3"))); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked"))); verify(putRequestedFor(anyUrl()).withRequestBody( containing( expectedRequestBody))); } private void stubResponseWithHeaders() { stubFor(put(anyUrl()) .willReturn(aResponse().withStatus(200) .withHeader("x-foo-id", "foo") .withHeader("x-bar-id", "bar") .withHeader("x-foobar-id", "foobar") .withBody("{}"))); } private void stubForFailureThenSuccess(int statusCode, String errorCode) { WireMock.reset(); stubFor(put(urlEqualTo(PATH)) .inScenario(SCENARIO) .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("1") .willReturn(aResponse() .withStatus(statusCode) .withHeader("x-amzn-ErrorType", errorCode) .withBody("{}"))); stubFor(put(urlEqualTo(PATH)) .inScenario(SCENARIO) .whenScenarioStateIs("1") .willSetStateTo("2") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); } private List<LoggedRequest> getRecordedRequests() { return findAll(putRequestedFor(urlEqualTo(PATH))); } }
2,867
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/AsyncRequestBodyFlexibleChecksumInTrailerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING; import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.stubbing.Scenario; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.HttpChecksumConstant; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.internal.async.FileAsyncRequestBody; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.model.ChecksumAlgorithm; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.utils.BinaryUtils; public class AsyncRequestBodyFlexibleChecksumInTrailerTest { public static final int KB = 1024; private static final String CRLF = "\r\n"; private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); private static final String SCENARIO = "scenario"; private static final String PATH = "/"; private static final String JSON_BODY = "{\"StringMember\":\"foo\"}"; @Rule public WireMockRule wireMock = new WireMockRule(0); private ProtocolRestJsonAsyncClient asyncClient; private ProtocolRestJsonAsyncClient asyncClientWithSigner; public static String createDataOfSize(int dataSize, char contentCharacter) { return IntStream.range(0, dataSize).mapToObj(i -> String.valueOf(contentCharacter)).collect(Collectors.joining()); } @Before public void setupClient() { asyncClientWithSigner = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .overrideConfiguration( // TODO(sra-identity-and-auth): we should remove these // overrides once we set up codegen to set chunk-encoding to true // for requests that are streaming and checksum-enabled o -> o.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, true) .putExecutionAttribute(ENABLE_PAYLOAD_SIGNING, false)) .build(); asyncClient = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(AnonymousCredentialsProvider.create()) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .overrideConfiguration( // TODO(sra-identity-and-auth): we should remove these // overrides once we set up codegen to set chunk-encoding to true // for requests that are streaming and checksum-enabled o -> o.putExecutionAttribute(ENABLE_CHUNKED_ENCODING, true) .putExecutionAttribute(ENABLE_PAYLOAD_SIGNING, false)) .build(); } @After public void cleanUp() { ENVIRONMENT_VARIABLE_HELPER.reset(); } @Test public void asyncStreaming_NoSigner_shouldContainChecksum_fromInterceptors() { stubResponseWithHeaders(); asyncClient.putOperationWithChecksum(b -> b.checksumAlgorithm(ChecksumAlgorithm.CRC32), AsyncRequestBody.fromString( "abc"), AsyncResponseTransformer.toBytes()).join(); //payload would in json form as "{"StringMember":"foo"}x-amz-checksum-crc32:tcUDMQ==[\r][\n]" verifyHeadersForPutRequest("44", "3", "x-amz-checksum-crc32"); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked"))); verify(putRequestedFor(anyUrl()).withRequestBody( containing( "3" + CRLF + "abc" + CRLF + "0" + CRLF + "x-amz-checksum-crc32:NSRBwg==" + CRLF + CRLF))); } @Test public void asyncStreaming_NoSigner_shouldContainChecksum_fromInterceptors_withContentEncoding() { stubResponseWithHeaders(); asyncClient.putOperationWithChecksum(b -> b.checksumAlgorithm(ChecksumAlgorithm.CRC32).contentEncoding("deflate"), AsyncRequestBody.fromString( "abc"), AsyncResponseTransformer.toBytes()).join(); //payload would in json form as "{"StringMember":"foo"}x-amz-checksum-crc32:tcUDMQ==[\r][\n]" verifyHeadersForPutRequest("44", "3", "x-amz-checksum-crc32"); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked"))); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("deflate"))); verify(putRequestedFor(anyUrl()).withRequestBody( containing( "3" + CRLF + "abc" + CRLF + "0" + CRLF + "x-amz-checksum-crc32:NSRBwg==" + CRLF + CRLF))); } @Test public void asyncStreaming_withRetry_NoSigner_shouldContainChecksum_fromInterceptors() { stubForFailureThenSuccess(500, "500"); final String expectedRequestBody = "3" + CRLF + "abc" + CRLF + "0" + CRLF + "x-amz-checksum-sha256:ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=" + CRLF + CRLF; asyncClient.putOperationWithChecksum(b -> b.checksumAlgorithm(ChecksumAlgorithm.SHA256), AsyncRequestBody.fromString( "abc"), AsyncResponseTransformer.toBytes()).join(); List<LoggedRequest> requests = getRecordedRequests(); assertThat(requests.size()).isEqualTo(2); assertThat(requests.get(0).getBody()).contains(expectedRequestBody.getBytes()); assertThat(requests.get(1).getBody()).contains(expectedRequestBody.getBytes()); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(Mimetype.MIMETYPE_TEXT_PLAIN + "; charset=UTF-8"))); verifyHeadersForPutRequest("81", "3", "x-amz-checksum-sha256"); verify(putRequestedFor(anyUrl()).withRequestBody( containing( expectedRequestBody))); } @Test public void asyncStreaming_FromAsyncRequestBody_VariableChunkSize_NoSigner_addsChecksums_fromInterceptors() throws IOException { stubForFailureThenSuccess(500, "500"); File randomFileOfFixedLength = new RandomTempFile(37 * KB); String contentString = new String(Files.readAllBytes(randomFileOfFixedLength.toPath())); String expectedChecksum = calculatedChecksum(contentString, Algorithm.CRC32); asyncClient.putOperationWithChecksum(b -> b.checksumAlgorithm(ChecksumAlgorithm.CRC32), FileAsyncRequestBody.builder().path(randomFileOfFixedLength.toPath()) .chunkSizeInBytes(16 * KB) .build(), AsyncResponseTransformer.toBytes()).join(); verifyHeadersForPutRequest("37948", "37888", "x-amz-checksum-crc32"); verify(putRequestedFor(anyUrl()).withRequestBody( containing( "4000" + CRLF + contentString.substring(0, 16 * KB) + CRLF + "4000" + CRLF + contentString.substring(16 * KB, 32 * KB) + CRLF + "1400" + CRLF + contentString.substring(32 * KB) + CRLF + "0" + CRLF + "x-amz-checksum-crc32:" + expectedChecksum + CRLF + CRLF))); } @Test public void asyncStreaming_withRetry_FromAsyncRequestBody_VariableChunkSize_NoSigner_addsChecksums_fromInterceptors() throws IOException { File randomFileOfFixedLength = new RandomTempFile(37 * KB); String contentString = new String(Files.readAllBytes(randomFileOfFixedLength.toPath())); String expectedChecksum = calculatedChecksum(contentString, Algorithm.CRC32); stubResponseWithHeaders(); asyncClient.putOperationWithChecksum(b -> b.checksumAlgorithm(ChecksumAlgorithm.CRC32), FileAsyncRequestBody.builder().path(randomFileOfFixedLength.toPath()) .chunkSizeInBytes(16 * KB) .build(), AsyncResponseTransformer.toBytes()).join(); verifyHeadersForPutRequest("37948", "37888", "x-amz-checksum-crc32"); verify(putRequestedFor(anyUrl()).withRequestBody( containing( "4000" + CRLF + contentString.substring(0, 16 * KB) + CRLF + "4000" + CRLF + contentString.substring(16 * KB, 32 * KB) + CRLF + "1400" + CRLF + contentString.substring(32 * KB) + CRLF + "0" + CRLF + "x-amz-checksum-crc32:" + expectedChecksum + CRLF + CRLF))); } private String calculatedChecksum(String contentString, Algorithm algorithm) { SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm); for (byte character : contentString.getBytes(StandardCharsets.UTF_8)) { sdkChecksum.update(character); } return BinaryUtils.toBase64(sdkChecksum.getChecksumBytes()); } private void stubResponseWithHeaders() { stubFor(put(anyUrl()) .willReturn(aResponse().withStatus(200) .withHeader("x-foo-id", "foo") .withHeader("x-bar-id", "bar") .withHeader("x-foobar-id", "foobar") .withBody("{}"))); } private void stubForFailureThenSuccess(int statusCode, String errorCode) { WireMock.reset(); stubFor(put(urlEqualTo(PATH)) .inScenario(SCENARIO) .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("1") .willReturn(aResponse() .withStatus(statusCode) .withHeader("x-amzn-ErrorType", errorCode) .withBody("{}"))); stubFor(put(urlEqualTo(PATH)) .inScenario(SCENARIO) .whenScenarioStateIs("1") .willSetStateTo("2") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); } private List<LoggedRequest> getRecordedRequests() { return findAll(putRequestedFor(urlEqualTo(PATH))); } private void verifyHeadersForPutRequest(String contentLength, String decodedContentLength, String checksumHeader) { verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo(contentLength))); verify(putRequestedFor(anyUrl()).withHeader(HttpChecksumConstant.HEADER_FOR_TRAILER_REFERENCE, equalTo( checksumHeader))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo(decodedContentLength))); verify(putRequestedFor(anyUrl()).withHeader("content-encoding", equalTo("aws-chunked"))); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked"))); } }
2,868
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/HttpChecksumRequiredTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import io.reactivex.Flowable; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.awscore.client.builder.AwsAsyncClientBuilder; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.model.ChecksumAlgorithm; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient; /** * Verify that the "httpChecksumRequired" C2J trait results in a valid MD5 checksum of the payload being included in the HTTP * request. */ public class HttpChecksumRequiredTest { private SdkHttpClient httpClient; private SdkAsyncHttpClient httpAsyncClient; private ProtocolRestJsonClient jsonClient; private ProtocolRestJsonAsyncClient jsonAsyncClient; private ProtocolRestXmlClient xmlClient; private ProtocolRestXmlAsyncClient xmlAsyncClient; @Before public void setup() throws IOException { httpClient = Mockito.mock(SdkHttpClient.class); httpAsyncClient = Mockito.mock(SdkAsyncHttpClient.class); jsonClient = initializeSync(ProtocolRestJsonClient.builder()).build(); jsonAsyncClient = initializeAsync(ProtocolRestJsonAsyncClient.builder()).build(); xmlClient = initializeSync(ProtocolRestXmlClient.builder()).build(); xmlAsyncClient = initializeAsync(ProtocolRestXmlAsyncClient.builder()).build(); SdkHttpFullResponse successfulHttpResponse = SdkHttpResponse.builder() .statusCode(200) .putHeader("Content-Length", "0") .build(); ExecutableHttpRequest request = Mockito.mock(ExecutableHttpRequest.class); Mockito.when(request.call()).thenReturn(HttpExecuteResponse.builder() .response(successfulHttpResponse) .build()); Mockito.when(httpClient.prepareRequest(any())).thenReturn(request); Mockito.when(httpAsyncClient.execute(any())).thenAnswer(invocation -> { AsyncExecuteRequest asyncExecuteRequest = invocation.getArgument(0, AsyncExecuteRequest.class); asyncExecuteRequest.responseHandler().onHeaders(successfulHttpResponse); asyncExecuteRequest.responseHandler().onStream(Flowable.empty()); return CompletableFuture.completedFuture(null); }); } private <T extends AwsSyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeSync(T syncClientBuilder) { return initialize(syncClientBuilder.httpClient(httpClient)); } private <T extends AwsAsyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeAsync(T asyncClientBuilder) { return initialize(asyncClientBuilder.httpClient(httpAsyncClient)); } private <T extends AwsClientBuilder<T, ?>> T initialize(T clientBuilder) { return clientBuilder.credentialsProvider(AnonymousCredentialsProvider.create()) .region(Region.US_WEST_2); } @Test public void syncJsonSupportsChecksumRequiredTrait() { jsonClient.operationWithRequiredChecksum(r -> r.stringMember("foo")); assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).hasValue("g8VCvPTPCMoU01rBlBVt9w=="); } @Test public void syncStreamingInputJsonSupportsChecksumRequiredTrait() { jsonClient.streamingInputOperationWithRequiredChecksum(r -> {}, RequestBody.fromString("foo")); assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).hasValue("rL0Y20zC+Fzt72VPzMSk2A=="); } @Test public void syncStreamingInputXmlSupportsChecksumRequiredTrait() { xmlClient.streamingInputOperationWithRequiredChecksum(r -> {}, RequestBody.fromString("foo")); assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).hasValue("rL0Y20zC+Fzt72VPzMSk2A=="); } @Test public void syncXmlSupportsChecksumRequiredTrait() { xmlClient.operationWithRequiredChecksum(r -> r.stringMember("foo")); assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).hasValue("vqm481l+Lv0zEvdu+duE6Q=="); } @Test public void asyncJsonSupportsChecksumRequiredTrait() { jsonAsyncClient.operationWithRequiredChecksum(r -> r.stringMember("foo")).join(); assertThat(getAsyncRequest().firstMatchingHeader("Content-MD5")).hasValue("g8VCvPTPCMoU01rBlBVt9w=="); } @Test public void asyncXmlSupportsChecksumRequiredTrait() { xmlAsyncClient.operationWithRequiredChecksum(r -> r.stringMember("foo")).join(); assertThat(getAsyncRequest().firstMatchingHeader("Content-MD5")).hasValue("vqm481l+Lv0zEvdu+duE6Q=="); } @Test(expected = CompletionException.class) public void asyncStreamingInputJsonFailsWithChecksumRequiredTrait() { jsonAsyncClient.streamingInputOperationWithRequiredChecksum(r -> {}, AsyncRequestBody.fromString("foo")).join(); } @Test(expected = CompletionException.class) public void asyncStreamingInputXmlFailsWithChecksumRequiredTrait() { xmlAsyncClient.streamingInputOperationWithRequiredChecksum(r -> {}, AsyncRequestBody.fromString("foo")).join(); } @Test public void syncJsonSupportsOperationWithRequestChecksumRequired() { jsonClient.operationWithRequestChecksumRequired(r -> r.stringMember("foo")); assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).hasValue("g8VCvPTPCMoU01rBlBVt9w=="); } @Test public void syncJsonSupportsOperationWithCustomRequestChecksum() { jsonClient.operationWithCustomRequestChecksum(r -> r.stringMember("foo").checksumAlgorithm(ChecksumAlgorithm.CRC32)); assertThat(getSyncRequest().firstMatchingHeader("Content-MD5")).isNotPresent(); assertThat(getSyncRequest().firstMatchingHeader("x-amz-checksum-crc32")).hasValue("rzlTOg=="); } private SdkHttpRequest getSyncRequest() { ArgumentCaptor<HttpExecuteRequest> captor = ArgumentCaptor.forClass(HttpExecuteRequest.class); Mockito.verify(httpClient).prepareRequest(captor.capture()); return captor.getValue().httpRequest(); } private SdkHttpRequest getAsyncRequest() { ArgumentCaptor<AsyncExecuteRequest> captor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); Mockito.verify(httpAsyncClient).execute(captor.capture()); return captor.getValue().request(); } }
2,869
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/AsyncRequestCompressionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.Assertions.assertThat; import io.reactivex.Flowable; import java.io.InputStream; import java.nio.ByteBuffer; import java.time.Duration; import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscriber; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.internal.compression.Compressor; import software.amazon.awssdk.core.internal.compression.GzipCompressor; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.model.PutOperationWithRequestCompressionRequest; import software.amazon.awssdk.services.protocolrestjson.model.PutOperationWithStreamingRequestCompressionRequest; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; public class AsyncRequestCompressionTest { private static final String UNCOMPRESSED_BODY = "RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest"; private String compressedBody; private int compressedLen; private MockAsyncHttpClient mockAsyncHttpClient; private ProtocolRestJsonAsyncClient asyncClient; private Compressor compressor; @BeforeEach public void setUp() { mockAsyncHttpClient = new MockAsyncHttpClient(); asyncClient = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(AnonymousCredentialsProvider.create()) .region(Region.US_EAST_1) .httpClient(mockAsyncHttpClient) .build(); compressor = new GzipCompressor(); byte[] compressedBodyBytes = compressor.compress(UNCOMPRESSED_BODY.getBytes()); compressedBody = new String(compressedBodyBytes); compressedLen = compressedBodyBytes.length; } @AfterEach public void reset() { mockAsyncHttpClient.reset(); } @Test public void asyncNonStreamingOperation_compressionEnabledThresholdOverridden_compressesCorrectly() { mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); PutOperationWithRequestCompressionRequest request = PutOperationWithRequestCompressionRequest.builder() .body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY)) .overrideConfiguration(o -> o.compressionConfiguration( c -> c.minimumCompressionThresholdInBytes(1))) .build(); asyncClient.putOperationWithRequestCompression(request); SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockAsyncHttpClient.getLastRequest(); InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream(); String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray()); int loggedSize = Integer.valueOf(loggedRequest.firstMatchingHeader("Content-Length").get()); assertThat(loggedBody).isEqualTo(compressedBody); assertThat(loggedSize).isEqualTo(compressedLen); assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip"); } @Test public void asyncNonStreamingOperation_payloadSizeLessThanCompressionThreshold_doesNotCompress() { mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); PutOperationWithRequestCompressionRequest request = PutOperationWithRequestCompressionRequest.builder() .body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY)) .build(); asyncClient.putOperationWithRequestCompression(request); SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockAsyncHttpClient.getLastRequest(); InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream(); String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray()); int loggedSize = Integer.valueOf(loggedRequest.firstMatchingHeader("Content-Length").get()); assertThat(loggedBody).isEqualTo(UNCOMPRESSED_BODY); assertThat(loggedSize).isEqualTo(UNCOMPRESSED_BODY.length()); assertThat(loggedRequest.firstMatchingHeader("Content-encoding")).isEmpty(); } @Test public void asyncStreamingOperation_compressionEnabled_compressesCorrectly() { mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); mockAsyncHttpClient.setAsyncRequestBodyLength(compressedBody.length()); PutOperationWithStreamingRequestCompressionRequest request = PutOperationWithStreamingRequestCompressionRequest.builder().build(); asyncClient.putOperationWithStreamingRequestCompression(request, customAsyncRequestBodyWithoutContentLength(), AsyncResponseTransformer.toBytes()).join(); SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockAsyncHttpClient.getLastRequest(); String loggedBody = new String(mockAsyncHttpClient.getStreamingPayload().get()); assertThat(loggedBody).isEqualTo(compressedBody); assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip"); assertThat(loggedRequest.matchingHeaders("Content-Length")).isEmpty(); assertThat(loggedRequest.firstMatchingHeader("Transfer-Encoding").get()).isEqualTo("chunked"); } @Test public void asyncNonStreamingOperation_compressionEnabledThresholdOverriddenWithRetry_compressesCorrectly() { mockAsyncHttpClient.stubNextResponse(mockErrorResponse(), Duration.ofMillis(500)); mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); PutOperationWithRequestCompressionRequest request = PutOperationWithRequestCompressionRequest.builder() .body(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY)) .overrideConfiguration(o -> o.compressionConfiguration( c -> c.minimumCompressionThresholdInBytes(1))) .build(); asyncClient.putOperationWithRequestCompression(request); SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockAsyncHttpClient.getLastRequest(); InputStream loggedStream = loggedRequest.contentStreamProvider().get().newStream(); String loggedBody = new String(SdkBytes.fromInputStream(loggedStream).asByteArray()); int loggedSize = Integer.valueOf(loggedRequest.firstMatchingHeader("Content-Length").get()); assertThat(loggedBody).isEqualTo(compressedBody); assertThat(loggedSize).isEqualTo(compressedLen); assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip"); } @Test public void asyncStreamingOperation_compressionEnabledWithRetry_compressesCorrectly() { mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); mockAsyncHttpClient.stubNextResponse(mockResponse(), Duration.ofMillis(500)); mockAsyncHttpClient.setAsyncRequestBodyLength(compressedBody.length()); PutOperationWithStreamingRequestCompressionRequest request = PutOperationWithStreamingRequestCompressionRequest.builder().build(); asyncClient.putOperationWithStreamingRequestCompression(request, customAsyncRequestBodyWithoutContentLength(), AsyncResponseTransformer.toBytes()).join(); SdkHttpFullRequest loggedRequest = (SdkHttpFullRequest) mockAsyncHttpClient.getLastRequest(); String loggedBody = new String(mockAsyncHttpClient.getStreamingPayload().get()); assertThat(loggedBody).isEqualTo(compressedBody); assertThat(loggedRequest.firstMatchingHeader("Content-encoding").get()).isEqualTo("gzip"); assertThat(loggedRequest.matchingHeaders("Content-Length")).isEmpty(); assertThat(loggedRequest.firstMatchingHeader("Transfer-Encoding").get()).isEqualTo("chunked"); } private HttpExecuteResponse mockResponse() { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200).build()) .build(); } private HttpExecuteResponse mockErrorResponse() { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(500).build()) .build(); } protected AsyncRequestBody customAsyncRequestBodyWithoutContentLength() { return new AsyncRequestBody() { @Override public Optional<Long> contentLength() { return Optional.empty(); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { Flowable.fromPublisher(AsyncRequestBody.fromBytes(UNCOMPRESSED_BODY.getBytes())) .subscribe(s); } }; } }
2,870
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/SdkPluginTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static software.amazon.awssdk.profiles.ProfileFile.Type.CONFIGURATION; import java.lang.reflect.Field; import java.net.URI; import java.time.Duration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Supplier; import java.util.stream.Stream; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.CompressionConfiguration; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.client.builder.SdkClientBuilder; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.scheme.NoAuthAuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonServiceClientConfiguration; import software.amazon.awssdk.services.protocolrestjson.auth.scheme.ProtocolRestJsonAuthSchemeProvider; import software.amazon.awssdk.services.protocolrestjson.endpoints.ProtocolRestJsonEndpointProvider; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.awssdk.utils.Lazy; import software.amazon.awssdk.utils.StringInputStream; /** * Verify that configuration changes made by plugins are reflected in the SDK client configuration used by the request, and * that the plugin can see all SDK configuration options. */ public class SdkPluginTest { private static final AwsCredentialsProvider DEFAULT_CREDENTIALS = () -> AwsBasicCredentials.create("akid", "skid"); public static Stream<TestCase<?>> testCases() { Map<String, AuthScheme<?>> defaultAuthSchemes = ImmutableMap.of(AwsV4AuthScheme.SCHEME_ID, AwsV4AuthScheme.create(), NoAuthAuthScheme.SCHEME_ID, NoAuthAuthScheme.create()); Map<String, AuthScheme<?>> nonDefaultAuthSchemes = new HashMap<>(defaultAuthSchemes); nonDefaultAuthSchemes.put(CustomAuthScheme.SCHEME_ID, new CustomAuthScheme()); ScheduledExecutorService mockScheduledExecutor = mock(ScheduledExecutorService.class); MetricPublisher mockMetricPublisher = mock(MetricPublisher.class); String profileFileContent = "[default]\n" + ProfileProperty.USE_FIPS_ENDPOINT + " = true" + "[profile some-profile]\n" + ProfileProperty.USE_FIPS_ENDPOINT + " = false"; ProfileFile nonDefaultProfileFile = ProfileFile.builder() .type(CONFIGURATION) .content(new StringInputStream(profileFileContent)) .build(); return Stream.of( new TestCase<URI>("endpointOverride") .nonDefaultValue(URI.create("https://example.aws")) .clientSetter(SdkClientBuilder::endpointOverride) .pluginSetter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointOverride) .pluginValidator((c, v) -> assertThat(v).isEqualTo(c.endpointOverride())) .beforeTransmissionValidator((r, a, v) -> { assertThat(v).isEqualTo(removePathAndQueryString(r.httpRequest().getUri())); }), new TestCase<ProtocolRestJsonEndpointProvider>("endpointProvider") .defaultValue(ProtocolRestJsonEndpointProvider.defaultProvider()) .nonDefaultValue(a -> CompletableFuture.completedFuture(Endpoint.builder() .url(URI.create("https://example.aws")) .build())) .clientSetter(ProtocolRestJsonClientBuilder::endpointProvider) .requestSetter(RequestOverrideConfiguration.Builder::endpointProvider) .pluginSetter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointProvider) .pluginValidator((c, v) -> assertThat(c.endpointProvider()).isEqualTo(v)) .beforeTransmissionValidator((r, a, v) -> { assertThat(removePathAndQueryString(r.httpRequest().getUri())) .isEqualTo(v.resolveEndpoint(x -> {}).join().url()); }), new TestCase<Map<String, AuthScheme<?>>>("authSchemes") .defaultValue(defaultAuthSchemes) .nonDefaultValue(nonDefaultAuthSchemes) .clientSetter((b, v) -> v.forEach((x, scheme) -> b.putAuthScheme(scheme))) .pluginSetter((b, v) -> v.forEach((x, scheme) -> b.putAuthScheme(scheme))) .pluginValidator((c, v) -> v.forEach((id, s) -> assertThat(c.authSchemes()).containsEntry(id, s))) .beforeTransmissionValidator((r, a, v) -> v.forEach((id, s) -> { assertThat(a.getAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES)).containsEntry(id, s); })), new TestCase<Region>("region") .defaultValue(Region.US_WEST_2) .nonDefaultValue(Region.US_EAST_1) .clientSetter(AwsClientBuilder::region) .pluginSetter(ProtocolRestJsonServiceClientConfiguration.Builder::region) .pluginValidator((c, v) -> assertThat(c.region()).isEqualTo(v)) .beforeTransmissionValidator((r, a, v) -> { assertThat(r.httpRequest() .firstMatchingHeader("Authorization")).get() .asString() .contains(v.id()); assertThat(r.httpRequest().getUri().getHost()).contains(v.id()); }), new TestCase<AwsCredentialsProvider>("credentialsProvider") .defaultValue(DEFAULT_CREDENTIALS) .nonDefaultValue(DEFAULT_CREDENTIALS::resolveCredentials) .clientSetter(AwsClientBuilder::credentialsProvider) .requestSetter(AwsRequestOverrideConfiguration.Builder::credentialsProvider) .pluginSetter(ProtocolRestJsonServiceClientConfiguration.Builder::credentialsProvider) .pluginValidator((c, v) -> assertThat(c.credentialsProvider()).isEqualTo(v)) .beforeTransmissionValidator((r, a, v) -> { assertThat(r.httpRequest() .firstMatchingHeader("Authorization")).get() .asString() .contains(v.resolveCredentials().accessKeyId()); }), new TestCase<ProtocolRestJsonAuthSchemeProvider>("authSchemeProvider") .defaultValue(ProtocolRestJsonAuthSchemeProvider.defaultProvider()) .nonDefaultValue(p -> singletonList(AuthSchemeOption.builder().schemeId(NoAuthAuthScheme.SCHEME_ID).build())) .clientSetter(ProtocolRestJsonClientBuilder::authSchemeProvider) .pluginSetter(ProtocolRestJsonServiceClientConfiguration.Builder::authSchemeProvider) .pluginValidator((c, v) -> assertThat(c.authSchemeProvider()).isEqualTo(v)) .beforeTransmissionValidator((r, a, v) -> { assertThat(a.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME) .authSchemeOption() .schemeId()).isEqualTo(NoAuthAuthScheme.SCHEME_ID); assertThat(r.httpRequest().firstMatchingHeader("Authorization")).isNotPresent(); }), new TestCase<Map<String, List<String>>>("override.headers") .defaultValue(emptyMap()) .nonDefaultValue(singletonMap("foo", singletonList("bar"))) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.headers(v))) .requestSetter(AwsRequestOverrideConfiguration.Builder::headers) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.headers(v)))) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().headers()).isEqualTo(v)) .beforeTransmissionValidator((r, a, v) -> { v.forEach((key, value) -> assertThat(r.httpRequest().headers().get(key)).isEqualTo(value)); }), new TestCase<RetryPolicy>("override.retryPolicy") .defaultValue(RetryPolicy.defaultRetryPolicy()) .nonDefaultValue(RetryPolicy.builder(RetryMode.STANDARD).numRetries(1).build()) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.retryPolicy(v))) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.retryPolicy(v)))) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().retryPolicy().get().numRetries()) .isEqualTo(v.numRetries())) .beforeTransmissionValidator((r, a, v) -> { assertThat(r.httpRequest().firstMatchingHeader("amz-sdk-request")) .hasValue("attempt=1; max=" + (v.numRetries() + 1)); }), new TestCase<List<ExecutionInterceptor>>("override.executionInterceptors") .defaultValue(emptyList()) .nonDefaultValue(singletonList(new FlagSettingInterceptor())) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.executionInterceptors(v))) .pluginSetter((b, v) -> { b.overrideConfiguration(b.overrideConfiguration().copy(c -> v.forEach(c::addExecutionInterceptor))); }) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().executionInterceptors()).containsAll(v)) .beforeTransmissionValidator((r, a, v) -> { if (v.stream().anyMatch(i -> i instanceof FlagSettingInterceptor)) { assertThat(a.getAttribute(FlagSettingInterceptor.FLAG)).isEqualTo(true); } else { assertThat(a.getAttribute(FlagSettingInterceptor.FLAG)).isNull(); } }), new TestCase<ScheduledExecutorService>("override.scheduledExecutorService") .defaultValue(null) .nonDefaultValue(mockScheduledExecutor) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.scheduledExecutorService(v))) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.scheduledExecutorService(v)))) .pluginValidator((c, v) -> { Optional<ScheduledExecutorService> executor = c.overrideConfiguration().scheduledExecutorService(); if (v != null) { // The SDK should decorate the non-default-value. Ensure that's what happened. Runnable runnable = () -> {}; v.submit(runnable); assertThat(v).isEqualTo(mockScheduledExecutor); Mockito.verify(v, times(1)).submit(eq(runnable)); } else { // Null means we're using the default, and the default should be specified by the runtime. assertThat(executor).isPresent(); } }) .clientConfigurationValidator((c, v) -> { ScheduledExecutorService configuredService = c.option(SdkClientOption.SCHEDULED_EXECUTOR_SERVICE); if (mockScheduledExecutor.equals(v)) { // The SDK should decorate the non-default-value. Ensure that's what happened. Runnable runnable = () -> {}; configuredService.submit(runnable); assertThat(v).isEqualTo(mockScheduledExecutor); Mockito.verify(v, times(1)).submit(eq(runnable)); } else { assertThat(configuredService).isNotNull(); } }), new TestCase<Map<SdkAdvancedClientOption<?>, ?>>("override.advancedOptions") .defaultValue(emptyMap()) .nonDefaultValue(singletonMap(SdkAdvancedClientOption.USER_AGENT_PREFIX, "foo")) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.advancedOptions(v))) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> { v.forEach((option, value) -> unsafePutOption(c, option, value)); }))) .pluginValidator((c, v) -> { v.forEach((o, ov) -> assertThat(c.overrideConfiguration().advancedOption(o).orElse(null)).isEqualTo(ov)); }) .clientConfigurationValidator((c, v) -> v.forEach((o, ov) -> assertThat(c.option(o)).isEqualTo(ov))), new TestCase<Duration>("override.apiCallTimeout") .defaultValue(null) .nonDefaultValue(Duration.ofSeconds(5)) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.apiCallTimeout(v))) .requestSetter(AwsRequestOverrideConfiguration.Builder::apiCallTimeout) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.apiCallTimeout(v)))) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().apiCallTimeout().orElse(null)).isEqualTo(v)) .clientConfigurationValidator((c, v) -> assertThat(c.option(SdkClientOption.API_CALL_TIMEOUT)).isEqualTo(v)), new TestCase<Duration>("override.apiCallAttemptTimeout") .defaultValue(null) .nonDefaultValue(Duration.ofSeconds(3)) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.apiCallAttemptTimeout(v))) .requestSetter(AwsRequestOverrideConfiguration.Builder::apiCallAttemptTimeout) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.apiCallAttemptTimeout(v)))) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().apiCallAttemptTimeout().orElse(null)).isEqualTo(v)) .clientConfigurationValidator((c, v) -> assertThat(c.option(SdkClientOption.API_CALL_ATTEMPT_TIMEOUT)).isEqualTo(v)), new TestCase<Supplier<ProfileFile>>("override.defaultProfileFileSupplier") .defaultValue(new Lazy<>(ProfileFile::defaultProfileFile)::getValue) .nonDefaultValue(() -> nonDefaultProfileFile) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.defaultProfileFileSupplier(v))) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.defaultProfileFileSupplier(v)))) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().defaultProfileFileSupplier().get().get()).isEqualTo(v.get())) .clientConfigurationValidator((c, v) -> { Supplier<ProfileFile> supplier = c.option(SdkClientOption.PROFILE_FILE_SUPPLIER); assertThat(supplier.get()).isEqualTo(v.get()); Optional<Profile> defaultProfile = v.get().profile("default"); defaultProfile.ifPresent(profile -> { profile.booleanProperty(ProfileProperty.USE_FIPS_ENDPOINT).ifPresent(d -> { assertThat(c.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isEqualTo(d); }); }); if (!defaultProfile.isPresent()) { assertThat(c.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isIn(null, false); } }), new TestCase<ProfileFile>("override.defaultProfileFile") .defaultValue(ProfileFile.defaultProfileFile()) .nonDefaultValue(nonDefaultProfileFile) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.defaultProfileFile(v))) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.defaultProfileFile(v)))) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().defaultProfileFile()).hasValue(v)) .clientConfigurationValidator((c, v) -> assertThat(c.option(SdkClientOption.PROFILE_FILE)).isEqualTo(v)), new TestCase<String>("override.defaultProfileName") .defaultValue("default") .nonDefaultValue("some-profile") .clientSetter((b, v) -> b.overrideConfiguration(c -> c.defaultProfileName(v) .defaultProfileFile(nonDefaultProfileFile))) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.defaultProfileName(v) .defaultProfileFile(nonDefaultProfileFile)))) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().defaultProfileName().orElse(null)).isEqualTo(v)) .clientConfigurationValidator((c, v) -> { assertThat(c.option(SdkClientOption.PROFILE_NAME)).isEqualTo(v); ProfileFile profileFile = c.option(SdkClientOption.PROFILE_FILE_SUPPLIER).get(); Optional<Profile> configuredProfile = profileFile.profile(v); configuredProfile.ifPresent(profile -> { profile.booleanProperty(ProfileProperty.USE_FIPS_ENDPOINT).ifPresent(d -> { assertThat(c.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isEqualTo(d); }); }); if (!configuredProfile.isPresent()) { assertThat(c.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isIn(null, false); } }), new TestCase<List<MetricPublisher>>("override.metricPublishers") .defaultValue(emptyList()) .nonDefaultValue(singletonList(mockMetricPublisher)) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.metricPublishers(v))) .requestSetter(AwsRequestOverrideConfiguration.Builder::metricPublishers) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.metricPublishers(v)))) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().metricPublishers()).isEqualTo(v)) .clientConfigurationValidator((c, v) -> { assertThat(c.option(SdkClientOption.METRIC_PUBLISHERS)).containsAll(v); }), new TestCase<ExecutionAttributes>("override.executionAttributes") .defaultValue(new ExecutionAttributes()) .nonDefaultValue(new ExecutionAttributes().putAttribute(FlagSettingInterceptor.FLAG, true)) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.executionAttributes(v))) .requestSetter(AwsRequestOverrideConfiguration.Builder::executionAttributes) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.executionAttributes(v)))) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().executionAttributes()).isEqualTo(v)) .beforeTransmissionValidator((r, a, v) -> { assertThat(a.getAttribute(FlagSettingInterceptor.FLAG)).isTrue(); }), new TestCase<CompressionConfiguration>("override.compressionConfiguration") .defaultValue(CompressionConfiguration.builder() .requestCompressionEnabled(true) .minimumCompressionThresholdInBytes(10_240) .build()) .nonDefaultValue(CompressionConfiguration.builder() .requestCompressionEnabled(true) .minimumCompressionThresholdInBytes(1) .build()) .clientSetter((b, v) -> b.overrideConfiguration(c -> c.compressionConfiguration(v))) .requestSetter(AwsRequestOverrideConfiguration.Builder::compressionConfiguration) .pluginSetter((b, v) -> b.overrideConfiguration(b.overrideConfiguration().copy(c -> c.compressionConfiguration(v)))) .pluginValidator((c, v) -> assertThat(c.overrideConfiguration().compressionConfiguration().orElse(null)).isEqualTo(v)) .clientConfigurationValidator((c, v) -> assertThat(c.option(SdkClientOption.COMPRESSION_CONFIGURATION)).isEqualTo(v)) ); } private static <T> void unsafePutOption(ClientOverrideConfiguration.Builder config, SdkAdvancedClientOption<T> option, Object value) { config.putAdvancedOption(option, option.convertValue(value)); } @ParameterizedTest @MethodSource("testCases") public <T> void validateTestCaseData(TestCase<T> testCase) { assertThat(testCase.defaultValue).isNotEqualTo(testCase.nonDefaultValue); } @ParameterizedTest @MethodSource("testCases") public <T> void clientPluginSeesDefaultValue(TestCase<T> testCase) { ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder(); AtomicInteger timesCalled = new AtomicInteger(0); SdkPlugin plugin = config -> { ProtocolRestJsonServiceClientConfiguration.Builder conf = (ProtocolRestJsonServiceClientConfiguration.Builder) config; testCase.pluginValidator.accept(conf, testCase.defaultValue); timesCalled.incrementAndGet(); }; ProtocolRestJsonClient client = clientBuilder.addPlugin(plugin).build(); if (testCase.clientConfigurationValidator != null) { testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.defaultValue); } assertThat(timesCalled).hasValue(1); } @ParameterizedTest @MethodSource("testCases") public <T> void requestPluginSeesDefaultValue(TestCase<T> testCase) { ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder(); AtomicInteger timesCalled = new AtomicInteger(0); SdkPlugin plugin = config -> { ProtocolRestJsonServiceClientConfiguration.Builder conf = (ProtocolRestJsonServiceClientConfiguration.Builder) config; testCase.pluginValidator.accept(conf, testCase.defaultValue); timesCalled.incrementAndGet(); }; ProtocolRestJsonClient client = clientBuilder.httpClient(succeedingHttpClient()).build(); if (testCase.clientConfigurationValidator != null) { testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.defaultValue); } client.allTypes(r -> r.overrideConfiguration(c -> c.addPlugin(plugin))); assertThat(timesCalled).hasValue(1); } @ParameterizedTest @MethodSource("testCases") public <T> void clientPluginSeesCustomerClientConfiguredValue(TestCase<T> testCase) { ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder(); testCase.clientSetter.accept(clientBuilder, testCase.nonDefaultValue); AtomicInteger timesCalled = new AtomicInteger(0); SdkPlugin plugin = config -> { ProtocolRestJsonServiceClientConfiguration.Builder conf = (ProtocolRestJsonServiceClientConfiguration.Builder) config; testCase.pluginValidator.accept(conf, testCase.nonDefaultValue); timesCalled.incrementAndGet(); }; ProtocolRestJsonClient client = clientBuilder.addPlugin(plugin).build(); if (testCase.clientConfigurationValidator != null) { testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.nonDefaultValue); } assertThat(timesCalled).hasValue(1); } @ParameterizedTest @MethodSource("testCases") public <T> void requestPluginSeesCustomerClientConfiguredValue(TestCase<T> testCase) { ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder(); testCase.clientSetter.accept(clientBuilder, testCase.nonDefaultValue); AtomicInteger timesCalled = new AtomicInteger(0); SdkPlugin plugin = config -> { ProtocolRestJsonServiceClientConfiguration.Builder conf = (ProtocolRestJsonServiceClientConfiguration.Builder) config; testCase.pluginValidator.accept(conf, testCase.nonDefaultValue); timesCalled.incrementAndGet(); }; ProtocolRestJsonClient client = clientBuilder.httpClient(succeedingHttpClient()).build(); if (testCase.clientConfigurationValidator != null) { testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.nonDefaultValue); } client.allTypes(r -> r.overrideConfiguration(c -> c.addPlugin(plugin))); assertThat(timesCalled).hasValue(1); } @ParameterizedTest @MethodSource("testCases") @Disabled("Request-level values are currently higher-priority than plugin settings.") // TODO(sra-identity-auth) public <T> void requestPluginSeesCustomerRequestConfiguredValue(TestCase<T> testCase) { if (testCase.requestSetter == null) { System.out.println("No request setting available."); return; } ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder(); AtomicInteger timesCalled = new AtomicInteger(0); SdkPlugin plugin = config -> { ProtocolRestJsonServiceClientConfiguration.Builder conf = (ProtocolRestJsonServiceClientConfiguration.Builder) config; testCase.pluginValidator.accept(conf, testCase.nonDefaultValue); timesCalled.incrementAndGet(); }; AwsRequestOverrideConfiguration overrideConfig = AwsRequestOverrideConfiguration.builder() .addPlugin(plugin) .applyMutation(c -> testCase.requestSetter.accept(c, testCase.nonDefaultValue)) .build(); ProtocolRestJsonClient client = clientBuilder.httpClient(succeedingHttpClient()).build(); if (testCase.clientConfigurationValidator != null) { testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.defaultValue); } client.allTypes(r -> r.overrideConfiguration(overrideConfig)); assertThat(timesCalled).hasValue(1); } @ParameterizedTest @MethodSource("testCases") public <T> void clientPluginSetValueIsUsed(TestCase<T> testCase) { ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder(); testCase.clientSetter.accept(clientBuilder, testCase.defaultValue); AtomicInteger timesPluginCalled = new AtomicInteger(0); SdkPlugin plugin = config -> { timesPluginCalled.incrementAndGet(); ProtocolRestJsonServiceClientConfiguration.Builder conf = (ProtocolRestJsonServiceClientConfiguration.Builder) config; testCase.pluginSetter.accept(conf, testCase.nonDefaultValue); }; AtomicInteger timesInterceptorCalled = new AtomicInteger(0); ExecutionInterceptor validatingInterceptor = new ExecutionInterceptor() { @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { timesInterceptorCalled.getAndIncrement(); if (testCase.beforeTransmissionValidator != null) { testCase.beforeTransmissionValidator.accept(context, executionAttributes, testCase.nonDefaultValue); } } }; ProtocolRestJsonClient client = clientBuilder.httpClient(succeedingHttpClient()) .addPlugin(plugin) .overrideConfiguration(c -> c.addExecutionInterceptor(validatingInterceptor)) .build(); if (testCase.clientConfigurationValidator != null) { testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.nonDefaultValue); } client.allTypes(); assertThat(timesPluginCalled).hasValue(1); assertThat(timesInterceptorCalled).hasValueGreaterThanOrEqualTo(1); } @ParameterizedTest @MethodSource("testCases") public <T> void requestPluginSetValueIsUsed(TestCase<T> testCase) { ProtocolRestJsonClientBuilder clientBuilder = defaultClientBuilder(); testCase.clientSetter.accept(clientBuilder, testCase.defaultValue); AtomicInteger timesPluginCalled = new AtomicInteger(0); SdkPlugin plugin = config -> { timesPluginCalled.incrementAndGet(); ProtocolRestJsonServiceClientConfiguration.Builder conf = (ProtocolRestJsonServiceClientConfiguration.Builder) config; testCase.pluginSetter.accept(conf, testCase.nonDefaultValue); }; AtomicInteger timesInterceptorCalled = new AtomicInteger(0); ExecutionInterceptor validatingInterceptor = new ExecutionInterceptor() { @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { timesInterceptorCalled.incrementAndGet(); if (testCase.beforeTransmissionValidator != null) { testCase.beforeTransmissionValidator.accept(context, executionAttributes, testCase.nonDefaultValue); } } }; AwsRequestOverrideConfiguration requestConfig = AwsRequestOverrideConfiguration.builder() .addPlugin(plugin) .applyMutation(c -> { // TODO(sra-identity-auth): request-level plugins should override request-level // configuration // if (testCase.requestSetter != null) { // testCase.requestSetter.accept(c, testCase.defaultValue); // } }) .build(); ProtocolRestJsonClient client = clientBuilder.httpClient(succeedingHttpClient()) .overrideConfiguration(c -> c.addExecutionInterceptor(validatingInterceptor)) .build(); if (testCase.clientConfigurationValidator != null) { testCase.clientConfigurationValidator.accept(extractClientConfiguration(client), testCase.defaultValue); } client.allTypes(r -> r.overrideConfiguration(requestConfig)); assertThat(timesPluginCalled).hasValue(1); assertThat(timesInterceptorCalled).hasValueGreaterThanOrEqualTo(1); } private static ProtocolRestJsonClientBuilder defaultClientBuilder() { return ProtocolRestJsonClient.builder().region(Region.US_WEST_2).credentialsProvider(DEFAULT_CREDENTIALS); } private SdkClientConfiguration extractClientConfiguration(ProtocolRestJsonClient client) { try { // Naughty, but we need to be able to verify some things that can't be easily observed with unprotected means. Class<? extends ProtocolRestJsonClient> clientClass = client.getClass(); Field configField = clientClass.getDeclaredField("clientConfiguration"); configField.setAccessible(true); return (SdkClientConfiguration) configField.get(client); } catch (Exception e) { throw new RuntimeException(e); } } static class TestCase<T> { private final String configName; T defaultValue; T nonDefaultValue; BiConsumer<ProtocolRestJsonClientBuilder, T> clientSetter; BiConsumer<AwsRequestOverrideConfiguration.Builder, T> requestSetter; BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> pluginSetter; BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> pluginValidator; BiConsumer<SdkClientConfiguration, T> clientConfigurationValidator; TriConsumer<Context.BeforeTransmission, ExecutionAttributes, T> beforeTransmissionValidator; TestCase(String configName) { this.configName = configName; } public TestCase<T> defaultValue(T defaultValue) { this.defaultValue = defaultValue; return this; } public TestCase<T> nonDefaultValue(T nonDefaultValue) { this.nonDefaultValue = nonDefaultValue; return this; } public TestCase<T> clientSetter(BiConsumer<ProtocolRestJsonClientBuilder, T> clientSetter) { this.clientSetter = clientSetter; return this; } public TestCase<T> requestSetter(BiConsumer<AwsRequestOverrideConfiguration.Builder, T> requestSetter) { this.requestSetter = requestSetter; return this; } public TestCase<T> pluginSetter(BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> pluginSetter) { this.pluginSetter = pluginSetter; return this; } public TestCase<T> pluginValidator(BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> pluginValidator) { this.pluginValidator = pluginValidator; return this; } public TestCase<T> clientConfigurationValidator(BiConsumer<SdkClientConfiguration, T> clientConfigurationValidator) { this.clientConfigurationValidator = clientConfigurationValidator; return this; } public TestCase<T> beforeTransmissionValidator(TriConsumer<Context.BeforeTransmission, ExecutionAttributes, T> beforeTransmissionValidator) { this.beforeTransmissionValidator = beforeTransmissionValidator; return this; } @Override public String toString() { return configName; } } private static SdkHttpClient succeedingHttpClient() { MockSyncHttpClient client = new MockSyncHttpClient(); client.stubNextResponse200(); return client; } private static URI removePathAndQueryString(URI uri) { String uriString = uri.toString(); return URI.create(uriString.substring(0, uriString.indexOf('/', "https://".length()))); } public interface TriConsumer<T, U, V> { void accept(T t, U u, V v); } private static class CustomAuthScheme implements AuthScheme<NoAuthAuthScheme.AnonymousIdentity> { private static final String SCHEME_ID = "foo"; private static final AuthScheme<NoAuthAuthScheme.AnonymousIdentity> DELEGATE = NoAuthAuthScheme.create(); @Override public String schemeId() { return SCHEME_ID; } @Override public IdentityProvider<NoAuthAuthScheme.AnonymousIdentity> identityProvider(IdentityProviders providers) { return DELEGATE.identityProvider(providers); } @Override public HttpSigner<NoAuthAuthScheme.AnonymousIdentity> signer() { return DELEGATE.signer(); } } private static class FlagSettingInterceptor implements ExecutionInterceptor { private static final ExecutionAttribute<Boolean> FLAG = new ExecutionAttribute<>("InterceptorAdded"); @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { executionAttributes.putAttribute(FLAG, true); } } }
2,871
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/CodegenServiceClientConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.mock; import java.net.URI; import java.util.Arrays; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.function.BiConsumer; import java.util.function.Function; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.awscore.AwsServiceClientConfiguration; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.client.config.ClientOption; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeProvider; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonServiceClientConfiguration; import software.amazon.awssdk.services.protocolrestjson.auth.scheme.ProtocolRestJsonAuthSchemeProvider; import software.amazon.awssdk.services.protocolrestjson.internal.ProtocolRestJsonServiceClientConfigurationBuilder; public class CodegenServiceClientConfigurationTest { private static final EndpointProvider MOCK_ENDPOINT_PROVIDER = mock(EndpointProvider.class); private static final IdentityProvider<AwsCredentialsIdentity> MOCK_IDENTITY_PROVIDER = mock(IdentityProvider.class); private static final ProtocolRestJsonAuthSchemeProvider MOCK_AUTH_SCHEME_PROVIDER = mock(ProtocolRestJsonAuthSchemeProvider.class); private static final ScheduledExecutorService MOCK_SCHEDULED_EXECUTOR_SERVICE = mock(ScheduledExecutorService.class); private static final Signer MOCK_SIGNER = mock(Signer.class); @ParameterizedTest @MethodSource("testCases") <T> void externalInternalTransforms_preserves_propertyValues(TestCase<T> testCase) { SdkClientConfiguration.Builder clientConfig = SdkClientConfiguration.builder(); ProtocolRestJsonServiceClientConfigurationBuilder builder = new ProtocolRestJsonServiceClientConfigurationBuilder(clientConfig); // Verify that initially the value is null for properties with direct mapping. if (testCase.hasDirectMapping) { assertThat(testCase.getter.apply(builder)).isNull(); } // Set the value testCase.setter.accept(builder, testCase.value); // Assert that we can retrieve the same value assertThat(testCase.getter.apply(builder)).isEqualTo(testCase.value); // Build the ServiceConfiguration instance ProtocolRestJsonServiceClientConfiguration config = builder.build(); // Assert that we can retrieve the same value assertThat(testCase.dataGetter.apply(config)).isEqualTo(testCase.value); // Build a new builder with the created client config ProtocolRestJsonServiceClientConfigurationBuilder anotherBuilder = new ProtocolRestJsonServiceClientConfigurationBuilder(clientConfig); // Assert that we can retrieve the same value if (testCase.hasDirectMapping) { assertThat(testCase.getter.apply(anotherBuilder)).isEqualTo(testCase.value); } } public static List<TestCase<?>> testCases() throws Exception { return Arrays.asList( TestCase.<Region>builder() .option(AwsClientOption.AWS_REGION) .value(Region.US_WEST_2) .setter(ProtocolRestJsonServiceClientConfiguration.Builder::region) .getter(ProtocolRestJsonServiceClientConfiguration.Builder::region) .dataGetter(AwsServiceClientConfiguration::region) .build(), TestCase.<URI>builder() .option(SdkClientOption.ENDPOINT) .value(new URI("http://localhost:8080")) .setter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointOverride) .getter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointOverride) .dataGetter(x -> x.endpointOverride().orElse(null)) .build(), TestCase.<EndpointProvider>builder() .option(SdkClientOption.ENDPOINT_PROVIDER) .value(MOCK_ENDPOINT_PROVIDER) .setter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointProvider) .getter(ProtocolRestJsonServiceClientConfiguration.Builder::endpointProvider) .dataGetter(x -> x.endpointProvider().orElse(null)) .build(), TestCase.<IdentityProvider<? extends AwsCredentialsIdentity>>builder() .option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER) .value(MOCK_IDENTITY_PROVIDER) .setter(ProtocolRestJsonServiceClientConfiguration.Builder::credentialsProvider) .getter(ProtocolRestJsonServiceClientConfiguration.Builder::credentialsProvider) .dataGetter(AwsServiceClientConfiguration::credentialsProvider) .build(), TestCase.<AuthSchemeProvider>builder() .option(SdkClientOption.AUTH_SCHEME_PROVIDER) .value(MOCK_AUTH_SCHEME_PROVIDER) .setter((b, p) -> b.authSchemeProvider((ProtocolRestJsonAuthSchemeProvider) p)) .getter(ProtocolRestJsonServiceClientConfiguration.Builder::authSchemeProvider) .dataGetter(ProtocolRestJsonServiceClientConfiguration::authSchemeProvider) .build(), // Override configuration gets tricky TestCase.<ScheduledExecutorService>builder() .option(SdkClientOption.SCHEDULED_EXECUTOR_SERVICE) .value(MOCK_SCHEDULED_EXECUTOR_SERVICE) .setter((b, p) -> b.overrideConfiguration( ClientOverrideConfiguration.builder() .scheduledExecutorService(p) .build())) .getter(b -> b.overrideConfiguration().scheduledExecutorService().orElse(null)) .dataGetter(d -> d.overrideConfiguration().scheduledExecutorService().orElse(null)) .withoutDirectMapping() .build(), TestCase.<Signer>builder() .option(SdkAdvancedClientOption.SIGNER) .value(MOCK_SIGNER) .setter((b, p) -> b.overrideConfiguration( ClientOverrideConfiguration.builder() .putAdvancedOption(SdkAdvancedClientOption.SIGNER, p) .build())) .getter(b -> b.overrideConfiguration().advancedOption(SdkAdvancedClientOption.SIGNER).orElse(null)) .dataGetter(d -> d.overrideConfiguration().advancedOption(SdkAdvancedClientOption.SIGNER).orElse(null)) .withoutDirectMapping() .build() ); } static class TestCase<T> { private final ClientOption<T> option; private final T value; private final BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> setter; private final Function<ProtocolRestJsonServiceClientConfiguration.Builder, T> getter; private Function<ProtocolRestJsonServiceClientConfiguration, T> dataGetter; private final boolean hasDirectMapping; public TestCase(Builder<T> builder) { this.option = builder.option; this.value = builder.value; this.setter = builder.setter; this.getter = builder.getter; this.dataGetter = builder.dataGetter; this.hasDirectMapping = builder.hasDirectMapping; } public static <T> Builder<T> builder() { return new Builder(); } static class Builder<T> { private ClientOption<T> option; private T value; private BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> setter; private Function<ProtocolRestJsonServiceClientConfiguration.Builder, T> getter; private Function<ProtocolRestJsonServiceClientConfiguration, T> dataGetter; private boolean hasDirectMapping = true; Builder<T> option(ClientOption<T> option) { this.option = option; return this; } Builder<T> value(T value) { this.value = value; return this; } Builder<T> setter(BiConsumer<ProtocolRestJsonServiceClientConfiguration.Builder, T> setter) { this.setter = setter; return this; } Builder<T> getter(Function<ProtocolRestJsonServiceClientConfiguration.Builder, T> getter) { this.getter = getter; return this; } Builder<T> dataGetter(Function<ProtocolRestJsonServiceClientConfiguration, T> dataGetter) { this.dataGetter = dataGetter; return this; } Builder<T> withoutDirectMapping() { this.hasDirectMapping = false; return this; } TestCase<T> build() { return new TestCase<>(this); } } } }
2,872
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/SyncClientMetricPublisherResolutionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.metrics; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Arrays; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder; import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil; @RunWith(MockitoJUnitRunner.class) public class SyncClientMetricPublisherResolutionTest { @Mock private SdkHttpClient mockHttpClient; private ProtocolRestJsonClient client; @After public void teardown() { if (client != null) { client.close(); } client = null; } @Test public void testApiCall_noPublishersSet_noException() throws IOException { client = clientWithPublishers(); client.allTypes(); } @Test public void testApiCall_publishersSetOnClient_clientPublishersInvoked() throws IOException { MetricPublisher publisher1 = mock(MetricPublisher.class); MetricPublisher publisher2 = mock(MetricPublisher.class); client = clientWithPublishers(publisher1, publisher2); try { client.allTypes(); } catch (Throwable t) { // ignored, call fails because our mock HTTP client isn't set up } finally { verify(publisher1).publish(any(MetricCollection.class)); verify(publisher2).publish(any(MetricCollection.class)); } } @Test public void testApiCall_publishersSetOnRequest_requestPublishersInvoked() throws IOException { MetricPublisher publisher1 = mock(MetricPublisher.class); MetricPublisher publisher2 = mock(MetricPublisher.class); client = clientWithPublishers(); try { client.allTypes(r -> r.overrideConfiguration(o -> o.addMetricPublisher(publisher1).addMetricPublisher(publisher2))); } catch (Throwable t) { // ignored, call fails because our mock HTTP client isn't set up } finally { verify(publisher1).publish(any(MetricCollection.class)); verify(publisher2).publish(any(MetricCollection.class)); } } @Test public void testApiCall_publishersSetOnClientAndRequest_requestPublishersInvoked() throws IOException { MetricPublisher clientPublisher1 = mock(MetricPublisher.class); MetricPublisher clientPublisher2 = mock(MetricPublisher.class); MetricPublisher requestPublisher1 = mock(MetricPublisher.class); MetricPublisher requestPublisher2 = mock(MetricPublisher.class); client = clientWithPublishers(clientPublisher1, clientPublisher2); try { client.allTypes(r -> r.overrideConfiguration(o -> o.addMetricPublisher(requestPublisher1).addMetricPublisher(requestPublisher2))); } catch (Throwable t) { // ignored, call fails because our mock HTTP client isn't set up } finally { verify(requestPublisher1).publish(any(MetricCollection.class)); verify(requestPublisher2).publish(any(MetricCollection.class)); verifyNoMoreInteractions(clientPublisher1); verifyNoMoreInteractions(clientPublisher2); } } private ProtocolRestJsonClient clientWithPublishers(MetricPublisher... metricPublishers) throws IOException { ProtocolRestJsonClientBuilder builder = ProtocolRestJsonClient.builder() .httpClient(mockHttpClient) .region(Region.US_WEST_2) .credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider()); AbortableInputStream content = AbortableInputStream.create(new ByteArrayInputStream("{}".getBytes())); SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(200) .content(content) .build(); HttpExecuteResponse mockResponse = mockExecuteResponse(httpResponse); ExecutableHttpRequest mockExecuteRequest = mock(ExecutableHttpRequest.class); when(mockExecuteRequest.call()).thenAnswer(invocation -> { try { Thread.sleep(100); } catch (InterruptedException ie) { ie.printStackTrace(); } return mockResponse; }); when(mockHttpClient.prepareRequest(any(HttpExecuteRequest.class))) .thenReturn(mockExecuteRequest); if (metricPublishers != null) { builder.overrideConfiguration(o -> o.metricPublishers(Arrays.asList(metricPublishers))); } return builder.build(); } private static HttpExecuteResponse mockExecuteResponse(SdkHttpFullResponse httpResponse) { HttpExecuteResponse mockResponse = mock(HttpExecuteResponse.class); when(mockResponse.httpResponse()).thenReturn(httpResponse); when(mockResponse.responseBody()).thenReturn(httpResponse.content()); return mockResponse; } }
2,873
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/CoreMetricsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.metrics; 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.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.time.Duration; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.internal.metrics.SdkErrorType; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.endpoints.ProtocolRestJsonEndpointParams; import software.amazon.awssdk.services.protocolrestjson.endpoints.ProtocolRestJsonEndpointProvider; import software.amazon.awssdk.services.protocolrestjson.model.EmptyModeledException; import software.amazon.awssdk.services.protocolrestjson.model.SimpleStruct; import software.amazon.awssdk.services.protocolrestjson.paginators.PaginatedOperationWithResultKeyIterable; import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil; @RunWith(MockitoJUnitRunner.class) public class CoreMetricsTest { private static final String SERVICE_ID = "AmazonProtocolRestJson"; private static final String REQUEST_ID = "req-id"; private static final String EXTENDED_REQUEST_ID = "extended-id"; private static final int MAX_RETRIES = 2; private static ProtocolRestJsonClient client; @Rule public ExpectedException thrown = ExpectedException.none(); @Mock private SdkHttpClient mockHttpClient; @Mock private MetricPublisher mockPublisher; @Mock private ProtocolRestJsonEndpointProvider mockEndpointProvider; @Before public void setup() throws IOException { client = ProtocolRestJsonClient.builder() .httpClient(mockHttpClient) .region(Region.US_WEST_2) .credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider()) .overrideConfiguration(c -> c.addMetricPublisher(mockPublisher).retryPolicy(b -> b.numRetries(MAX_RETRIES))) .endpointProvider(mockEndpointProvider) .build(); AbortableInputStream content = contentStream("{}"); SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(200) .putHeader("x-amz-request-id", REQUEST_ID) .putHeader("x-amz-id-2", EXTENDED_REQUEST_ID) .content(content) .build(); HttpExecuteResponse mockResponse = mockExecuteResponse(httpResponse); ExecutableHttpRequest mockExecuteRequest = mock(ExecutableHttpRequest.class); when(mockExecuteRequest.call()).thenAnswer(invocation -> { try { Thread.sleep(100); } catch (InterruptedException ie) { ie.printStackTrace(); } return mockResponse; }); when(mockHttpClient.prepareRequest(any(HttpExecuteRequest.class))) .thenReturn(mockExecuteRequest); when(mockEndpointProvider.resolveEndpoint(any(ProtocolRestJsonEndpointParams.class))).thenReturn( CompletableFuture.completedFuture(Endpoint.builder() .url(URI.create("https://protocolrestjson.amazonaws.com")) .build())); } @After public void teardown() { if (client != null) { client.close(); } client = null; } @Test public void testApiCall_noConfiguredPublisher_succeeds() { ProtocolRestJsonClient noPublisher = ProtocolRestJsonClient.builder() .region(Region.US_WEST_2) .credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider()) .httpClient(mockHttpClient) .build(); noPublisher.allTypes(); } @Test public void testApiCall_publisherOverriddenOnRequest_requestPublisherTakesPrecedence() { MetricPublisher requestMetricPublisher = mock(MetricPublisher.class); client.allTypes(r -> r.overrideConfiguration(o -> o.addMetricPublisher(requestMetricPublisher))); verify(requestMetricPublisher).publish(any(MetricCollection.class)); verifyNoMoreInteractions(mockPublisher); } @Test public void testPaginatingApiCall_publisherOverriddenOnRequest_requestPublisherTakesPrecedence() { MetricPublisher requestMetricPublisher = mock(MetricPublisher.class); PaginatedOperationWithResultKeyIterable iterable = client.paginatedOperationWithResultKeyPaginator( r -> r.overrideConfiguration(o -> o.addMetricPublisher(requestMetricPublisher))); List<SimpleStruct> resultingItems = iterable.items().stream().collect(Collectors.toList()); verify(requestMetricPublisher).publish(any(MetricCollection.class)); verifyNoMoreInteractions(mockPublisher); } @Test public void testApiCall_operationSuccessful_addsMetrics() { client.allTypes(); ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class); verify(mockPublisher).publish(collectionCaptor.capture()); MetricCollection capturedCollection = collectionCaptor.getValue(); assertThat(capturedCollection.name()).isEqualTo("ApiCall"); assertThat(capturedCollection.metricValues(CoreMetric.SERVICE_ID)) .containsExactly(SERVICE_ID); assertThat(capturedCollection.metricValues(CoreMetric.OPERATION_NAME)) .containsExactly("AllTypes"); assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_SUCCESSFUL)).containsExactly(true); assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_DURATION).get(0)) .isGreaterThan(Duration.ZERO); assertThat(capturedCollection.metricValues(CoreMetric.CREDENTIALS_FETCH_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(capturedCollection.metricValues(CoreMetric.MARSHALLING_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(capturedCollection.metricValues(CoreMetric.RETRY_COUNT)).containsExactly(0); assertThat(capturedCollection.metricValues(CoreMetric.SERVICE_ENDPOINT).get(0)).isEqualTo(URI.create( "https://protocolrestjson.amazonaws.com")); assertThat(capturedCollection.children()).hasSize(1); MetricCollection attemptCollection = capturedCollection.children().get(0); assertThat(attemptCollection.name()).isEqualTo("ApiCallAttempt"); assertThat(attemptCollection.metricValues(CoreMetric.BACKOFF_DELAY_DURATION)) .containsExactly(Duration.ZERO); assertThat(attemptCollection.metricValues(HttpMetric.HTTP_STATUS_CODE)) .containsExactly(200); assertThat(attemptCollection.metricValues(CoreMetric.SIGNING_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(attemptCollection.metricValues(CoreMetric.AWS_REQUEST_ID)) .containsExactly(REQUEST_ID); assertThat(attemptCollection.metricValues(CoreMetric.AWS_EXTENDED_REQUEST_ID)) .containsExactly(EXTENDED_REQUEST_ID); assertThat(attemptCollection.metricValues(CoreMetric.SERVICE_CALL_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ofMillis(100)); assertThat(attemptCollection.metricValues(CoreMetric.UNMARSHALLING_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); } @Test public void testApiCall_serviceReturnsError_errorInfoIncludedInMetrics() throws IOException { AbortableInputStream content = contentStream("{}"); SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(500) .putHeader("x-amz-request-id", REQUEST_ID) .putHeader("x-amz-id-2", EXTENDED_REQUEST_ID) .putHeader("X-Amzn-Errortype", "EmptyModeledException") .content(content) .build(); HttpExecuteResponse response = mockExecuteResponse(httpResponse); ExecutableHttpRequest mockExecuteRequest = mock(ExecutableHttpRequest.class); when(mockExecuteRequest.call()).thenReturn(response); when(mockHttpClient.prepareRequest(any(HttpExecuteRequest.class))) .thenReturn(mockExecuteRequest); thrown.expect(EmptyModeledException.class); try { client.allTypes(); } finally { ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class); verify(mockPublisher).publish(collectionCaptor.capture()); MetricCollection capturedCollection = collectionCaptor.getValue(); assertThat(capturedCollection.children()).hasSize(MAX_RETRIES + 1); assertThat(capturedCollection.metricValues(CoreMetric.RETRY_COUNT)).containsExactly(MAX_RETRIES); assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_SUCCESSFUL)).containsExactly(false); for (MetricCollection requestMetrics : capturedCollection.children()) { // A service exception is still a successful HTTP execution so // we should still have HTTP metrics as well. assertThat(requestMetrics.metricValues(HttpMetric.HTTP_STATUS_CODE)) .containsExactly(500); assertThat(requestMetrics.metricValues(CoreMetric.AWS_REQUEST_ID)) .containsExactly(REQUEST_ID); assertThat(requestMetrics.metricValues(CoreMetric.AWS_EXTENDED_REQUEST_ID)) .containsExactly(EXTENDED_REQUEST_ID); assertThat(requestMetrics.metricValues(CoreMetric.SERVICE_CALL_DURATION)).hasOnlyOneElementSatisfying(d -> { assertThat(d).isGreaterThanOrEqualTo(Duration.ZERO); }); assertThat(requestMetrics.metricValues(CoreMetric.UNMARSHALLING_DURATION)).hasOnlyOneElementSatisfying(d -> { assertThat(d).isGreaterThanOrEqualTo(Duration.ZERO); }); assertThat(requestMetrics.metricValues(CoreMetric.ERROR_TYPE)).containsExactly(SdkErrorType.SERVER_ERROR.toString()); } } } @Test public void testApiCall_httpClientThrowsNetworkError_errorTypeIncludedInMetrics() throws IOException { ExecutableHttpRequest mockExecuteRequest = mock(ExecutableHttpRequest.class); when(mockExecuteRequest.call()).thenThrow(new IOException("I/O error")); when(mockHttpClient.prepareRequest(any(HttpExecuteRequest.class))) .thenReturn(mockExecuteRequest); thrown.expect(SdkException.class); try { client.allTypes(); } finally { ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class); verify(mockPublisher).publish(collectionCaptor.capture()); MetricCollection capturedCollection = collectionCaptor.getValue(); assertThat(capturedCollection.children()).isNotEmpty(); for (MetricCollection requestMetrics : capturedCollection.children()) { assertThat(requestMetrics.metricValues(CoreMetric.ERROR_TYPE)).containsExactly(SdkErrorType.IO.toString()); } } } @Test public void testApiCall_endpointProviderAddsPathQueryFragment_notReportedInServiceEndpointMetric() { when(mockEndpointProvider.resolveEndpoint(any(ProtocolRestJsonEndpointParams.class))) .thenReturn(CompletableFuture.completedFuture(Endpoint.builder() .url(URI.create("https://protocolrestjson.amazonaws.com:8080/foo?bar#baz")) .build())); client.allTypes(); ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class); verify(mockPublisher).publish(collectionCaptor.capture()); MetricCollection capturedCollection = collectionCaptor.getValue(); URI expectedServiceEndpoint = URI.create("https://protocolrestjson.amazonaws.com:8080"); assertThat(capturedCollection.metricValues(CoreMetric.SERVICE_ENDPOINT)).containsExactly(expectedServiceEndpoint); } private static HttpExecuteResponse mockExecuteResponse(SdkHttpFullResponse httpResponse) { HttpExecuteResponse mockResponse = mock(HttpExecuteResponse.class); when(mockResponse.httpResponse()).thenReturn(httpResponse); when(mockResponse.responseBody()).thenReturn(httpResponse.content()); return mockResponse; } private static AbortableInputStream contentStream(String content) { ByteArrayInputStream baos = new ByteArrayInputStream(content.getBytes()); return AbortableInputStream.create(baos); } }
2,874
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/async/AsyncEventStreamingCoreMetricsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.metrics.async; import static org.mockito.Mockito.when; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.core.async.EmptyPublisher; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.model.EventStreamOperationRequest; import software.amazon.awssdk.services.protocolrestjson.model.EventStreamOperationResponseHandler; import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil; /** * Core metrics test for async streaming API */ @RunWith(MockitoJUnitRunner.class) public class AsyncEventStreamingCoreMetricsTest extends BaseAsyncCoreMetricsTest { @Rule public WireMockRule wireMock = new WireMockRule(0); @Mock private MetricPublisher mockPublisher; private ProtocolRestJsonAsyncClient client; @Before public void setup() { client = ProtocolRestJsonAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider()) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .overrideConfiguration(c -> c.addMetricPublisher(mockPublisher) .retryPolicy(b -> b.numRetries(MAX_RETRIES))) .build(); } @After public void teardown() { wireMock.resetAll(); if (client != null) { client.close(); } client = null; } @Override String operationName() { return "EventStreamOperation"; } @Override Supplier<CompletableFuture<?>> callable() { return () -> client.eventStreamOperation(EventStreamOperationRequest.builder().overrideConfiguration(b -> b.signer(new NoOpSigner())).build(), new EmptyPublisher<>(), EventStreamOperationResponseHandler.builder() .subscriber(b -> {}) .build()); } @Override MetricPublisher publisher() { return mockPublisher; } }
2,875
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/async/AsyncCoreMetricsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.metrics.async; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URI; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.model.PaginatedOperationWithResultKeyResponse; import software.amazon.awssdk.services.protocolrestjson.paginators.PaginatedOperationWithResultKeyPublisher; import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil; /** * Core metrics test for async non-streaming API */ @RunWith(MockitoJUnitRunner.class) public class AsyncCoreMetricsTest extends BaseAsyncCoreMetricsTest { @Mock private MetricPublisher mockPublisher; @Rule public WireMockRule wireMock = new WireMockRule(0); private ProtocolRestJsonAsyncClient client; @Before public void setup() throws IOException { client = ProtocolRestJsonAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider()) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .overrideConfiguration(c -> c.addMetricPublisher(mockPublisher).retryPolicy(b -> b.numRetries(MAX_RETRIES))) .build(); } @After public void teardown() { wireMock.resetAll(); if (client != null) { client.close(); } client = null; } @Override String operationName() { return "AllTypes"; } @Override Supplier<CompletableFuture<?>> callable() { return () -> client.allTypes(); } @Override MetricPublisher publisher() { return mockPublisher; } @Test public void apiCall_noConfiguredPublisher_succeeds() { stubSuccessfulResponse(); ProtocolRestJsonAsyncClient noPublisher = ProtocolRestJsonAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider()) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); noPublisher.allTypes().join(); } @Test public void apiCall_publisherOverriddenOnRequest_requestPublisherTakesPrecedence() { stubSuccessfulResponse(); MetricPublisher requestMetricPublisher = mock(MetricPublisher.class); client.allTypes(r -> r.overrideConfiguration(o -> o.addMetricPublisher(requestMetricPublisher))).join(); verify(requestMetricPublisher).publish(any(MetricCollection.class)); verifyNoMoreInteractions(mockPublisher); } @Test public void testPaginatingApiCall_publisherOverriddenOnRequest_requestPublisherTakesPrecedence() throws Exception { stubSuccessfulResponse(); MetricPublisher requestMetricPublisher = mock(MetricPublisher.class); PaginatedOperationWithResultKeyPublisher paginatedPublisher = client.paginatedOperationWithResultKeyPaginator( r -> r.overrideConfiguration(o -> o.addMetricPublisher(requestMetricPublisher))); CompletableFuture<Void> future = paginatedPublisher.subscribe(PaginatedOperationWithResultKeyResponse::items); future.get(); verify(requestMetricPublisher).publish(any(MetricCollection.class)); verifyNoMoreInteractions(mockPublisher); } }
2,876
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/async/AsyncClientMetricPublisherResolutionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.metrics.async; import static org.hamcrest.Matchers.instanceOf; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.concurrent.CompletableFuture; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClientBuilder; import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonException; import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil; @RunWith(MockitoJUnitRunner.class) public class AsyncClientMetricPublisherResolutionTest { @Rule public WireMockRule wireMock = new WireMockRule(0); @Rule public ExpectedException thrown = ExpectedException.none(); private ProtocolRestJsonAsyncClient client; @After public void teardown() { wireMock.resetAll(); if (client != null) { client.close(); } client = null; } @Test public void testApiCall_noPublishersSet_noNpe() { client = clientWithPublishers(); // This is thrown because all the requests to our wiremock are // nonsense, it's just important that we don't get NPE because we // don't have publishers set thrown.expectCause(instanceOf(ProtocolRestJsonException.class)); client.allTypes().join(); } @Test public void testApiCall_publishersSetOnClient_clientPublishersInvoked() throws IOException { MetricPublisher publisher1 = mock(MetricPublisher.class); MetricPublisher publisher2 = mock(MetricPublisher.class); client = clientWithPublishers(publisher1, publisher2); try { client.allTypes().join(); } catch (Throwable t) { // ignored, call fails because our mock HTTP client isn't set up } finally { verify(publisher1).publish(any(MetricCollection.class)); verify(publisher2).publish(any(MetricCollection.class)); } } @Test public void testApiCall_publishersSetOnRequest_requestPublishersInvoked() throws IOException { MetricPublisher publisher1 = mock(MetricPublisher.class); MetricPublisher publisher2 = mock(MetricPublisher.class); client = clientWithPublishers(); try { client.allTypes(r -> r.overrideConfiguration(o -> o.addMetricPublisher(publisher1).addMetricPublisher(publisher2))) .join(); } catch (Throwable t) { // ignored, call fails because our mock HTTP client isn't set up } finally { verify(publisher1).publish(any(MetricCollection.class)); verify(publisher2).publish(any(MetricCollection.class)); } } @Test public void testApiCall_publishersSetOnClientAndRequest_requestPublishersInvoked() throws IOException { MetricPublisher clientPublisher1 = mock(MetricPublisher.class); MetricPublisher clientPublisher2 = mock(MetricPublisher.class); MetricPublisher requestPublisher1 = mock(MetricPublisher.class); MetricPublisher requestPublisher2 = mock(MetricPublisher.class); client = clientWithPublishers(clientPublisher1, clientPublisher2); try { client.allTypes(r -> r.overrideConfiguration(o -> o.addMetricPublisher(requestPublisher1).addMetricPublisher(requestPublisher2))) .join(); } catch (Throwable t) { // ignored, call fails because our mock HTTP client isn't set up } finally { verify(requestPublisher1).publish(any(MetricCollection.class)); verify(requestPublisher2).publish(any(MetricCollection.class)); verifyNoMoreInteractions(clientPublisher1); verifyNoMoreInteractions(clientPublisher2); } } private ProtocolRestJsonAsyncClient clientWithPublishers(MetricPublisher... metricPublishers) { ProtocolRestJsonAsyncClientBuilder builder = ProtocolRestJsonAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider()) .endpointOverride(URI.create("http://localhost:" + wireMock.port())); if (metricPublishers != null) { builder.overrideConfiguration(o -> o.metricPublishers(Arrays.asList(metricPublishers))); } return builder.build(); } }
2,877
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/async/AsyncStreamingCoreMetricsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.metrics.async; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URI; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationRequest; import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil; /** * Core metrics test for async streaming API */ @RunWith(MockitoJUnitRunner.class) public class AsyncStreamingCoreMetricsTest extends BaseAsyncCoreMetricsTest { @Mock private MetricPublisher mockPublisher; @Rule public WireMockRule wireMock = new WireMockRule(0); private ProtocolRestJsonAsyncClient client; @Before public void setup() throws IOException { client = ProtocolRestJsonAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider()) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .overrideConfiguration(c -> c.addMetricPublisher(mockPublisher).retryPolicy(b -> b.numRetries(MAX_RETRIES))) .build(); } @After public void teardown() { wireMock.resetAll(); if (client != null) { client.close(); } client = null; } @Override String operationName() { return "StreamingInputOperation"; } @Override Supplier<CompletableFuture<?>> callable() { return () -> client.streamingInputOperation(StreamingInputOperationRequest.builder().build(), AsyncRequestBody.fromBytes("helloworld".getBytes())); } @Override MetricPublisher publisher() { return mockPublisher; } }
2,878
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/async/BaseAsyncCoreMetricsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.metrics.async; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.verify; import com.github.tomakehurst.wiremock.http.Fault; import com.github.tomakehurst.wiremock.stubbing.Scenario; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.core.internal.metrics.SdkErrorType; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.services.protocolrestjson.model.EmptyModeledException; @RunWith(MockitoJUnitRunner.class) public abstract class BaseAsyncCoreMetricsTest { private static final String SERVICE_ID = "AmazonProtocolRestJson"; private static final String REQUEST_ID = "req-id"; private static final String EXTENDED_REQUEST_ID = "extended-id"; static final int MAX_RETRIES = 2; public static final Duration FIXED_DELAY = Duration.ofMillis(500); @Test public void apiCall_operationSuccessful_addsMetrics() { stubSuccessfulResponse(); callable().get().join(); addDelayIfNeeded(); ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class); verify(publisher()).publish(collectionCaptor.capture()); MetricCollection capturedCollection = collectionCaptor.getValue(); verifySuccessfulApiCallCollection(capturedCollection); assertThat(capturedCollection.children()).hasSize(1); MetricCollection attemptCollection = capturedCollection.children().get(0); assertThat(attemptCollection.name()).isEqualTo("ApiCallAttempt"); verifySuccessfulApiCallAttemptCollection(attemptCollection); assertThat(attemptCollection.metricValues(CoreMetric.SERVICE_CALL_DURATION).get(0)) .isGreaterThanOrEqualTo(FIXED_DELAY); } @Test public void apiCall_allRetryAttemptsFailedOf500() { stubErrorResponse(); assertThatThrownBy(() -> callable().get().join()).hasCauseInstanceOf(EmptyModeledException.class); addDelayIfNeeded(); ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class); verify(publisher()).publish(collectionCaptor.capture()); MetricCollection capturedCollection = collectionCaptor.getValue(); verifyFailedApiCallCollection(capturedCollection); assertThat(capturedCollection.children()).hasSize(MAX_RETRIES + 1); capturedCollection.children().forEach(this::verifyFailedApiCallAttemptCollection); } @Test public void apiCall_allRetryAttemptsFailedOfNetworkError() { stubNetworkError(); assertThatThrownBy(() -> callable().get().join()).hasCauseInstanceOf(SdkClientException.class); addDelayIfNeeded(); ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class); verify(publisher()).publish(collectionCaptor.capture()); MetricCollection capturedCollection = collectionCaptor.getValue(); verifyFailedApiCallCollection(capturedCollection); assertThat(capturedCollection.children()).hasSize(MAX_RETRIES + 1); capturedCollection.children().forEach(requestMetrics -> { assertThat(requestMetrics.metricValues(HttpMetric.HTTP_STATUS_CODE)) .isEmpty(); assertThat(requestMetrics.metricValues(CoreMetric.AWS_REQUEST_ID)) .isEmpty(); assertThat(requestMetrics.metricValues(CoreMetric.AWS_EXTENDED_REQUEST_ID)) .isEmpty(); assertThat(requestMetrics.metricValues(CoreMetric.SERVICE_CALL_DURATION).get(0)) .isGreaterThanOrEqualTo(FIXED_DELAY); assertThat(requestMetrics.metricValues(CoreMetric.ERROR_TYPE)).containsExactly(SdkErrorType.IO.toString()); }); } @Test public void apiCall_firstAttemptFailedRetrySucceeded() { stubSuccessfulRetry(); callable().get().join(); addDelayIfNeeded(); ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class); verify(publisher()).publish(collectionCaptor.capture()); MetricCollection capturedCollection = collectionCaptor.getValue(); verifyApiCallCollection(capturedCollection); assertThat(capturedCollection.metricValues(CoreMetric.RETRY_COUNT)).containsExactly(1); assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_SUCCESSFUL)).containsExactly(true); assertThat(capturedCollection.children()).hasSize(2); MetricCollection failedAttempt = capturedCollection.children().get(0); verifyFailedApiCallAttemptCollection(failedAttempt); MetricCollection successfulAttempt = capturedCollection.children().get(1); verifySuccessfulApiCallAttemptCollection(successfulAttempt); } /** * Adds delay after calling CompletableFuture.join to wait for publisher to get metrics. */ void addDelayIfNeeded() { try { Thread.sleep(1000); } catch (InterruptedException ie) { ie.printStackTrace(); } } abstract String operationName(); abstract Supplier<CompletableFuture<?>> callable(); abstract MetricPublisher publisher(); private void verifyFailedApiCallAttemptCollection(MetricCollection requestMetrics) { assertThat(requestMetrics.metricValues(HttpMetric.HTTP_STATUS_CODE)) .containsExactly(500); assertThat(requestMetrics.metricValues(CoreMetric.AWS_REQUEST_ID)) .containsExactly(REQUEST_ID); assertThat(requestMetrics.metricValues(CoreMetric.AWS_EXTENDED_REQUEST_ID)) .containsExactly(EXTENDED_REQUEST_ID); assertThat(requestMetrics.metricValues(CoreMetric.BACKOFF_DELAY_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(requestMetrics.metricValues(CoreMetric.SERVICE_CALL_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(requestMetrics.metricValues(CoreMetric.ERROR_TYPE)).containsExactly(SdkErrorType.SERVER_ERROR.toString()); } private void verifySuccessfulApiCallAttemptCollection(MetricCollection attemptCollection) { assertThat(attemptCollection.metricValues(HttpMetric.HTTP_STATUS_CODE)) .containsExactly(200); assertThat(attemptCollection.metricValues(CoreMetric.AWS_REQUEST_ID)) .containsExactly(REQUEST_ID); assertThat(attemptCollection.metricValues(CoreMetric.AWS_EXTENDED_REQUEST_ID)) .containsExactly(EXTENDED_REQUEST_ID); assertThat(attemptCollection.metricValues(CoreMetric.BACKOFF_DELAY_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(attemptCollection.metricValues(CoreMetric.SIGNING_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); } private void verifyFailedApiCallCollection(MetricCollection capturedCollection) { verifyApiCallCollection(capturedCollection); assertThat(capturedCollection.metricValues(CoreMetric.RETRY_COUNT)).containsExactly(MAX_RETRIES); assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_SUCCESSFUL)).containsExactly(false); } private void verifySuccessfulApiCallCollection(MetricCollection capturedCollection) { verifyApiCallCollection(capturedCollection); assertThat(capturedCollection.metricValues(CoreMetric.RETRY_COUNT)).containsExactly(0); assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_SUCCESSFUL)).containsExactly(true); } private void verifyApiCallCollection(MetricCollection capturedCollection) { assertThat(capturedCollection.name()).isEqualTo("ApiCall"); assertThat(capturedCollection.metricValues(CoreMetric.SERVICE_ID)) .containsExactly(SERVICE_ID); assertThat(capturedCollection.metricValues(CoreMetric.OPERATION_NAME)) .containsExactly(operationName()); assertThat(capturedCollection.metricValues(CoreMetric.CREDENTIALS_FETCH_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(capturedCollection.metricValues(CoreMetric.MARSHALLING_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_DURATION).get(0)) .isGreaterThan(FIXED_DELAY); assertThat(capturedCollection.metricValues(CoreMetric.SERVICE_ENDPOINT).get(0)).toString() .startsWith("http://localhost"); } void stubSuccessfulResponse() { stubFor(post(anyUrl()) .willReturn(aResponse().withStatus(200) .withHeader("x-amz-request-id", REQUEST_ID) .withFixedDelay((int) FIXED_DELAY.toMillis()) .withHeader("x-amz-id-2", EXTENDED_REQUEST_ID) .withBody("{}"))); } void stubErrorResponse() { stubFor(post(anyUrl()) .willReturn(aResponse().withStatus(500) .withHeader("x-amz-request-id", REQUEST_ID) .withHeader("x-amz-id-2", EXTENDED_REQUEST_ID) .withFixedDelay((int) FIXED_DELAY.toMillis()) .withHeader("X-Amzn-Errortype", "EmptyModeledException") .withBody("{}"))); } void stubNetworkError() { stubFor(post(anyUrl()) .willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER) .withFixedDelay((int) FIXED_DELAY.toMillis()) )); } void stubSuccessfulRetry() { stubFor(post(anyUrl()) .inScenario("retry at 500") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withHeader("x-amz-request-id", REQUEST_ID) .withHeader("x-amz-id-2", EXTENDED_REQUEST_ID) .withFixedDelay((int) FIXED_DELAY.toMillis()) .withHeader("X-Amzn-Errortype", "EmptyModeledException") .withStatus(500))); stubFor(post(anyUrl()) .inScenario("retry at 500") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-request-id", REQUEST_ID) .withHeader("x-amz-id-2", EXTENDED_REQUEST_ID) .withFixedDelay((int) FIXED_DELAY.toMillis()) .withBody("{}"))); } }
2,879
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/customsdkshape/CustomSdkShapeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.customsdkshape; 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.notMatching; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient; @WireMockTest public class CustomSdkShapeTest { private ProtocolRestXmlClient xmlClient; @Mock private SdkHttpClient mockHttpClient; @BeforeEach public void setUp(WireMockRuntimeInfo wmRuntimeInfo) { xmlClient = ProtocolRestXmlClient.builder() .region(Region.US_WEST_2) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .httpClient(mockHttpClient) .endpointOverride(URI.create("http://localhost:" + wmRuntimeInfo.getHttpPort())) .build(); } @Test public void requestPayloadDoesNotContainInjectedCustomShape() { stubFor(any(urlMatching(".*")) .willReturn(aResponse().withStatus(200).withBody("<xml></xml>"))); xmlClient.allTypes(c -> c.sdkPartType("DEFAULT").build()); xmlClient.allTypes(c -> c.sdkPartType("LAST").build()); verify(anyRequestedFor(anyUrl()).withRequestBody(notMatching("^.*SdkPartType.*$"))); } }
2,880
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/retry/AsyncRetryFailureTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.retry; import java.net.URI; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; public class AsyncRetryFailureTest extends RetryFailureTestSuite<MockAsyncHttpClient> { private final ProtocolRestJsonAsyncClient client; public AsyncRetryFailureTest() { super(new MockAsyncHttpClient()); client = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost")) .httpClient(mockHttpClient) .build(); } @Override protected void callAllTypesOperation() { client.allTypes().join(); } }
2,881
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/retry/SyncClientRetryModeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.retry; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse; public class SyncClientRetryModeTest extends ClientRetryModeTestSuite<ProtocolRestJsonClient, ProtocolRestJsonClientBuilder> { @Override protected ProtocolRestJsonClientBuilder newClientBuilder() { return ProtocolRestJsonClient.builder(); } @Override protected AllTypesResponse callAllTypes(ProtocolRestJsonClient client) { return client.allTypes(); } }
2,882
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/retry/RetryFailureTestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.retry; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.concurrent.CompletionException; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.testutils.service.http.MockHttpClient; /** * A set of tests that verify the behavior of the SDK when retries are exhausted. */ public abstract class RetryFailureTestSuite<T extends MockHttpClient> { protected final T mockHttpClient; protected RetryFailureTestSuite(T mockHttpClient) { this.mockHttpClient = mockHttpClient; } @BeforeEach public void setupClient() { mockHttpClient.reset(); } protected abstract void callAllTypesOperation(); @Test public void clientSideErrorsIncludeSuppressedExceptions() { mockHttpClient.stubResponses(retryableFailure(), retryableFailure(), nonRetryableFailure()); try { callAllTypesOperation(); } catch (Throwable e) { if (e instanceof CompletionException) { e = e.getCause(); } e.printStackTrace(); assertThat(e.getSuppressed()).hasSize(2) .allSatisfy(t -> assertThat(t.getMessage()).contains("500")); } } private HttpExecuteResponse retryableFailure() { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(500) .putHeader("content-length", "0") .build()) .build(); } private HttpExecuteResponse nonRetryableFailure() { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(400) .putHeader("content-length", "0") .build()) .build(); } }
2,883
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/retry/AsyncClientRetryModeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.retry; import java.util.concurrent.CompletionException; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClientBuilder; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse; public class AsyncClientRetryModeTest extends ClientRetryModeTestSuite<ProtocolRestJsonAsyncClient, ProtocolRestJsonAsyncClientBuilder> { @Override protected ProtocolRestJsonAsyncClientBuilder newClientBuilder() { return ProtocolRestJsonAsyncClient.builder(); } @Override protected AllTypesResponse callAllTypes(ProtocolRestJsonAsyncClient client) { try { return client.allTypes().join(); } catch (CompletionException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw e; } } }
2,884
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/retry/AsyncRetryHeaderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.retry; import java.net.URI; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; public class AsyncRetryHeaderTest extends RetryHeaderTestSuite<MockAsyncHttpClient> { private final ProtocolRestJsonAsyncClient client; public AsyncRetryHeaderTest() { super(new MockAsyncHttpClient()); client = ProtocolRestJsonAsyncClient.builder() .overrideConfiguration(c -> c.retryPolicy(RetryMode.STANDARD)) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost")) .httpClient(mockHttpClient) .build(); } @Override protected void callAllTypesOperation() { client.allTypes().join(); } }
2,885
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/retry/SyncRetryFailureTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.retry; import java.net.URI; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; public class SyncRetryFailureTest extends RetryFailureTestSuite<MockSyncHttpClient> { private final ProtocolRestJsonClient client; public SyncRetryFailureTest() { super(new MockSyncHttpClient()); client = ProtocolRestJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost")) .httpClient(mockHttpClient) .build(); } @Override protected void callAllTypesOperation() { client.allTypes(); } }
2,886
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/retry/SyncRetryHeaderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.retry; import java.net.URI; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; public class SyncRetryHeaderTest extends RetryHeaderTestSuite<MockSyncHttpClient> { private final ProtocolRestJsonClient client; public SyncRetryHeaderTest() { super(new MockSyncHttpClient()); client = ProtocolRestJsonClient.builder() .overrideConfiguration(c -> c.retryPolicy(RetryMode.STANDARD)) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost")) .httpClient(mockHttpClient) .build(); } @Override protected void callAllTypesOperation() { client.allTypes(); } }
2,887
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/retry/RetryHeaderTestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.retry; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.testutils.service.http.MockHttpClient; /** * A set of tests that verify the behavior of retry-related headers (amz-sdk-invocation-id and amz-sdk-request). */ public abstract class RetryHeaderTestSuite<T extends MockHttpClient> { protected final T mockHttpClient; protected RetryHeaderTestSuite(T mockHttpClient) { this.mockHttpClient = mockHttpClient; } @BeforeEach public void setupClient() { mockHttpClient.reset(); } protected abstract void callAllTypesOperation(); @Test public void invocationIdSharedBetweenRetries() { mockHttpClient.stubResponses(retryableFailure(), retryableFailure(), success()); callAllTypesOperation(); List<SdkHttpRequest> requests = mockHttpClient.getRequests(); assertThat(requests).hasSize(3); String firstInvocationId = invocationId(requests.get(0)); assertThat(invocationId(requests.get(1))).isEqualTo(firstInvocationId); assertThat(invocationId(requests.get(2))).isEqualTo(firstInvocationId); } @Test public void invocationIdDifferentBetweenApiCalls() { mockHttpClient.stubResponses(success()); callAllTypesOperation(); callAllTypesOperation(); List<SdkHttpRequest> requests = mockHttpClient.getRequests(); assertThat(requests).hasSize(2); String firstInvocationId = invocationId(requests.get(0)); assertThat(invocationId(requests.get(1))).isNotEqualTo(firstInvocationId); } @Test public void retryAttemptAndMaxAreCorrect() { mockHttpClient.stubResponses(retryableFailure(), success()); callAllTypesOperation(); List<SdkHttpRequest> requests = mockHttpClient.getRequests(); assertThat(requests).hasSize(2); assertThat(retryComponent(requests.get(0), "attempt")).isEqualTo("1"); assertThat(retryComponent(requests.get(1), "attempt")).isEqualTo("2"); assertThat(retryComponent(requests.get(0), "max")).isEqualTo("3"); assertThat(retryComponent(requests.get(1), "max")).isEqualTo("3"); } private String invocationId(SdkHttpRequest request) { return request.firstMatchingHeader("amz-sdk-invocation-id") .orElseThrow(() -> new AssertionError("Expected aws-sdk-invocation-id in " + request)); } private String retryComponent(SdkHttpRequest request, String componentName) { return retryComponent(request.firstMatchingHeader("amz-sdk-request") .orElseThrow(() -> new AssertionError("Expected amz-sdk-request in " + request)), componentName); } private String retryComponent(String amzSdkRequestHeader, String componentName) { return Stream.of(amzSdkRequestHeader.split(";")) .map(h -> h.split("=")) .filter(h -> h[0].trim().equals(componentName)) .map(h -> h[1].trim()) .findAny() .orElseThrow(() -> new AssertionError("Expected " + componentName + " in " + amzSdkRequestHeader)); } private HttpExecuteResponse retryableFailure() { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(500) .putHeader("content-length", "0") .build()) .build(); } private HttpExecuteResponse success() { return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(200) .putHeader("content-length", "0") .build()) .build(); } }
2,888
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/retry/ClientRetryModeTestSuite.java
/* * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.retry; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; 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.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; 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.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse; import software.amazon.awssdk.utils.StringInputStream; public abstract class ClientRetryModeTestSuite<ClientT, BuilderT extends AwsClientBuilder<BuilderT, ClientT>> { @Rule public WireMockRule wireMock = new WireMockRule(0); @Test public void legacyRetryModeIsFourAttempts() { stubThrottlingResponse(); ClientT client = clientBuilder().overrideConfiguration(o -> o.retryPolicy(RetryMode.LEGACY)).build(); assertThatThrownBy(() -> callAllTypes(client)).isInstanceOf(SdkException.class); verifyRequestCount(4); } @Test public void standardRetryModeIsThreeAttempts() { stubThrottlingResponse(); ClientT client = clientBuilder().overrideConfiguration(o -> o.retryPolicy(RetryMode.STANDARD)).build(); assertThatThrownBy(() -> callAllTypes(client)).isInstanceOf(SdkException.class); verifyRequestCount(3); } @Test public void retryModeCanBeSetByProfileFile() { ProfileFile profileFile = ProfileFile.builder() .content(new StringInputStream("[profile foo]\n" + "retry_mode = standard")) .type(ProfileFile.Type.CONFIGURATION) .build(); stubThrottlingResponse(); ClientT client = clientBuilder().overrideConfiguration(o -> o.defaultProfileFile(profileFile) .defaultProfileName("foo")).build(); assertThatThrownBy(() -> callAllTypes(client)).isInstanceOf(SdkException.class); verifyRequestCount(3); } @Test public void legacyRetryModeExcludesThrottlingExceptions() throws InterruptedException { stubThrottlingResponse(); ExecutorService executor = Executors.newFixedThreadPool(51); ClientT client = clientBuilder().overrideConfiguration(o -> o.retryPolicy(RetryMode.LEGACY)).build(); for (int i = 0; i < 51; ++i) { executor.execute(() -> assertThatThrownBy(() -> callAllTypes(client)).isInstanceOf(SdkException.class)); } executor.shutdown(); assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue(); // 51 requests * 4 attempts = 204 requests verifyRequestCount(204); } @Test public void standardRetryModeIncludesThrottlingExceptions() throws InterruptedException { stubThrottlingResponse(); ExecutorService executor = Executors.newFixedThreadPool(51); ClientT client = clientBuilder().overrideConfiguration(o -> o.retryPolicy(RetryMode.STANDARD)).build(); for (int i = 0; i < 51; ++i) { executor.execute(() -> assertThatThrownBy(() -> callAllTypes(client)).isInstanceOf(SdkException.class)); } executor.shutdown(); assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue(); // Would receive 153 without throttling (51 requests * 3 attempts = 153 requests) verifyRequestCount(151); } private BuilderT clientBuilder() { return newClientBuilder().credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())); } protected abstract BuilderT newClientBuilder(); protected abstract AllTypesResponse callAllTypes(ClientT client); private void verifyRequestCount(int count) { verify(count, anyRequestedFor(anyUrl())); } private void stubThrottlingResponse() { stubFor(post(anyUrl()) .willReturn(aResponse().withStatus(429))); } }
2,889
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/bearerauth/ClientBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.bearerauth; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.mockito.Mockito.mock; import java.lang.reflect.Method; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.auth.token.credentials.aws.DefaultAwsTokenProvider; import software.amazon.awssdk.auth.token.signer.aws.BearerTokenSigner; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.client.builder.SdkDefaultClientBuilder; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.TokenIdentity; import software.amazon.awssdk.regions.Region; public class ClientBuilderTest { @Test public void syncClient_includesDefaultProvider_includesDefaultSigner() { DefaultBearerauthClientBuilder builder = new DefaultBearerauthClientBuilder(); SdkClientConfiguration config = getSyncConfig(builder); assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER)) .isInstanceOf(DefaultAwsTokenProvider.class); assertThat(config.option(SdkAdvancedClientOption.TOKEN_SIGNER)) .isInstanceOf(BearerTokenSigner.class); } @Test public void syncClient_customTokenProviderSet_presentInFinalConfig() { DefaultBearerauthClientBuilder builder = new DefaultBearerauthClientBuilder(); SdkTokenProvider mockProvider = mock(SdkTokenProvider.class); builder.tokenProvider(mockProvider); SdkClientConfiguration config = getSyncConfig(builder); assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER)) .isSameAs(mockProvider); } @Test public void syncClient_customTokenIdentityProviderSet_presentInFinalConfig() { DefaultBearerauthClientBuilder builder = new DefaultBearerauthClientBuilder(); IdentityProvider<TokenIdentity> mockProvider = mock(IdentityProvider.class); builder.tokenProvider(mockProvider); SdkClientConfiguration config = getSyncConfig(builder); assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER)) .isSameAs(mockProvider); } @Test public void syncClient_customSignerSet_presentInFinalConfig() { DefaultBearerauthClientBuilder builder = new DefaultBearerauthClientBuilder(); Signer mockSigner = mock(Signer.class); builder.overrideConfiguration(o -> o.putAdvancedOption(SdkAdvancedClientOption.TOKEN_SIGNER, mockSigner)); SdkClientConfiguration config = getSyncConfig(builder); assertThat(config.option(SdkAdvancedClientOption.TOKEN_SIGNER)) .isSameAs(mockSigner); } @Test public void asyncClient_includesDefaultProvider_includesDefaultSigner() { DefaultBearerauthAsyncClientBuilder builder = new DefaultBearerauthAsyncClientBuilder(); SdkClientConfiguration config = getAsyncConfig(builder); assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER)) .isInstanceOf(DefaultAwsTokenProvider.class); assertThat(config.option(SdkAdvancedClientOption.TOKEN_SIGNER)) .isInstanceOf(BearerTokenSigner.class); } @Test public void asyncClient_customTokenProviderSet_presentInFinalConfig() { DefaultBearerauthAsyncClientBuilder builder = new DefaultBearerauthAsyncClientBuilder(); SdkTokenProvider mockProvider = mock(SdkTokenProvider.class); builder.tokenProvider(mockProvider); SdkClientConfiguration config = getAsyncConfig(builder); assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER)) .isSameAs(mockProvider); } @Test public void asyncClient_customTokenIdentityProviderSet_presentInFinalConfig() { DefaultBearerauthAsyncClientBuilder builder = new DefaultBearerauthAsyncClientBuilder(); IdentityProvider<TokenIdentity> mockProvider = mock(IdentityProvider.class); builder.tokenProvider(mockProvider); SdkClientConfiguration config = getAsyncConfig(builder); assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER)) .isSameAs(mockProvider); } @Test public void asyncClient_customSignerSet_presentInFinalConfig() { DefaultBearerauthAsyncClientBuilder builder = new DefaultBearerauthAsyncClientBuilder(); Signer mockSigner = mock(Signer.class); builder.overrideConfiguration(o -> o.putAdvancedOption(SdkAdvancedClientOption.TOKEN_SIGNER, mockSigner)); SdkClientConfiguration config = getAsyncConfig(builder); assertThat(config.option(SdkAdvancedClientOption.TOKEN_SIGNER)) .isSameAs(mockSigner); } @Test public void syncClient_buildWithDefaults_validationsSucceed() { DefaultBearerauthClientBuilder builder = new DefaultBearerauthClientBuilder(); builder.region(Region.US_WEST_2).credentialsProvider(AnonymousCredentialsProvider.create()); assertThatNoException().isThrownBy(builder::build); } @Test public void asyncClient_buildWithDefaults_validationsSucceed() { DefaultBearerauthAsyncClientBuilder builder = new DefaultBearerauthAsyncClientBuilder(); builder.region(Region.US_WEST_2).credentialsProvider(AnonymousCredentialsProvider.create()); assertThatNoException().isThrownBy(builder::build); } // syncClientConfiguration() is a protected method, and the concrete builder classes are final private static SdkClientConfiguration getSyncConfig(DefaultBearerauthClientBuilder builder) { try { Method syncClientConfiguration = SdkDefaultClientBuilder.class.getDeclaredMethod("syncClientConfiguration"); syncClientConfiguration.setAccessible(true); return (SdkClientConfiguration) syncClientConfiguration.invoke(builder); } catch (Exception e) { throw new RuntimeException(e); } } // syncClientConfiguration() is a protected method, and the concrete builder classes are final private static SdkClientConfiguration getAsyncConfig(DefaultBearerauthAsyncClientBuilder builder) { try { Method syncClientConfiguration = SdkDefaultClientBuilder.class.getDeclaredMethod("asyncClientConfiguration"); syncClientConfiguration.setAccessible(true); return (SdkClientConfiguration) syncClientConfiguration.invoke(builder); } catch (Exception e) { throw new RuntimeException(e); } } }
2,890
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/endpointproviders/EndpointInterceptorTests.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.endpointproviders; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.concurrent.CompletableFuture; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest; import software.amazon.awssdk.http.auth.spi.signer.BaseSignRequest; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClient; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClientBuilder; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClientBuilder; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointProvider; import software.amazon.awssdk.utils.CompletableFutureUtils; public class EndpointInterceptorTests { @Test public void sync_hostPrefixInjectDisabled_hostPrefixNotAdded() { CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersClient client = syncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor) .putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true)) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {})) .hasMessageContaining("stop"); Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT); assertThat(endpoint.url().getHost()).isEqualTo("restjson.us-west-2.amazonaws.com"); } @Test public void async_hostPrefixInjectDisabled_hostPrefixNotAdded() { CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor) .putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true)) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join()) .hasMessageContaining("stop"); Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT); assertThat(endpoint.url().getHost()).isEqualTo("restjson.us-west-2.amazonaws.com"); } @Test public void sync_clientContextParamsSetOnBuilder_includedInExecutionAttributes() { CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersClient client = syncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)) .build(); assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> { })).hasMessageContaining("stop"); Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT); assertThat(endpoint).isNotNull(); } @Test public void async_clientContextParamsSetOnBuilder_includedInExecutionAttributes() { CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)) .build(); assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> { }).join()).hasMessageContaining("stop"); Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT); assertThat(endpoint).isNotNull(); } @Test public void sync_endpointProviderReturnsHeaders_includedInHttpRequest() { RestJsonEndpointProvidersEndpointProvider defaultProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersClient client = syncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)) .endpointProvider(r -> defaultProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putHeader("TestHeader", "TestValue") .build())) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {})) .hasMessageContaining("stop"); assertThat(interceptor.context.httpRequest().matchingHeaders("TestHeader")).containsExactly("TestValue"); } @Test public void async_endpointProviderReturnsHeaders_includedInHttpRequest() { RestJsonEndpointProvidersEndpointProvider defaultProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)) .endpointProvider(r -> defaultProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putHeader("TestHeader", "TestValue") .build())) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join()) .hasMessageContaining("stop"); assertThat(interceptor.context.httpRequest().matchingHeaders("TestHeader")).containsExactly("TestValue"); } @Test public void sync_endpointProviderReturnsHeaders_appendedToExistingRequest() { RestJsonEndpointProvidersEndpointProvider defaultProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersClient client = syncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)) .endpointProvider(r -> defaultProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putHeader("TestHeader", "TestValue") .build())) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> r.overrideConfiguration(c -> c.putHeader("TestHeader", "TestValue0")))) .hasMessageContaining("stop"); assertThat(interceptor.context.httpRequest().matchingHeaders("TestHeader")).containsExactly("TestValue", "TestValue0"); } @Test public void async_endpointProviderReturnsHeaders_appendedToExistingRequest() { RestJsonEndpointProvidersEndpointProvider defaultProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)) .endpointProvider(r -> defaultProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putHeader("TestHeader", "TestValue") .build())) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> r.overrideConfiguration(c -> c.putHeader("TestHeader", "TestValue0"))) .join()) .hasMessageContaining("stop"); assertThat(interceptor.context.httpRequest().matchingHeaders("TestHeader")).containsExactly("TestValue", "TestValue0"); } // TODO(sra-identity-auth): Enable for useSraAuth=true /* @Test public void sync_endpointProviderReturnsSignerProperties_overridesV4AuthSchemeResolverProperties() { RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingSigner signer = new CapturingSigner(); List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>(); endpointAuthSchemes.add(SigV4AuthScheme.builder() .signingRegion("region-from-ep") .signingName("name-from-ep") .disableDoubleEncoding(true) .build()); RestJsonEndpointProvidersClient client = syncClientBuilder() .endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes) .build())) .putAuthScheme(authScheme("aws.auth#sigv4", signer)) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {})) .hasMessageContaining("stop"); assertThat(signer.request.property(AwsV4HttpSigner.REGION_NAME)).isEqualTo("region-from-ep"); assertThat(signer.request.property(AwsV4HttpSigner.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep"); assertThat(signer.request.property(AwsV4HttpSigner.DOUBLE_URL_ENCODE)).isEqualTo(false); } @Test public void async_endpointProviderReturnsSignerProperties_overridesV4AuthSchemeResolverProperties() { RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingSigner signer = new CapturingSigner(); List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>(); endpointAuthSchemes.add(SigV4AuthScheme.builder() .signingRegion("region-from-ep") .signingName("name-from-ep") .disableDoubleEncoding(true) .build()); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes) .build())) .putAuthScheme(authScheme("aws.auth#sigv4", signer)) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join()) .hasMessageContaining("stop"); assertThat(signer.request.property(AwsV4HttpSigner.REGION_NAME)).isEqualTo("region-from-ep"); assertThat(signer.request.property(AwsV4HttpSigner.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep"); assertThat(signer.request.property(AwsV4HttpSigner.DOUBLE_URL_ENCODE)).isEqualTo(false); } @Test public void sync_endpointProviderReturnsSignerProperties_overridesV4AAuthSchemeResolverProperties() { RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingSigner signer = new CapturingSigner(); List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>(); endpointAuthSchemes.add(SigV4aAuthScheme.builder() .addSigningRegion("region-1-from-ep") .signingName("name-from-ep") .disableDoubleEncoding(true) .build()); RestJsonEndpointProvidersClient client = syncClientBuilder() .endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes) .build())) .putAuthScheme(authScheme("aws.auth#sigv4a", signer)) .authSchemeProvider(p -> singletonList(AuthSchemeOption.builder() .schemeId("aws.auth#sigv4a") .putSignerProperty( AwsV4aHttpSigner.REGION_SET, RegionSet.create("us-east-1")) .putSignerProperty(AwsV4aHttpSigner.SERVICE_SIGNING_NAME, "Y") .putSignerProperty(AwsV4aHttpSigner.DOUBLE_URL_ENCODE, true) .build())) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {})) .hasMessageContaining("stop"); assertThat(signer.request.property(AwsV4aHttpSigner.REGION_SET)).isEqualTo(RegionSet.create("region-1-from-ep")); assertThat(signer.request.property(AwsV4aHttpSigner.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep"); assertThat(signer.request.property(AwsV4aHttpSigner.DOUBLE_URL_ENCODE)).isEqualTo(false); } @Test public void async_endpointProviderReturnsSignerProperties_overridesV4AAuthSchemeResolverProperties() { RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingSigner signer = new CapturingSigner(); List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>(); endpointAuthSchemes.add(SigV4aAuthScheme.builder() .addSigningRegion("region-1-from-ep") .signingName("name-from-ep") .disableDoubleEncoding(true) .build()); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes) .build())) .putAuthScheme(authScheme("aws.auth#sigv4a", signer)) .authSchemeProvider(p -> singletonList(AuthSchemeOption.builder() .schemeId("aws.auth#sigv4a") .putSignerProperty(AwsV4aHttpSigner.REGION_SET, RegionSet.create("us-east-1")) .putSignerProperty(AwsV4aHttpSigner.SERVICE_SIGNING_NAME, "Y") .putSignerProperty(AwsV4aHttpSigner.DOUBLE_URL_ENCODE, true) .build())) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join()) .hasMessageContaining("stop"); assertThat(signer.request.property(AwsV4aHttpSigner.REGION_SET)).isEqualTo(RegionSet.create("region-1-from-ep")); assertThat(signer.request.property(AwsV4aHttpSigner.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep"); assertThat(signer.request.property(AwsV4aHttpSigner.DOUBLE_URL_ENCODE)).isEqualTo(false); } @Test public void sync_endpointProviderDoesNotReturnV4SignerProperties_executionAttributesFromAuthSchemeOption() { RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)) .authSchemeProvider(p -> singletonList(AuthSchemeOption.builder() .schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, "X") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "Y") .putSignerProperty(AwsV4HttpSigner.DOUBLE_URL_ENCODE, true) .build())) .endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, emptyList()) .build())) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join()) .hasMessageContaining("stop"); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION)).isEqualTo(Region.of("X")); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)).isEqualTo("Y"); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)).isEqualTo(true); } @Test public void sync_endpointProviderReturnsV4SignerProperties_executionAttributesFromEndpointProvider() { RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingInterceptor interceptor = new CapturingInterceptor(); List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>(); endpointAuthSchemes.add(SigV4AuthScheme.builder() .signingRegion("region-from-ep") .signingName("name-from-ep") .disableDoubleEncoding(false) .build()); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)) .endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes) .build())) .authSchemeProvider(p -> singletonList(AuthSchemeOption.builder() .schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, "X") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "Y") .putSignerProperty(AwsV4HttpSigner.DOUBLE_URL_ENCODE, false) .build())) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join()) .hasMessageContaining("stop"); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION)).isEqualTo(Region.of("region-from-ep")); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep"); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)).isEqualTo(true); } @Test public void sync_endpointProviderDoesNotReturnV4aSignerProperties_executionAttributesFromAuthSchemeOption() { RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)) .authSchemeProvider(p -> singletonList(AuthSchemeOption.builder() .schemeId("aws.auth#sigv4a") .putSignerProperty(AwsV4aHttpSigner.REGION_SET, RegionSet.create("region-from-ap")) .putSignerProperty(AwsV4aHttpSigner.SERVICE_SIGNING_NAME, "Y") .putSignerProperty(AwsV4aHttpSigner.DOUBLE_URL_ENCODE, true) .build())) .endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, emptyList()) .build())) .putAuthScheme(authScheme("aws.auth#sigv4a", AwsV4HttpSigner.create())) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join()) .hasMessageContaining("stop"); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE)).isEqualTo(RegionScope.create("region-from-ap")); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)).isEqualTo("Y"); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)).isEqualTo(true); } @Test public void sync_endpointProviderReturnsV4aSignerProperties_executionAttributesFromEndpointProvider() { RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); CapturingInterceptor interceptor = new CapturingInterceptor(); List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>(); endpointAuthSchemes.add(SigV4aAuthScheme.builder() .addSigningRegion("region-from-ep") .signingName("name-from-ep") .disableDoubleEncoding(false) .build()); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .overrideConfiguration(c -> c.addExecutionInterceptor(interceptor)) .endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r) .thenApply(e -> e.toBuilder() .putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes) .build())) .authSchemeProvider(p -> singletonList(AuthSchemeOption.builder() .schemeId("aws.auth#sigv4a") .putSignerProperty(AwsV4aHttpSigner.REGION_SET, RegionSet.create("us-east-1")) .putSignerProperty(AwsV4aHttpSigner.SERVICE_SIGNING_NAME, "Y") .putSignerProperty(AwsV4aHttpSigner.DOUBLE_URL_ENCODE, false) .build())) .putAuthScheme(authScheme("aws.auth#sigv4a", AwsV4HttpSigner.create())) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join()) .hasMessageContaining("stop"); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE)).isEqualTo(RegionScope.create("region-from-ep")); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep"); assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)).isEqualTo(true); } */ private static AuthScheme<?> authScheme(String schemeId, HttpSigner<AwsCredentialsIdentity> signer) { return new AuthScheme<AwsCredentialsIdentity>() { @Override public String schemeId() { return schemeId; } @Override public IdentityProvider<AwsCredentialsIdentity> identityProvider(IdentityProviders providers) { return providers.identityProvider(AwsCredentialsIdentity.class); } @Override public HttpSigner<AwsCredentialsIdentity> signer() { return signer; } }; } public static class CapturingSigner implements HttpSigner<AwsCredentialsIdentity> { private BaseSignRequest<?, ?> request; @Override public SignedRequest sign(SignRequest<? extends AwsCredentialsIdentity> request) { this.request = request; throw new CaptureCompletedException("stop"); } @Override public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends AwsCredentialsIdentity> request) { this.request = request; return CompletableFutureUtils.failedFuture(new CaptureCompletedException("stop")); } } public static class CapturingInterceptor implements ExecutionInterceptor { private Context.BeforeTransmission context; private ExecutionAttributes executionAttributes; @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { this.context = context; this.executionAttributes = executionAttributes; throw new CaptureCompletedException("stop"); } public ExecutionAttributes executionAttributes() { return executionAttributes; } } public static class CaptureCompletedException extends RuntimeException { CaptureCompletedException(String message) { super(message); } } private RestJsonEndpointProvidersClientBuilder syncClientBuilder() { return RestJsonEndpointProvidersClient.builder() .region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))); } private RestJsonEndpointProvidersAsyncClientBuilder asyncClientBuilder() { return RestJsonEndpointProvidersAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))); } }
2,891
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/endpointproviders/AuthSchemeUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.endpointproviders; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import software.amazon.awssdk.awscore.endpoints.authscheme.EndpointAuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4AuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4aAuthScheme; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.AuthSchemeUtils; public class AuthSchemeUtilsTest { @Test public void chooseAuthScheme_noSchemesInList_throws() { assertThatThrownBy(() -> AuthSchemeUtils.chooseAuthScheme(Collections.emptyList())) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Endpoint did not contain any known auth schemes"); } @Test public void chooseAuthScheme_noKnownSchemes_throws() { EndpointAuthScheme sigv1 = mock(EndpointAuthScheme.class); when(sigv1.name()).thenReturn("sigv1"); EndpointAuthScheme sigv5 = mock(EndpointAuthScheme.class); when(sigv5.name()).thenReturn("sigv5"); assertThatThrownBy(() -> AuthSchemeUtils.chooseAuthScheme(Arrays.asList(sigv1, sigv5))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Endpoint did not contain any known auth schemes"); } @Test public void chooseAuthScheme_multipleSchemesKnown_choosesFirst() { EndpointAuthScheme sigv4 = SigV4AuthScheme.builder().build(); EndpointAuthScheme sigv4a = SigV4aAuthScheme.builder().build(); assertThat(AuthSchemeUtils.chooseAuthScheme(Arrays.asList(sigv4, sigv4a))).isEqualTo(sigv4); } }
2,892
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/endpointproviders/EndpointProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.endpointproviders; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointProvider; public class EndpointProviderTest { @Test public void resolveEndpoint_requiredParamNotPresent_throws() { assertThatThrownBy(() -> RestJsonEndpointProvidersEndpointProvider.defaultProvider() .resolveEndpoint(r -> {})) .hasMessageContaining("must not be null"); } @Test public void resolveEndpoint_optionalParamNotPresent_doesNotThrow() { assertThatNoException().isThrownBy(() -> RestJsonEndpointProvidersEndpointProvider.defaultProvider() .resolveEndpoint(r -> r.useFips(null) .region(Region.of("us-mars-1")))); } }
2,893
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/endpointproviders/DefaultPartitionDataProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.endpointproviders; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.DefaultPartitionDataProvider; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Partition; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Partitions; public class DefaultPartitionDataProviderTest { private DefaultPartitionDataProvider provider; @BeforeEach public void setup() { provider = new DefaultPartitionDataProvider(); } @Test public void loadPartitions_returnsData() { Partitions partitions = provider.loadPartitions(); assertThat(partitions.partitions()).isNotEmpty(); } @Test public void loadPartitions_partitionsContainsValidData() { Partition awsPartition = provider.loadPartitions() .partitions() .stream().filter(e -> e.id().equals("aws")) .findFirst() .orElseThrow( () -> new RuntimeException("could not find aws partition")); assertThat(awsPartition.regions()).containsKey("us-west-2"); } }
2,894
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/endpointproviders/ParametersTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.endpointproviders; 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.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointParams; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointProvider; public class ParametersTest { private static final AwsCredentialsProvider CREDENTIALS = StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid")); private static final Region REGION = Region.of("us-east-9000"); private RestJsonEndpointProvidersEndpointProvider mockEndpointProvider; @Before public void setup() { mockEndpointProvider = mock(RestJsonEndpointProvidersEndpointProvider.class); when(mockEndpointProvider.resolveEndpoint(any(RestJsonEndpointProvidersEndpointParams.class))) .thenThrow(new RuntimeException("boom")); } @Test public void parametersObject_defaultStringParam_isPresent() { RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder().build(); assertThat(params.regionWithDefault()).isEqualTo(Region.of("us-east-1")); } @Test public void parametersObject_defaultBooleanParam_isPresent() { RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder().build(); assertThat(params.useFips()).isEqualTo(false); } @Test public void parametersObject_defaultStringParam_customValue_isPresent() { RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder() .regionWithDefault(Region.of( "us-east-1000")) .build(); assertThat(params.regionWithDefault()).isEqualTo(Region.of("us-east-1000")); } @Test public void parametersObject_defaultBooleanParam_customValue_isPresent() { RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder() .useFips(true) .build(); assertThat(params.useFips()).isEqualTo(true); } @Test public void parametersObject_defaultStringParam_setToNull_usesDefaultValue() { RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder() .regionWithDefault(null) .build(); assertThat(params.regionWithDefault()).isEqualTo(Region.of("us-east-1")); } @Test public void parametersObject_defaultBooleanParam_setToNull_usesDefaultValue() { RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder() .useFips(null) .build(); assertThat(params.useFips()).isEqualTo(false); } @Test public void regionBuiltIn_resolvedCorrectly() { RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder() .region(REGION) .credentialsProvider(CREDENTIALS) .endpointProvider(mockEndpointProvider) .build(); assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> { })); ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor = ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class); verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture()); RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue(); assertThat(params.region()).isEqualTo(REGION); } @Test public void dualStackBuiltIn_resolvedCorrectly() { RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder() .region(REGION) .dualstackEnabled(true) .credentialsProvider(CREDENTIALS) .endpointProvider(mockEndpointProvider) .build(); assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> { })); ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor = ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class); verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture()); RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue(); assertThat(params.useDualStack()).isEqualTo(true); } @Test public void fipsBuiltIn_resolvedCorrectly() { RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder() .region(REGION) .fipsEnabled(true) .credentialsProvider(CREDENTIALS) .endpointProvider(mockEndpointProvider) .build(); assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> { })); ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor = ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class); verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture()); RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue(); assertThat(params.useFips()).isEqualTo(true); } @Test public void staticContextParams_OperationWithStaticContextParamA_resolvedCorrectly() { RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder() .region(REGION) .credentialsProvider(CREDENTIALS) .endpointProvider(mockEndpointProvider) .build(); assertThatThrownBy(() -> client.operationWithStaticContextParamA(r -> { })); ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor = ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class); verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture()); RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue(); assertThat(params.staticStringParam()).isEqualTo("operation A"); } @Test public void staticContextParams_OperationWithStaticContextParamB_resolvedCorrectly() { RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder() .region(REGION) .credentialsProvider(CREDENTIALS) .endpointProvider(mockEndpointProvider) .build(); assertThatThrownBy(() -> client.operationWithStaticContextParamB(r -> { })); ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor = ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class); verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture()); RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue(); assertThat(params.staticStringParam()).isEqualTo("operation B"); } @Test public void contextParams_OperationWithContextParam_resolvedCorrectly() { RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder() .region(REGION) .credentialsProvider(CREDENTIALS) .endpointProvider(mockEndpointProvider) .build(); assertThatThrownBy(() -> client.operationWithContextParam(r -> r.stringMember("foobar"))); ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor = ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class); verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture()); RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue(); assertThat(params.operationContextParam()).isEqualTo("foobar"); } @Test public void clientContextParams_setOnBuilder_resolvedCorrectly() { RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder() .region(REGION) .credentialsProvider(CREDENTIALS) .endpointProvider(mockEndpointProvider) .stringClientContextParam("foobar") .booleanClientContextParam(true) .build(); assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> { })); ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor = ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class); verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture()); RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue(); assertThat(params.stringClientContextParam()).isEqualTo("foobar"); assertThat(params.booleanClientContextParam()).isTrue(); } }
2,895
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/endpointproviders/AwsEndpointProviderUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.endpointproviders; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Test; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.awscore.endpoints.AwsEndpointAttribute; import software.amazon.awssdk.awscore.endpoints.authscheme.EndpointAuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4AuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4aAuthScheme; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.AwsEndpointProviderUtils; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Identifier; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Value; import software.amazon.awssdk.utils.MapUtils; public class AwsEndpointProviderUtilsTest { @Test public void endpointOverridden_attrIsFalse_returnsFalse() { ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN, false); assertThat(AwsEndpointProviderUtils.endpointIsOverridden(attrs)).isFalse(); } @Test public void endpointOverridden_attrIsAbsent_returnsFalse() { ExecutionAttributes attrs = new ExecutionAttributes(); assertThat(AwsEndpointProviderUtils.endpointIsOverridden(attrs)).isFalse(); } @Test public void endpointOverridden_attrIsTrue_returnsTrue() { ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN, true); assertThat(AwsEndpointProviderUtils.endpointIsOverridden(attrs)).isTrue(); } @Test public void endpointIsDiscovered_attrIsFalse_returnsFalse() { ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(SdkInternalExecutionAttribute.IS_DISCOVERED_ENDPOINT, false); assertThat(AwsEndpointProviderUtils.endpointIsDiscovered(attrs)).isFalse(); } @Test public void endpointIsDiscovered_attrIsAbsent_returnsFalse() { ExecutionAttributes attrs = new ExecutionAttributes(); assertThat(AwsEndpointProviderUtils.endpointIsDiscovered(attrs)).isFalse(); } @Test public void endpointIsDiscovered_attrIsTrue_returnsTrue() { ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(SdkInternalExecutionAttribute.IS_DISCOVERED_ENDPOINT, true); assertThat(AwsEndpointProviderUtils.endpointIsDiscovered(attrs)).isTrue(); } @Test public void disableHostPrefixInjection_attrIsFalse_returnsFalse() { ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(SdkInternalExecutionAttribute.DISABLE_HOST_PREFIX_INJECTION, false); assertThat(AwsEndpointProviderUtils.disableHostPrefixInjection(attrs)).isFalse(); } @Test public void disableHostPrefixInjection_attrIsAbsent_returnsFalse() { ExecutionAttributes attrs = new ExecutionAttributes(); assertThat(AwsEndpointProviderUtils.disableHostPrefixInjection(attrs)).isFalse(); } @Test public void disableHostPrefixInjection_attrIsTrue_returnsTrue() { ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(SdkInternalExecutionAttribute.DISABLE_HOST_PREFIX_INJECTION, true); assertThat(AwsEndpointProviderUtils.disableHostPrefixInjection(attrs)).isTrue(); } @Test public void valueAsEndpoint_isNone_throws() { assertThatThrownBy(() -> AwsEndpointProviderUtils.valueAsEndpointOrThrow(Value.none())) .isInstanceOf(SdkClientException.class); } @Test public void valueAsEndpoint_isString_throwsAsMsg() { assertThatThrownBy(() -> AwsEndpointProviderUtils.valueAsEndpointOrThrow(Value.fromStr("oops!"))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("oops!"); } @Test public void valueAsEndpoint_isEndpoint_returnsEndpoint() { Value.Endpoint endpointVal = Value.Endpoint.builder() .url("https://myservice.aws") .build(); Endpoint expected = Endpoint.builder() .url(URI.create("https://myservice.aws")) .build(); assertThat(expected.url()).isEqualTo(AwsEndpointProviderUtils.valueAsEndpointOrThrow(endpointVal).url()); } @Test public void valueAsEndpoint_endpointHasAuthSchemes_includesAuthSchemes() { List<Value> authSchemes = Arrays.asList( Value.fromRecord(MapUtils.of(Identifier.of("name"), Value.fromStr("sigv4"), Identifier.of("signingRegion"), Value.fromStr("us-west-2"), Identifier.of("signingName"), Value.fromStr("myservice"), Identifier.of("disableDoubleEncoding"), Value.fromBool(false))), Value.fromRecord(MapUtils.of(Identifier.of("name"), Value.fromStr("sigv4a"), Identifier.of("signingRegionSet"), Value.fromArray(Collections.singletonList(Value.fromStr("*"))), Identifier.of("signingName"), Value.fromStr("myservice"), Identifier.of("disableDoubleEncoding"), Value.fromBool(false))), // Unknown scheme name, should ignore Value.fromRecord(MapUtils.of(Identifier.of("name"), Value.fromStr("sigv5"))) ); Value.Endpoint endpointVal = Value.Endpoint.builder() .url("https://myservice.aws") .property("authSchemes", Value.fromArray(authSchemes)) .build(); EndpointAuthScheme sigv4 = SigV4AuthScheme.builder() .signingName("myservice") .signingRegion("us-west-2") .disableDoubleEncoding(false) .build(); EndpointAuthScheme sigv4a = SigV4aAuthScheme.builder() .signingName("myservice") .addSigningRegion("*") .disableDoubleEncoding(false) .build(); assertThat(AwsEndpointProviderUtils.valueAsEndpointOrThrow(endpointVal).attribute(AwsEndpointAttribute.AUTH_SCHEMES)) .containsExactly(sigv4, sigv4a); } @Test public void valueAsEndpoint_endpointHasUnknownProperty_ignores() { Value.Endpoint endpointVal = Value.Endpoint.builder() .url("https://myservice.aws") .property("foo", Value.fromStr("baz")) .build(); assertThat(AwsEndpointProviderUtils.valueAsEndpointOrThrow(endpointVal).attribute(AwsEndpointAttribute.AUTH_SCHEMES)).isNull(); } @Test public void valueAsEndpoint_endpointHasHeaders_includesHeaders() { Value.Endpoint endpointVal = Value.Endpoint.builder() .url("https://myservice.aws") .addHeader("foo1", "bar1") .addHeader("foo1", "bar2") .addHeader("foo2", "baz") .build(); Map<String, List<String>> expectedHeaders = MapUtils.of("foo1", Arrays.asList("bar1", "bar2"), "foo2", Arrays.asList("baz")); assertThat(AwsEndpointProviderUtils.valueAsEndpointOrThrow(endpointVal).headers()).isEqualTo(expectedHeaders); } @Test public void regionBuiltIn_returnsAttrValue() { ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_EAST_1); assertThat(AwsEndpointProviderUtils.regionBuiltIn(attrs)).isEqualTo(Region.US_EAST_1); } @Test public void dualStackEnabledBuiltIn_returnsAttrValue() { ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(AwsExecutionAttribute.DUALSTACK_ENDPOINT_ENABLED, true); assertThat(AwsEndpointProviderUtils.dualStackEnabledBuiltIn(attrs)).isEqualTo(true); } @Test public void fipsEnabledBuiltIn_returnsAttrValue() { ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(AwsExecutionAttribute.FIPS_ENDPOINT_ENABLED, true); assertThat(AwsEndpointProviderUtils.fipsEnabledBuiltIn(attrs)).isEqualTo(true); } @Test public void endpointBuiltIn_doesNotIncludeQueryParams() { URI endpoint = URI.create("https://example.com/path?foo=bar"); ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN, true); attrs.putAttribute(SdkExecutionAttribute.CLIENT_ENDPOINT, endpoint); assertThat(AwsEndpointProviderUtils.endpointBuiltIn(attrs).toString()).isEqualTo("https://example.com/path"); } @Test public void useGlobalEndpointBuiltIn_returnsAttrValue() { ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(AwsExecutionAttribute.USE_GLOBAL_ENDPOINT, true); assertThat(AwsEndpointProviderUtils.useGlobalEndpointBuiltIn(attrs)).isEqualTo(true); } @Test public void setUri_combinesPathsCorrectly() { URI clientEndpoint = URI.create("https://override.example.com/a"); URI requestUri = URI.create("https://override.example.com/a/c"); URI resolvedUri = URI.create("https://override.example.com/a/b"); SdkHttpRequest request = SdkHttpRequest.builder() .uri(requestUri) .method(SdkHttpMethod.GET) .build(); assertThat(AwsEndpointProviderUtils.setUri(request, clientEndpoint, resolvedUri).getUri().toString()) .isEqualTo("https://override.example.com/a/b/c"); } @Test public void setUri_doubleSlash_combinesPathsCorrectly() { URI clientEndpoint = URI.create("https://override.example.com/a"); URI requestUri = URI.create("https://override.example.com/a//c"); URI resolvedUri = URI.create("https://override.example.com/a/b"); SdkHttpRequest request = SdkHttpRequest.builder() .uri(requestUri) .method(SdkHttpMethod.GET) .build(); assertThat(AwsEndpointProviderUtils.setUri(request, clientEndpoint, resolvedUri).getUri().toString()) .isEqualTo("https://override.example.com/a/b//c"); } @Test public void setUri_withTrailingSlashNoPath_combinesPathsCorrectly() { URI clientEndpoint = URI.create("https://override.example.com/"); URI requestUri = URI.create("https://override.example.com//a"); URI resolvedUri = URI.create("https://override.example.com/"); SdkHttpRequest request = SdkHttpRequest.builder() .uri(requestUri) .method(SdkHttpMethod.GET) .build(); assertThat(AwsEndpointProviderUtils.setUri(request, clientEndpoint, resolvedUri).getUri().toString()) .isEqualTo("https://override.example.com//a"); } @Test public void addHostPrefix_prefixIsNull_returnsUnModified() { URI url = URI.create("https://foo.aws"); Endpoint e = Endpoint.builder() .url(url) .build(); assertThat(AwsEndpointProviderUtils.addHostPrefix(e, null).url()).isEqualTo(url); } @Test public void addHostPrefix_prefixIsEmpty_returnsUnModified() { URI url = URI.create("https://foo.aws"); Endpoint e = Endpoint.builder() .url(url) .build(); assertThat(AwsEndpointProviderUtils.addHostPrefix(e, "").url()).isEqualTo(url); } @Test public void addHostPrefix_prefixPresent_returnsPrefixPrepended() { URI url = URI.create("https://foo.aws"); Endpoint e = Endpoint.builder() .url(url) .build(); URI expected = URI.create("https://api.foo.aws"); assertThat(AwsEndpointProviderUtils.addHostPrefix(e, "api.").url()).isEqualTo(expected); } @Test public void addHostPrefix_prefixPresent_preservesPortPathAndQuery() { URI url = URI.create("https://foo.aws:1234/a/b/c?queryParam1=val1"); Endpoint e = Endpoint.builder() .url(url) .build(); URI expected = URI.create("https://api.foo.aws:1234/a/b/c?queryParam1=val1"); assertThat(AwsEndpointProviderUtils.addHostPrefix(e, "api.").url()).isEqualTo(expected); } @Test public void addHostPrefix_prefixInvalid_throws() { URI url = URI.create("https://foo.aws"); Endpoint e = Endpoint.builder() .url(url) .build(); assertThatThrownBy(() -> AwsEndpointProviderUtils.addHostPrefix(e, "foo#bar.*baz")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("component must match the pattern"); } }
2,896
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/endpointproviders/ClientBuilderTests.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.endpointproviders; 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.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.net.URI; import java.util.concurrent.CompletableFuture; import org.junit.Test; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClient; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClientBuilder; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClientBuilder; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersClientContextParams; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointParams; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointProvider; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.CompletableFutureUtils; public class ClientBuilderTests { @Test public void syncBuilder_setCustomProvider_interceptorUsesProvider() { RestJsonEndpointProvidersEndpointProvider mockProvider = mock(RestJsonEndpointProvidersEndpointProvider.class); SdkHttpClient mockClient = mock(SdkHttpClient.class); when(mockClient.clientName()).thenReturn("MockHttpClient"); when(mockClient.prepareRequest(any())).thenThrow(new RuntimeException("boom")); when(mockProvider.resolveEndpoint(any(RestJsonEndpointProvidersEndpointParams.class))) .thenReturn(CompletableFuture.completedFuture(Endpoint.builder() .url(URI.create("https://my-service.com")) .build())); RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder() .endpointProvider(mockProvider) .httpClient(mockClient) .region(Region.US_WEST_2) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))) .build(); assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> { })).hasMessageContaining("boom"); verify(mockProvider).resolveEndpoint(any(RestJsonEndpointProvidersEndpointParams.class)); ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(mockClient).prepareRequest(httpRequestCaptor.capture()); URI requestUri = httpRequestCaptor.getValue().httpRequest().getUri(); assertThat(requestUri.getScheme()).isEqualTo("https"); assertThat(requestUri.getHost()).isEqualTo("my-service.com"); } @Test public void asyncBuilder_setCustomProvider_interceptorUsesProvider() { RestJsonEndpointProvidersEndpointProvider mockProvider = mock(RestJsonEndpointProvidersEndpointProvider.class); SdkAsyncHttpClient mockClient = mock(SdkAsyncHttpClient.class); when(mockClient.clientName()).thenReturn("MockHttpClient"); when(mockClient.execute(any())).thenAnswer(i -> { AsyncExecuteRequest r = i.getArgument(0, AsyncExecuteRequest.class); r.responseHandler().onError(new RuntimeException("boom")); return CompletableFutureUtils.failedFuture(new RuntimeException()); }); when(mockProvider.resolveEndpoint(any(RestJsonEndpointProvidersEndpointParams.class))) .thenReturn(CompletableFuture.completedFuture(Endpoint.builder() .url(URI.create("https://my-service.com")) .build())); RestJsonEndpointProvidersAsyncClient client = RestJsonEndpointProvidersAsyncClient.builder() .endpointProvider(mockProvider) .httpClient(mockClient) .region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))) .build(); assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> { }).join()) .hasRootCauseMessage("boom"); verify(mockProvider).resolveEndpoint(any(RestJsonEndpointProvidersEndpointParams.class)); ArgumentCaptor<AsyncExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); verify(mockClient).execute(httpRequestCaptor.capture()); URI requestUri = httpRequestCaptor.getValue().request().getUri(); assertThat(requestUri.getScheme()).isEqualTo("https"); assertThat(requestUri.getHost()).isEqualTo("my-service.com"); } @Test public void sync_clientContextParamsSetOnBuilder_includedInExecutionAttributes() { ExecutionInterceptor mockInterceptor = mock(ExecutionInterceptor.class); when(mockInterceptor.modifyRequest(any(), any())).thenThrow(new RuntimeException("oops")); RestJsonEndpointProvidersClient client = syncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(mockInterceptor)) .booleanClientContextParam(true) .stringClientContextParam("hello") .build(); assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> { })).hasMessageContaining("oops"); ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); verify(mockInterceptor).modifyRequest(any(), attributesCaptor.capture()); ExecutionAttributes executionAttrs = attributesCaptor.getValue(); AttributeMap clientContextParams = executionAttrs.getAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS); assertThat(clientContextParams.get(RestJsonEndpointProvidersClientContextParams.BOOLEAN_CLIENT_CONTEXT_PARAM)) .isEqualTo(true); assertThat(clientContextParams.get(RestJsonEndpointProvidersClientContextParams.STRING_CLIENT_CONTEXT_PARAM)) .isEqualTo("hello"); } @Test public void async_clientContextParamsSetOnBuilder_includedInExecutionAttributes() { ExecutionInterceptor mockInterceptor = mock(ExecutionInterceptor.class); when(mockInterceptor.modifyRequest(any(), any())).thenThrow(new RuntimeException("oops")); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(mockInterceptor)) .booleanClientContextParam(true) .stringClientContextParam("hello") .build(); assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> { }).join()).hasMessageContaining("oops"); ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); verify(mockInterceptor).modifyRequest(any(), attributesCaptor.capture()); ExecutionAttributes executionAttrs = attributesCaptor.getValue(); AttributeMap clientContextParams = executionAttrs.getAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS); assertThat(clientContextParams.get(RestJsonEndpointProvidersClientContextParams.BOOLEAN_CLIENT_CONTEXT_PARAM)) .isEqualTo(true); assertThat(clientContextParams.get(RestJsonEndpointProvidersClientContextParams.STRING_CLIENT_CONTEXT_PARAM)) .isEqualTo("hello"); } private RestJsonEndpointProvidersClientBuilder syncClientBuilder() { return RestJsonEndpointProvidersClient.builder() .region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))); } private RestJsonEndpointProvidersAsyncClientBuilder asyncClientBuilder() { return RestJsonEndpointProvidersAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))); } }
2,897
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/endpointproviders/RequestOverrideEndpointProviderTests.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.endpointproviders; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.util.concurrent.CompletableFuture; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClient; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClientBuilder; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient; import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClientBuilder; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointParams; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointProvider; public class RequestOverrideEndpointProviderTests { @Test public void sync_endpointOverridden_equals_requestOverride() { CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersClient client = syncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor) .putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true)) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix( r -> r.overrideConfiguration(o -> o.endpointProvider(new CustomEndpointProvider(Region.AWS_GLOBAL)))) ) .hasMessageContaining("stop"); Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT); assertThat(endpoint.url().getHost()).isEqualTo("restjson.aws-global.amazonaws.com"); } @Test public void sync_endpointOverridden_equals_ClientsWhenNoRequestOverride() { CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersClient client = syncClientBuilder().endpointProvider(new CustomEndpointProvider(Region.EU_WEST_2)) .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor) .putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true)) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {})).hasMessageContaining("stop"); Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT); assertThat(endpoint.url().getHost()).isEqualTo("restjson.eu-west-2.amazonaws.com"); } @Test public void async_endpointOverridden_equals_requestOverride() { CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder() .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor) .putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true)) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix( r -> r.overrideConfiguration(o -> o.endpointProvider(new CustomEndpointProvider(Region.AWS_GLOBAL))) ).join()) .hasMessageContaining("stop"); Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT); assertThat(endpoint.url().getHost()).isEqualTo("restjson.aws-global.amazonaws.com"); } @Test public void async_endpointOverridden_equals_ClientsWhenNoRequestOverride() { CapturingInterceptor interceptor = new CapturingInterceptor(); RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder().endpointProvider(new CustomEndpointProvider(Region.EU_WEST_2)) .overrideConfiguration(o -> o.addExecutionInterceptor(interceptor) .putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true)) .build(); assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join()) .hasMessageContaining("stop"); Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT); assertThat(endpoint.url().getHost()).isEqualTo("restjson.eu-west-2.amazonaws.com"); } public static class CapturingInterceptor implements ExecutionInterceptor { private ExecutionAttributes executionAttributes; @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { this.executionAttributes = executionAttributes; throw new CaptureCompletedException("stop"); } public ExecutionAttributes executionAttributes() { return executionAttributes; } public class CaptureCompletedException extends RuntimeException { CaptureCompletedException(String message) { super(message); } } } private RestJsonEndpointProvidersClientBuilder syncClientBuilder() { return RestJsonEndpointProvidersClient.builder() .region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))); } private RestJsonEndpointProvidersAsyncClientBuilder asyncClientBuilder() { return RestJsonEndpointProvidersAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("akid", "skid"))); } class CustomEndpointProvider implements RestJsonEndpointProvidersEndpointProvider{ final RestJsonEndpointProvidersEndpointProvider endpointProvider; final Region overridingRegion; CustomEndpointProvider (Region region){ this.endpointProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider(); this.overridingRegion = region; } @Override public CompletableFuture<Endpoint> resolveEndpoint(RestJsonEndpointProvidersEndpointParams endpointParams) { return endpointProvider.resolveEndpoint(endpointParams.toBuilder().region(overridingRegion).build()); } } }
2,898
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/customresponsemetadata/CustomResponseMetadataTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.customresponsemetadata; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; 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 software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse; import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonResponse; import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationResponse; import software.amazon.awssdk.utils.builder.SdkBuilder; public class CustomResponseMetadataTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private ProtocolRestJsonClient client; private ProtocolRestJsonAsyncClient asyncClient; @Before public void setupClient() { client = ProtocolRestJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); asyncClient = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); } @Test public void syncNonStreaming_shouldContainResponseMetadata() { stubResponseWithHeaders(); AllTypesResponse allTypesResponse = client.allTypes(SdkBuilder::build); verifyResponseMetadata(allTypesResponse); } @Test public void syncStreaming_shouldContainResponseMetadata() { stubResponseWithHeaders(); ResponseBytes<StreamingOutputOperationResponse> streamingOutputOperationResponseResponseBytes = client.streamingOutputOperation(SdkBuilder::build, ResponseTransformer.toBytes()); verifyResponseMetadata(streamingOutputOperationResponseResponseBytes.response()); } @Test public void asyncNonStreaming_shouldContainResponseMetadata() { stubResponseWithHeaders(); AllTypesResponse allTypesResponse = asyncClient.allTypes(SdkBuilder::build).join(); verifyResponseMetadata(allTypesResponse); } @Test public void asyncStreaming_shouldContainResponseMetadata() { stubResponseWithHeaders(); CompletableFuture<ResponseBytes<StreamingOutputOperationResponse>> response = asyncClient.streamingOutputOperation(SdkBuilder::build, AsyncResponseTransformer.toBytes()); verifyResponseMetadata(response.join().response()); } @Test public void headerNotAvailable_responseMetadataShouldBeUnknown() { stubResponseWithoutHeaders(); AllTypesResponse allTypesResponse = client.allTypes(SdkBuilder::build); verifyUnknownResponseMetadata(allTypesResponse); } private void verifyResponseMetadata(ProtocolRestJsonResponse allTypesResponse) { assertThat(allTypesResponse.responseMetadata()).isNotNull(); assertThat(allTypesResponse.responseMetadata().barId()).isEqualTo("bar"); assertThat(allTypesResponse.responseMetadata().fooId()).isEqualTo("foo"); assertThat(allTypesResponse.responseMetadata().requestId()).isEqualTo("foobar"); } private void verifyUnknownResponseMetadata(ProtocolRestJsonResponse allTypesResponse) { assertThat(allTypesResponse.responseMetadata()).isNotNull(); assertThat(allTypesResponse.responseMetadata().barId()).isEqualTo("UNKNOWN"); assertThat(allTypesResponse.responseMetadata().fooId()).isEqualTo("UNKNOWN"); assertThat(allTypesResponse.responseMetadata().requestId()).isEqualTo("UNKNOWN"); } private void stubResponseWithHeaders() { stubFor(post(anyUrl()) .willReturn(aResponse().withStatus(200) .withHeader("x-foo-id", "foo") .withHeader("x-bar-id", "bar") .withHeader("x-foobar-id", "foobar") .withBody("{}"))); } private void stubResponseWithoutHeaders() { stubFor(post(anyUrl()) .willReturn(aResponse().withStatus(200) .withBody("{}"))); } }
2,899