index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/endpointdiscovery/EndpointDiscoveryCacheLoaderGeneratorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.endpointdiscovery; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClientTestModels; public class EndpointDiscoveryCacheLoaderGeneratorTest { @Test public void syncEndpointDiscoveryCacheLoaderGenerator() { IntermediateModel model = ClientTestModels.endpointDiscoveryModels(); GeneratorTaskParams dependencies = GeneratorTaskParams.create(model, "sources/", "tests/", "resources/"); EndpointDiscoveryCacheLoaderGenerator cacheLoader = new EndpointDiscoveryCacheLoaderGenerator(dependencies); assertThat(cacheLoader, generatesTo("test-sync-cache-loader.java")); } @Test public void asyncEndpointDiscoveryCacheLoaderGenerator() { IntermediateModel model = ClientTestModels.endpointDiscoveryModels(); GeneratorTaskParams dependencies = GeneratorTaskParams.create(model, "sources/", "tests/", "resources/"); EndpointDiscoveryAsyncCacheLoaderGenerator cacheLoader = new EndpointDiscoveryAsyncCacheLoaderGenerator(dependencies); assertThat(cacheLoader, generatesTo("test-async-cache-loader.java")); } }
3,300
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/waiters/WaitersClassSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.waiters; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.ClientTestModels; public class WaitersClassSpecTest { @Test public void asyncWaiterInterface() throws Exception { ClassSpec asyncWaiterInterfaceSpec = new AsyncWaiterInterfaceSpec(ClientTestModels.queryServiceModels()); assertThat(asyncWaiterInterfaceSpec, generatesTo("query-async-waiter-interface.java")); } @Test public void syncWaiterInterface() throws Exception { ClassSpec waiterInterface = new WaiterInterfaceSpec(ClientTestModels.queryServiceModels()); assertThat(waiterInterface, generatesTo("query-sync-waiter-interface.java")); } @Test public void asyncWaiterImpl() throws Exception { ClassSpec asyncWaiterInterfaceSpec = new AsyncWaiterClassSpec(ClientTestModels.queryServiceModels()); assertThat(asyncWaiterInterfaceSpec, generatesTo("query-async-waiter-class.java")); } @Test public void syncWaiterImpl() throws Exception { ClassSpec waiterInterface = new WaiterClassSpec(ClientTestModels.queryServiceModels()); assertThat(waiterInterface, generatesTo("query-sync-waiter-class.java")); } }
3,301
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/waiters/JmesPathAcceptorGeneratorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.waiters; import static org.assertj.core.api.Assertions.assertThat; import com.squareup.javapoet.ClassName; import org.junit.Before; import org.junit.Test; public class JmesPathAcceptorGeneratorTest { private JmesPathAcceptorGenerator acceptorGenerator; @Before public void setup() { acceptorGenerator = new JmesPathAcceptorGenerator(ClassName.get("software.amazon.awssdk.codegen", "WaitersRuntime")); } @Test public void testAutoScalingComplexExpression() { testConversion("contains(AutoScalingGroups[].[length(Instances[?LifecycleState=='InService']) >= MinSize][], `false`)", "input.field(\"AutoScalingGroups\").flatten().multiSelectList(x0 -> x0.field(\"Instances\").filter(x1 -> " + "x1.field(\"LifecycleState\").compare(\"==\", x1.constant(\"InService\"))).length().compare(\">=\", " + "x0.field(\"MinSize\"))).flatten().contains(input.constant(false))"); } @Test public void testEcsComplexExpression() { testConversion("length(services[?!(length(deployments) == `1` && runningCount == desiredCount)]) == `0`", "input.field(\"services\").filter(x0 -> x0.constant(x0.field(\"deployments\").length().compare(\"==\", " + "x0.constant(1)).and(x0.field(\"runningCount\").compare(\"==\", x0.field(\"desiredCount\"))).not()))" + ".length().compare(\"==\", input.constant(0))"); } @Test public void testSubExpressionWithIdentifier() { testConversion("foo.bar", "input.field(\"foo\").field(\"bar\")"); } @Test public void testSubExpressionWithMultiSelectList() { testConversion("foo.[bar]", "input.field(\"foo\").multiSelectList(x0 -> x0.field(\"bar\"))"); } @Test(expected = UnsupportedOperationException.class) public void testSubExpressionWithMultiSelectHash() { testConversion("foo.{bar : baz}", ""); } @Test public void testSubExpressionWithFunction() { testConversion("length(foo)", "input.field(\"foo\").length()"); } @Test public void testSubExpressionWithStar() { testConversion("foo.*", "input.field(\"foo\").wildcard()"); } @Test(expected = UnsupportedOperationException.class) public void testPipeExpression() { testConversion("foo | bar", ""); } @Test public void testOrExpression() { testConversion("foo || bar", "input.field(\"foo\").or(input.field(\"bar\"))"); } @Test public void testAndExpression() { testConversion("foo && bar", "input.field(\"foo\").and(input.field(\"bar\"))"); } @Test public void testNotExpression() { testConversion("!foo", "input.constant(input.field(\"foo\").not())"); } @Test public void testParenExpression() { testConversion("(foo)", "input.field(\"foo\")"); } @Test public void testWildcardExpression() { testConversion("*", "input.wildcard()"); } @Test public void testIndexedExpressionWithoutLeftExpressionWithoutContents() { testConversion("[]", "input.flatten()"); } @Test public void testIndexedExpressionWithoutLeftExpressionWithNumberContents() { testConversion("[10]", "input.index(10)"); } @Test(expected = UnsupportedOperationException.class) public void testIndexedExpressionWithoutLeftExpressionWithStarContents() { testConversion("[*]", ""); } @Test public void testIndexedExpressionWithoutLeftExpressionWithQuestionMark() { testConversion("[?foo]", "input.filter(x0 -> x0.field(\"foo\"))"); } @Test public void testIndexedExpressionWithLeftExpressionWithoutContents() { testConversion("foo[]", "input.field(\"foo\").flatten()"); } @Test public void testIndexedExpressionWithLeftExpressionWithContents() { testConversion("foo[10]", "input.field(\"foo\").index(10)"); } @Test(expected = UnsupportedOperationException.class) public void testIndexedExpressionWithLeftExpressionWithStarContents() { testConversion("foo[*]", ""); } @Test public void testIndexedExpressionWithLeftExpressionWithQuestionMark() { testConversion("foo[?bar]", "input.field(\"foo\").filter(x0 -> x0.field(\"bar\"))"); } @Test public void testMultiSelectList2() { testConversion("[foo, bar]", "input.multiSelectList(x0 -> x0.field(\"foo\"), x1 -> x1.field(\"bar\"))"); } @Test public void testMultiSelectList3() { testConversion("[foo, bar, baz]", "input.multiSelectList(x0 -> x0.field(\"foo\"), x1 -> x1.field(\"bar\"), x2 -> x2.field(\"baz\"))"); } @Test public void testNestedMultiSelectListsRight() { testConversion("[foo, [bar, baz]]", "input.multiSelectList(x0 -> x0.field(\"foo\"), " + "x1 -> x1.multiSelectList(x2 -> x2.field(\"bar\"), x3 -> x3.field(\"baz\")))"); } @Test public void testNestedMultiSelectListsCenter() { testConversion("[foo, [bar, baz], bam]", "input.multiSelectList(x0 -> x0.field(\"foo\"), " + "x1 -> x1.multiSelectList(x2 -> x2.field(\"bar\"), x3 -> x3.field(\"baz\")), " + "x4 -> x4.field(\"bam\"))"); } @Test public void testNestedMultiSelectListsLeft() { testConversion("[[foo, bar], baz]", "input.multiSelectList(x0 -> x0.multiSelectList(x1 -> x1.field(\"foo\"), " + "x2 -> x2.field(\"bar\")), " + "x3 -> x3.field(\"baz\"))"); } @Test(expected = UnsupportedOperationException.class) public void testMultiSelectHash2() { testConversion("{fooK : fooV, barK : barV}", ""); } @Test(expected = UnsupportedOperationException.class) public void testMultiSelectHash3() { testConversion("{fooK : fooV, barK : barV, bazK : bazV}", ""); } @Test public void testComparatorExpressionLT() { testConversion("foo < bar", "input.field(\"foo\").compare(\"<\", input.field(\"bar\"))"); } @Test public void testComparatorExpressionGT() { testConversion("foo > bar", "input.field(\"foo\").compare(\">\", input.field(\"bar\"))"); } @Test public void testComparatorExpressionLTE() { testConversion("foo <= bar", "input.field(\"foo\").compare(\"<=\", input.field(\"bar\"))"); } @Test public void testComparatorExpressionGTE() { testConversion("foo >= bar", "input.field(\"foo\").compare(\">=\", input.field(\"bar\"))"); } @Test public void testComparatorExpressionEQ() { testConversion("foo == bar", "input.field(\"foo\").compare(\"==\", input.field(\"bar\"))"); } @Test public void testComparatorExpressionNEQ() { testConversion("foo != bar", "input.field(\"foo\").compare(\"!=\", input.field(\"bar\"))"); } @Test(expected = UnsupportedOperationException.class) public void testSliceExpressionWithNoNumbers2() { testConversion("[:]", ""); } @Test(expected = UnsupportedOperationException.class) public void testSliceExpressionWithNoNumbers3() { testConversion("[::]", ""); } @Test(expected = UnsupportedOperationException.class) public void testSliceExpressionWithStartNumber2() { testConversion("[10:]", ""); } @Test(expected = UnsupportedOperationException.class) public void testSliceExpressionWithStopNumber2() { testConversion("[:10]", ""); } @Test(expected = UnsupportedOperationException.class) public void testSliceExpressionWithStartStopNumber2() { testConversion("[10:20]", ""); } @Test(expected = UnsupportedOperationException.class) public void testSliceExpressionWithStartNumber3() { testConversion("[10::]", ""); } @Test(expected = UnsupportedOperationException.class) public void testSliceExpressionWithStopNumber3() { testConversion("[:10:]", ""); } @Test(expected = UnsupportedOperationException.class) public void testSliceExpressionWithStartStopNumber3() { testConversion("[10:20:]", ""); } @Test(expected = UnsupportedOperationException.class) public void testSliceExpressionWithStartStopStepNumber3() { testConversion("[10:20:30]", ""); } @Test(expected = UnsupportedOperationException.class) public void testSliceExpressionWithStepNumber3() { testConversion("[::30]", ""); } @Test(expected = UnsupportedOperationException.class) public void testCurrentNode() { testConversion("@", ""); } @Test public void testEmptyIdentifierUnquoted() { testConversion("foo_bar", "input.field(\"foo_bar\")"); } @Test public void testIdentifierUnquoted() { testConversion("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_", "input.field(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\")"); } @Test public void testIdentifierQuoted() { testConversion("\"foo bar\"", "input.field(\"foo bar\")"); } @Test public void testRawStringEmpty() { testConversion("''", "input.constant(\"\")"); } @Test public void testRawStringWithValue() { testConversion("'foo bar'", "input.constant(\"foo bar\")"); } @Test public void testNegativeNumber() { testConversion("foo[-10]", "input.field(\"foo\").index(-10)"); } private void testConversion(String jmesPathString, String expectedCode) { assertThat(acceptorGenerator.interpret(jmesPathString, "input").toString()).isEqualTo((expectedCode)); } }
3,302
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/common/UserAgentClassSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.common; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.ClientTestModels; import software.amazon.awssdk.codegen.poet.common.UserAgentUtilsSpec; public class UserAgentClassSpecTest { @Test void testUserAgentClass() { ClassSpec useragentspec = new UserAgentUtilsSpec(ClientTestModels.restJsonServiceModels()); assertThat(useragentspec, generatesTo("test-user-agent-class.java")); } }
3,303
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/common/EnumClassTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.common; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import java.io.IOException; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.model.intermediate.EnumModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; public class EnumClassTest { @Test public void basicEnumTest() throws IOException { ShapeModel m = new ShapeModel("TestEnumClass"); m.setType(ShapeType.Enum); m.setShapeName("TestEnumClass"); m.setEnums(asList(new EnumModel("AVAILABLE", "available"), new EnumModel("PERMANENT_FAILURE", "permanent-failure"))); m.setDocumentation("Some comment on the class itself"); EnumClass sut = new EnumClass("software.amazon.awssdk.codegen.poet.common.model", m); assertThat(sut, generatesTo("test-enum-class.java")); } }
3,304
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/SharedStreamAwsModelSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Locale; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; @RunWith(Parameterized.class) public class SharedStreamAwsModelSpecTest { private static IntermediateModel intermediateModel; private final ShapeModel shapeModel; @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> data() { invokeSafely(SharedStreamAwsModelSpecTest::setUp); return intermediateModel.getShapes().values().stream().map(shape -> new Object[] { shape }).collect(toList()); } public SharedStreamAwsModelSpecTest(ShapeModel shapeModel) { this.shapeModel = shapeModel; } @Test public void basicGeneration() throws Exception { assertThat(new AwsServiceModel(intermediateModel, shapeModel), generatesTo(referenceFileForShape())); } private String referenceFileForShape() { return "sharedstream/" + shapeModel.getShapeName().toLowerCase(Locale.ENGLISH) + ".java"; } private static void setUp() throws IOException { File serviceModelFile = new File(SharedStreamAwsModelSpecTest.class.getResource("sharedstream/service-2.json").getFile()); ServiceModel serviceModel = ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(serviceModel) .customizationConfig(CustomizationConfig.create()) .build()) .build(); } }
3,305
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/AwsServiceBaseResponseSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; public class AwsServiceBaseResponseSpecTest { private static IntermediateModel intermediateModel; @BeforeAll public static void setUp() throws IOException { File serviceModelFile = new File(AwsModelSpecTest.class.getResource("service-2.json").getFile()); File customizationConfigFile = new File(AwsModelSpecTest.class .getResource("customization.config") .getFile()); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile)) .customizationConfig(ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile)) .build()) .build(); } @Test public void testGeneration() { AwsServiceBaseResponseSpec spec = new AwsServiceBaseResponseSpec(intermediateModel); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); } }
3,306
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/ServiceClientConfigurationSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import java.io.File; import java.io.IOException; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; public class ServiceClientConfigurationSpecTest { private static IntermediateModel intermediateModel; @BeforeAll public static void setUp() throws IOException { File serviceModelFile = new File(AwsModelSpecTest.class.getResource("service-2.json").getFile()); File customizationConfigFile = new File(AwsModelSpecTest.class .getResource("customization.config") .getFile()); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile)) .customizationConfig(ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile)) .build()) .build(); } @Test public void testGeneration() { ServiceClientConfigurationClass spec = new ServiceClientConfigurationClass(intermediateModel); MatcherAssert.assertThat(spec, generatesTo("serviceclientconfiguration.java")); } }
3,307
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/ResponseMetadataSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; public class ResponseMetadataSpecTest { private static IntermediateModel model; private static IntermediateModel modelWithCustomizedResponseMetadata; @BeforeAll public static void setUp() throws IOException { File serviceModelFile = new File(AwsModelSpecTest.class.getResource("service-2.json") .getFile()); File configFile = new File(AwsModelSpecTest.class .getResource("customization.config") .getFile()); File customizationConfigFile = new File(ResponseMetadataSpecTest.class .getResource("customresponsemetadata/customization.config") .getFile()); model = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile)) .customizationConfig(ModelLoaderUtils.loadModel(CustomizationConfig.class, configFile)) .build()) .build(); modelWithCustomizedResponseMetadata = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile)) .customizationConfig(ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile)) .build()) .build(); } @Test public void responseMetadataGeneration() { ResponseMetadataSpec spec = new ResponseMetadataSpec(model); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); AwsServiceBaseResponseSpec responseSpec = new AwsServiceBaseResponseSpec(model); assertThat(responseSpec, generatesTo(responseSpec.className().simpleName().toLowerCase() + ".java")); } @Test public void customResponseMetadataGeneration() { ResponseMetadataSpec spec = new ResponseMetadataSpec(modelWithCustomizedResponseMetadata); assertThat(spec, generatesTo("./customresponsemetadata/" + spec.className().simpleName().toLowerCase() + ".java")); AwsServiceBaseResponseSpec responseSpec = new AwsServiceBaseResponseSpec(modelWithCustomizedResponseMetadata); assertThat(responseSpec, generatesTo("./customresponsemetadata/" + responseSpec.className().simpleName().toLowerCase() + ".java")); } }
3,308
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/CustomSdkShapesCodegenTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; public class CustomSdkShapesCodegenTest { private IntermediateModel intermediateModel; @Before public void setUp() throws IOException { File serviceModelFile = new File(AwsModelSpecTest.class.getResource("service-2.json").getFile()); File customizationConfigFile = new File(AwsModelSpecTest.class .getResource("customization.config") .getFile()); ServiceModel serviceModel = ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile); CustomizationConfig basicConfig = ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(serviceModel) .customizationConfig(basicConfig) .build()) .build(); } @Test public void setAndInjectCustomShapes_areAddedAsMembersToBaseTypeShape() { ShapeModel baseTypeShape = intermediateModel.getShapes().get("BaseType"); List<MemberModel> baseTypeShapeMembers = baseTypeShape.getMembers(); List<String> memberNames = new ArrayList<>(); for (MemberModel member: baseTypeShapeMembers) { memberNames.add(member.getName()); } assertThat(memberNames).contains("CustomShape1","CustomShape2"); } }
3,309
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/BaseExceptionClassSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; public class BaseExceptionClassSpecTest { private static IntermediateModel intermediateModel; @BeforeAll public static void setUp() throws IOException { File serviceModelFile = new File(AwsModelSpecTest.class.getResource("service-2.json").getFile()); File customizationConfigFile = new File(AwsModelSpecTest.class .getResource("customization.config") .getFile()); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile)) .customizationConfig(ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile)) .build()) .build(); } @Test public void testGeneration() { BaseExceptionClass spec = new BaseExceptionClass(intermediateModel); assertThat(spec, generatesTo("baseserviceexception.java")); } }
3,310
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/DeprecatedNameTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import java.io.File; import org.junit.Test; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; public class DeprecatedNameTest { @Test(expected = IllegalStateException.class) public void throwsOnListDeprecation() { runTest("listdeprecationfailure"); } @Test(expected = IllegalStateException.class) public void throwsOnMapDeprecation() { runTest("mapdeprecationfailure"); } @Test(expected = IllegalStateException.class) public void throwsOnEnumDeprecation() { runTest("enumdeprecationfailure"); } private void runTest(String testName) { File serviceModelFile = new File(getClass().getResource("./deprecatedname/" + testName + ".json").getFile()); File customizationConfigFile = new File(getClass() .getResource("./deprecatedname/" + testName + ".customization") .getFile()); ServiceModel serviceModel = ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile); CustomizationConfig basicConfig = ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile); new IntermediateModelBuilder( C2jModels.builder() .serviceModel(serviceModel) .customizationConfig(basicConfig) .build()) .build(); } }
3,311
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/AwsModelSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Locale; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; @RunWith(Parameterized.class) public class AwsModelSpecTest { private static IntermediateModel intermediateModel; private final ShapeModel shapeModel; @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> data() { invokeSafely(AwsModelSpecTest::setUp); return intermediateModel.getShapes().values().stream().map(shape -> new Object[] { shape }).collect(toList()); } public AwsModelSpecTest(ShapeModel shapeModel) { this.shapeModel = shapeModel; } @Test public void basicGeneration() { AwsServiceModel actual = new AwsServiceModel(intermediateModel, shapeModel); assertThat(actual, generatesTo(referenceFileForShape())); } private String referenceFileForShape() { return shapeModel.getShapeName().toLowerCase(Locale.ENGLISH) + ".java"; } private static void setUp() throws IOException { File serviceModelFile = new File(AwsModelSpecTest.class.getResource("service-2.json").getFile()); File customizationConfigFile = new File(AwsModelSpecTest.class .getResource("customization.config") .getFile()); ServiceModel serviceModel = ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile); CustomizationConfig basicConfig = ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(serviceModel) .customizationConfig(basicConfig) .build()) .build(); } }
3,312
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/XmlNamespaceModelTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Locale; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; @RunWith(Parameterized.class) public class XmlNamespaceModelTest { private static IntermediateModel intermediateModel; private final ShapeModel shapeModel; @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> data() { invokeSafely(XmlNamespaceModelTest::setUp); return intermediateModel.getShapes().values().stream().map(shape -> new Object[] { shape }).collect(toList()); } public XmlNamespaceModelTest(ShapeModel shapeModel) { this.shapeModel = shapeModel; } private static void setUp() throws IOException { File serviceModelFile = new File(XmlNamespaceModelTest.class.getResource("xmlnamespace/service-2.json") .getFile()); File configFile = new File(XmlNamespaceModelTest.class .getResource("xmlnamespace/customization.config") .getFile()); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile)) .customizationConfig(ModelLoaderUtils.loadModel(CustomizationConfig.class, configFile)) .build()) .build(); } @Test public void basicGeneration() { assertThat(new AwsServiceModel(intermediateModel, shapeModel), generatesTo("./xmlnamespace/" + referenceFileForShape())); } private String referenceFileForShape() { return shapeModel.getShapeName().toLowerCase(Locale.ENGLISH) + ".java"; } }
3,313
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/AwsServiceBaseRequestSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Optional; import java.util.regex.Pattern; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; public class AwsServiceBaseRequestSpecTest { private static IntermediateModel intermediateModel; @BeforeAll public static void setUp() throws IOException { File serviceModelFile = new File(AwsModelSpecTest.class.getResource("service-2.json").getFile()); File customizationConfigFile = new File(AwsModelSpecTest.class .getResource("customization.config") .getFile()); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile)) .customizationConfig(ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile)) .build()) .build(); } @Test void testGeneration() { AwsServiceBaseRequestSpec spec = new AwsServiceBaseRequestSpec(intermediateModel); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); } @Test void buildJavaFile_memberRequiredByShape_addsTraitToGeneratedCode() { String requestShapeName = "QueryParameterOperationRequest"; String queryParamName = "QueryParamOne"; ShapeModel requestShapeModel = intermediateModel.getShapes().get(requestShapeName); AwsServiceModel spec = new AwsServiceModel(intermediateModel, requestShapeModel); String codeString = PoetUtils.buildJavaFile(spec).toString(); String uploadIdDeclarationString = findTraitDeclarationString(codeString, queryParamName).get(); Assertions.assertThat(uploadIdDeclarationString).contains("RequiredTrait.create()"); } @Test void buildJavaFile_memberNotRequiredByShape_doesNotAddTraitToGeneratedCode() { String requestShapeName = "QueryParameterOperationRequest"; String queryParamName = "QueryParamTwo"; ShapeModel requestShapeModel = intermediateModel.getShapes().get(requestShapeName); AwsServiceModel spec = new AwsServiceModel(intermediateModel, requestShapeModel); String codeString = PoetUtils.buildJavaFile(spec).toString(); String uploadIdDeclarationString = findTraitDeclarationString(codeString, queryParamName).get(); Assertions.assertThat(uploadIdDeclarationString).doesNotContain("RequiredTrait.create()"); } private static Optional<String> findTraitDeclarationString(String javaFileString, String fieldName) { return Arrays.stream(Pattern.compile("\n\n").split(javaFileString)) .filter(block -> block.contains(fieldName)) .filter(block -> block.contains("traits")) .findFirst(); } }
3,314
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/ServiceClientConfigurationBuilderSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import java.io.File; import java.io.IOException; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; public class ServiceClientConfigurationBuilderSpecTest { private static IntermediateModel intermediateModel; @BeforeAll public static void setUp() throws IOException { File serviceModelFile = new File(AwsModelSpecTest.class.getResource("service-2.json").getFile()); File customizationConfigFile = new File(AwsModelSpecTest.class .getResource("customization.config") .getFile()); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile)) .customizationConfig(ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile)) .build()) .build(); } @Test public void testGeneration() { ServiceClientConfigurationBuilderClass spec = new ServiceClientConfigurationBuilderClass(intermediateModel); MatcherAssert.assertThat(spec, generatesTo("serviceclientconfiguration-builder.java")); } }
3,315
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/TestMemberModels.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; class TestMemberModels { private final IntermediateModel intermediateModel; private Map<String, MemberModel> shapeToMemberMap; public TestMemberModels(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; } /** * Returns a mapping of c2jshapes to a single MemberModel in the intermediate model. * * @return */ public Map<String, MemberModel> shapeToMemberMap() { if (shapeToMemberMap == null) { shapeToMemberMap = new HashMap<>(); intermediateModel.getShapes().values().stream() .flatMap(s -> s.getMembers().stream()) .forEach(m -> shapeToMemberMap.put(m.getC2jShape(), m)); } return shapeToMemberMap; } }
3,316
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/model/ModelCopierSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.model; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.stream.Collectors; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; @RunWith(Parameterized.class) public class ModelCopierSpecTest { private static File serviceModelFile; private static IntermediateModel intermediateModel; private static TestMemberModels testMemberModels; private final ClassSpec spec; private final String specName; private static void setUp() throws URISyntaxException, IOException { serviceModelFile = new File(AwsModelSpecTest.class .getResource("service-2.json") .getFile()); File customizationConfigFile = new File(AwsModelSpecTest.class .getResource("customization.config") .getFile()); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile)) .customizationConfig(ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile)) .build()) .build(); testMemberModels = new TestMemberModels(intermediateModel); } @Parameterized.Parameters(name = "{1}") public static Collection<Object[]> data() { invokeSafely(ModelCopierSpecTest::setUp); return new ServiceModelCopiers(intermediateModel).copierSpecs().stream() .map(spec -> new Object[] { spec, spec.className().simpleName().toLowerCase(Locale.ENGLISH) }) .collect(toList()); } public ModelCopierSpecTest(ClassSpec spec, String specName) { this.spec = spec; this.specName = specName; } @Test public void basicGeneration() { assertThat(spec, generatesTo(specName + ".java")); } @Test public void doesNotReturnACopierForImmutableTypes() { ServiceModelCopiers copiers = new ServiceModelCopiers(intermediateModel); // Find members that are not Maps, Lists, Dates, or SdkBytes List<MemberModel> immutableMembers = testMemberModels.shapeToMemberMap().values().stream() .filter(m -> !(m.isList() || m.isMap())) .filter(m -> !(m.getVariable().getSimpleType().equals("Date"))) .filter(m -> !(m.getVariable().getSimpleType().equals("SdkBytes"))) .collect(Collectors.toList()); // Quick sanity check to ensure we're actually testing something assertThat(immutableMembers.size(), is(greaterThan(0))); immutableMembers.forEach(m -> assertThat(copiers.copierClassFor(m), is(equalTo(Optional.empty())))); } }
3,317
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/rules/EndpointProviderInterfaceSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.rules; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.ClientTestModels; public class EndpointProviderInterfaceSpecTest { @Test public void endpointProviderInterface() { ClassSpec endpointProviderInterfaceSpec = new EndpointProviderInterfaceSpec(ClientTestModels.queryServiceModels()); assertThat(endpointProviderInterfaceSpec, generatesTo("endpoint-provider-interface.java")); } @Test public void endpointParameters() { ClassSpec endpointParametersClassSpec = new EndpointParametersClassSpec(ClientTestModels.queryServiceModels()); assertThat(endpointParametersClassSpec, generatesTo("endpoint-parameters.java")); } }
3,318
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/rules/EndpointRulesClientTestSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.rules; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.ClientTestModels; public class EndpointRulesClientTestSpecTest { @Test public void endpointRulesTestClass() { ClassSpec endpointProviderSpec = new EndpointRulesClientTestSpec(ClientTestModels.queryServiceModels()); assertThat(endpointProviderSpec, generatesTo("endpoint-rules-test-class.java")); } }
3,319
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/rules/RequestEndpointProviderInterceptorSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.rules; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.ClientTestModels; public class RequestEndpointProviderInterceptorSpecTest { @Test public void requestSetEndpointInterceptorClass() { ClassSpec endpointProviderInterceptor = new RequestEndpointInterceptorSpec(ClientTestModels.queryServiceModels()); assertThat(endpointProviderInterceptor, generatesTo("request-set-endpoint-interceptor.java")); } }
3,320
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/rules/EndpointProviderClassSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.rules; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.ClientTestModels; public class EndpointProviderClassSpecTest { @Test public void endpointProviderClass() { ClassSpec endpointProviderSpec = new EndpointProviderSpec(ClientTestModels.queryServiceModels()); assertThat(endpointProviderSpec, generatesTo("endpoint-provider-class.java")); } }
3,321
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/rules/EndpointResolverInterceptorSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.rules; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.ClientTestModels; public class EndpointResolverInterceptorSpecTest { @Test public void endpointResolverInterceptorClass() { ClassSpec endpointProviderInterceptor = new EndpointResolverInterceptorSpec(getModel(true)); assertThat(endpointProviderInterceptor, generatesTo("endpoint-resolve-interceptor.java")); } // TODO(post-sra-identity-auth): This can be deleted when useSraAuth is removed @Test public void endpointResolverInterceptorClass_preSra() { ClassSpec endpointProviderInterceptor = new EndpointResolverInterceptorSpec(getModel(false)); assertThat(endpointProviderInterceptor, generatesTo("endpoint-resolve-interceptor-preSra.java")); } private static IntermediateModel getModel(boolean useSraAuth) { IntermediateModel model = ClientTestModels.queryServiceModels(); model.getCustomizationConfig().setUseSraAuth(useSraAuth); return model; } }
3,322
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/rules/ClientContextParamsClassSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.rules; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.ClientTestModels; public class ClientContextParamsClassSpecTest { @Test public void clientContextParams() { ClassSpec endpointProviderInterfaceSpec = new ClientContextParamsClassSpec(ClientTestModels.queryServiceModels()); assertThat(endpointProviderInterfaceSpec, generatesTo("client-context-params.java")); } }
3,323
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/builder/BuilderClassTestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.builder; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import java.util.function.Function; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; public class BuilderClassTestUtils { static void validateGeneration(Function<IntermediateModel, ClassSpec> generatorConstructor, IntermediateModel model, String expectedClassName) { assertThat(generatorConstructor.apply(model), generatesTo(expectedClassName)); } }
3,324
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/builder/AsyncClientBuilderInterfaceTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.builder; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.builder.BuilderClassTestUtils.validateGeneration; import org.junit.jupiter.api.Test; /** * Validate AsyncClientBuilderInterface generation. */ public class AsyncClientBuilderInterfaceTest { @Test public void asyncClientBuilderInterface() { validateGeneration(AsyncClientBuilderInterface::new, restJsonServiceModels(), "test-async-client-builder-interface.java"); } }
3,325
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/builder/BaseClientBuilderInterfaceTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.builder; import static software.amazon.awssdk.codegen.poet.ClientTestModels.bearerAuthServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.composedClientJsonServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.builder.BuilderClassTestUtils.validateGeneration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; /** * Validate BaseClientBuilderInterface generation. */ public class BaseClientBuilderInterfaceTest { @Test public void baseClientBuilderInterface() { validateBaseClientBuilderInterfaceGeneration(restJsonServiceModels(), "test-client-builder-interface.java"); } @Test public void baseClientBuilderInterfaceWithBearerAuth() { validateBaseClientBuilderInterfaceGeneration(bearerAuthServiceModels(), "test-bearer-auth-client-builder-interface.java"); } @Test public void syncHasCrossRegionAccessEnabledPropertyBuilderClass() { validateBaseClientBuilderInterfaceGeneration(composedClientJsonServiceModels(), "test-customcontextparams-sync-client-builder-class.java"); } private void validateBaseClientBuilderInterfaceGeneration(IntermediateModel model, String expectedClassName) { validateGeneration(BaseClientBuilderInterface::new, model, expectedClassName); } }
3,326
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/builder/BaseClientBuilderClassTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.builder; import static software.amazon.awssdk.codegen.poet.ClientTestModels.bearerAuthServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.composedClientJsonServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.internalConfigModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.operationWithNoAuth; import static software.amazon.awssdk.codegen.poet.ClientTestModels.queryServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.queryServiceModelsEndpointAuthParamsWithAllowList; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.serviceWithNoAuth; import static software.amazon.awssdk.codegen.poet.builder.BuilderClassTestUtils.validateGeneration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; /** * Validate BaseClientBuilderClass generation. */ public class BaseClientBuilderClassTest { @Test public void baseClientBuilderClass() { validateBaseClientBuilderClassGeneration(restJsonServiceModels(), "test-client-builder-class.java"); } @Test public void baseClientBuilderClassWithBearerAuth() { validateBaseClientBuilderClassGeneration(bearerAuthServiceModels(), "test-bearer-auth-client-builder-class.java"); } @Test public void baseClientBuilderClassWithNoAuthOperation() { validateBaseClientBuilderClassGeneration(operationWithNoAuth(), "test-no-auth-ops-client-builder-class.java"); } @Test public void baseClientBuilderClassWithNoAuthService() { validateBaseClientBuilderClassGeneration(serviceWithNoAuth(), "test-no-auth-service-client-builder-class.java"); } @Test public void baseClientBuilderClassWithInternalUserAgent() { validateBaseClientBuilderClassGeneration(internalConfigModels(), "test-client-builder-internal-defaults-class.java"); } @Test public void baseQueryClientBuilderClass() { validateBaseClientBuilderClassGeneration(queryServiceModels(), "test-query-client-builder-class.java"); } @Test public void baseClientBuilderClassWithEndpointsAuthParams() { validateBaseClientBuilderClassGeneration(queryServiceModelsEndpointAuthParamsWithAllowList(), "test-client-builder-endpoints-auth-params.java"); } @Test public void syncComposedDefaultClientBuilderClass() { validateBaseClientBuilderClassGeneration(composedClientJsonServiceModels(), "test-composed-sync-default-client-builder.java"); } private void validateBaseClientBuilderClassGeneration(IntermediateModel model, String expectedClassName) { model.getCustomizationConfig().setUseSraAuth(false); validateGeneration(BaseClientBuilderClass::new, model, expectedClassName); model.getCustomizationConfig().setUseSraAuth(true); validateGeneration(BaseClientBuilderClass::new, model, "sra/" + expectedClassName); } }
3,327
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/builder/SyncClientBuilderClassTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.builder; import static software.amazon.awssdk.codegen.poet.ClientTestModels.composedClientJsonServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.builder.BuilderClassTestUtils.validateGeneration; import org.junit.jupiter.api.Test; /** * Validate SyncClientBuilderClass generation. */ public class SyncClientBuilderClassTest { @Test public void syncClientBuilderClass() { validateGeneration(SyncClientBuilderClass::new, restJsonServiceModels(), "test-sync-client-builder-class.java"); } @Test public void syncComposedClientBuilderClass() { validateGeneration(SyncClientBuilderClass::new, composedClientJsonServiceModels(), "test-composed-sync-client-builder-class.java"); } }
3,328
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/builder/AsyncClientBuilderClassTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.builder; import static software.amazon.awssdk.codegen.poet.ClientTestModels.composedClientJsonServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.builder.BuilderClassTestUtils.validateGeneration; import org.junit.jupiter.api.Test; /** * Validate AsyncClientBuilderClass generation. */ public class AsyncClientBuilderClassTest { @Test public void asyncClientBuilderClass() { validateGeneration(AsyncClientBuilderClass::new, restJsonServiceModels(), "test-async-client-builder-class.java"); } @Test public void asyncComposedClientBuilderClass() { validateGeneration(AsyncClientBuilderClass::new, composedClientJsonServiceModels(), "test-composed-async-client-builder-class.java"); } }
3,329
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/builder/SyncClientBuilderInterfaceTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.builder; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.builder.BuilderClassTestUtils.validateGeneration; import org.junit.jupiter.api.Test; /** * Validate SyncClientBuilderInterface generation. */ public class SyncClientBuilderInterfaceTest { @Test public void syncClientBuilderInterface() { validateGeneration(SyncClientBuilderInterface::new, restJsonServiceModels(), "test-sync-client-builder-interface.java"); } }
3,330
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/transform/CustomDefaultValueSupplier.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.transform; import java.util.function.Supplier; public class CustomDefaultValueSupplier { /** * Value that indicates the current account. */ private static final String VALUE = "BLAHBLAH"; private static final Supplier<String> INSTANCE = () -> VALUE; private CustomDefaultValueSupplier() { } public static Supplier<String> getInstance() { return INSTANCE; } }
3,331
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/transform/MarshallerSpecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.transform; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Locale; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; @RunWith(Parameterized.class) public class MarshallerSpecTest { private static IntermediateModel intermediateModel; private final ShapeModel shapeModel; @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> data() { invokeSafely(MarshallerSpecTest::setUp); return intermediateModel.getShapes().values().stream() .filter(shape -> "Request".equals(shape.getType()) || shape.isEvent()) .map(shape -> new Object[] {shape}).collect(toList()); } public MarshallerSpecTest(ShapeModel shapeModel) { this.shapeModel = shapeModel; } @Test public void basicGeneration() { assertThat(new MarshallerSpec(intermediateModel, shapeModel), generatesTo(referenceFileForShape())); } private String referenceFileForShape() { return shapeModel.getShapeName().toLowerCase(Locale.ENGLISH) + "marshaller.java"; } private static void setUp() throws IOException { File serviceModelFile = new File(MarshallerSpecTest.class.getResource("service-2.json").getFile()); File customizationConfigFile = new File(MarshallerSpecTest.class .getResource("customization.config") .getFile()); intermediateModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, serviceModelFile)) .customizationConfig(ModelLoaderUtils.loadModel(CustomizationConfig.class, customizationConfigFile)) .build()) .build(); } }
3,332
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/client/SyncClientInterfaceTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.client; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.Test; import software.amazon.awssdk.codegen.poet.ClassSpec; public class SyncClientInterfaceTest { @Test public void syncClientInterface() { ClassSpec syncClientInterface = new SyncClientInterface(restJsonServiceModels()); assertThat(syncClientInterface, generatesTo("test-json-client-interface.java")); } }
3,333
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/client/DelegatingAsyncClientClassTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.client; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.Test; public class DelegatingAsyncClientClassTest { @Test public void delegatingAsyncClientClass() { DelegatingAsyncClientClass asyncClientDecoratorAbstractClass = new DelegatingAsyncClientClass(restJsonServiceModels()); assertThat(asyncClientDecoratorAbstractClass, generatesTo("test-abstract-async-client-class.java")); } }
3,334
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/client/SyncClientClassTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.client; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.ClientTestModels.awsQueryCompatibleJsonServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.customContentTypeModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.endpointDiscoveryModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.queryServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.xmlServiceModels; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.Test; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; public class SyncClientClassTest { @Test public void syncClientClassRestJson() { SyncClientClass syncClientClass = createSyncClientClass(restJsonServiceModels(), false); assertThat(syncClientClass, generatesTo("test-json-client-class.java")); SyncClientClass sraSyncClientClass = createSyncClientClass(restJsonServiceModels(), true); assertThat(sraSyncClientClass, generatesTo("sra/test-json-client-class.java")); } @Test public void syncClientClassQuery() { SyncClientClass syncClientClass = createSyncClientClass(queryServiceModels(), false); assertThat(syncClientClass, generatesTo("test-query-client-class.java")); SyncClientClass sraSyncClientClass = createSyncClientClass(queryServiceModels(), true); assertThat(sraSyncClientClass, generatesTo("sra/test-query-client-class.java")); } @Test public void syncClientClassAwsQueryCompatibleJson() { SyncClientClass syncClientClass = createSyncClientClass(awsQueryCompatibleJsonServiceModels()); assertThat(syncClientClass, generatesTo("test-aws-query-compatible-json-sync-client-class.java")); } @Test public void syncClientClassXml() { SyncClientClass syncClientClass = createSyncClientClass(xmlServiceModels(), false); assertThat(syncClientClass, generatesTo("test-xml-client-class.java")); SyncClientClass sraSyncClientClass = createSyncClientClass(xmlServiceModels(), true); assertThat(sraSyncClientClass, generatesTo("sra/test-xml-client-class.java")); } @Test public void syncClientEndpointDiscovery() { ClassSpec syncClientEndpointDiscovery = createSyncClientClass(endpointDiscoveryModels()); assertThat(syncClientEndpointDiscovery, generatesTo("test-endpoint-discovery-sync.java")); } @Test public void syncClientCustomServiceMetaData() { ClassSpec syncClientCustomServiceMetaData = createSyncClientClass(customContentTypeModels()); assertThat(syncClientCustomServiceMetaData, generatesTo("test-customservicemetadata-sync.java")); } private SyncClientClass createSyncClientClass(IntermediateModel model) { return new SyncClientClass(GeneratorTaskParams.create(model, "sources/", "tests/", "resources/")); } private SyncClientClass createSyncClientClass(IntermediateModel model, boolean useSraAuth) { model.getCustomizationConfig().setUseSraAuth(useSraAuth); return createSyncClientClass(model); } }
3,335
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/client/AsyncClientClassTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.client; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.ClientTestModels.awsJsonServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.awsQueryCompatibleJsonServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.customContentTypeModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.endpointDiscoveryModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.queryServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.ClientTestModels.xmlServiceModels; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.Test; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; public class AsyncClientClassTest { @Test public void asyncClientClassRestJson() { AsyncClientClass asyncClientClass = createAsyncClientClass(restJsonServiceModels(), false); assertThat(asyncClientClass, generatesTo("test-json-async-client-class.java")); AsyncClientClass sraAsyncClientClass = createAsyncClientClass(restJsonServiceModels(), true); assertThat(sraAsyncClientClass, generatesTo("sra/test-json-async-client-class.java")); } @Test public void asyncClientClassQuery() { AsyncClientClass asyncClientClass = createAsyncClientClass(queryServiceModels(), false); assertThat(asyncClientClass, generatesTo("test-query-async-client-class.java")); AsyncClientClass sraAsyncClientClass = createAsyncClientClass(queryServiceModels(), true); assertThat(sraAsyncClientClass, generatesTo("sra/test-query-async-client-class.java")); } @Test public void asyncClientClassAwsJson() { AsyncClientClass asyncClientClass = createAsyncClientClass(awsJsonServiceModels(), false); assertThat(asyncClientClass, generatesTo("test-aws-json-async-client-class.java")); AsyncClientClass sraAsyncClientClass = createAsyncClientClass(awsJsonServiceModels(), true); assertThat(sraAsyncClientClass, generatesTo("sra/test-aws-json-async-client-class.java")); } @Test public void asyncClientClassAwsQueryCompatibleJson() { AsyncClientClass asyncClientClass = createAsyncClientClass(awsQueryCompatibleJsonServiceModels()); assertThat(asyncClientClass, generatesTo("test-aws-query-compatible-json-async-client-class.java")); } @Test public void asyncClientClassXml() { AsyncClientClass asyncClientClass = createAsyncClientClass(xmlServiceModels(), false); assertThat(asyncClientClass, generatesTo("test-xml-async-client-class.java")); AsyncClientClass sraAsyncClientClass = createAsyncClientClass(xmlServiceModels(), true); assertThat(sraAsyncClientClass, generatesTo("sra/test-xml-async-client-class.java")); } @Test public void asyncClientEndpointDiscovery() { AsyncClientClass asyncClientEndpointDiscovery = createAsyncClientClass(endpointDiscoveryModels()); assertThat(asyncClientEndpointDiscovery, generatesTo("test-endpoint-discovery-async.java")); } @Test public void asyncClientCustomServiceMetaData() { AsyncClientClass asyncClientCustomServiceMetaData = createAsyncClientClass(customContentTypeModels()); assertThat(asyncClientCustomServiceMetaData, generatesTo("test-customservicemetadata-async.java")); } private AsyncClientClass createAsyncClientClass(IntermediateModel model) { return new AsyncClientClass(GeneratorTaskParams.create(model, "sources/", "tests/", "resources/")); } private AsyncClientClass createAsyncClientClass(IntermediateModel model, boolean useSraAuth) { model.getCustomizationConfig().setUseSraAuth(useSraAuth); return createAsyncClientClass(model); } }
3,336
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/client/DelegatingSyncClientClassTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.client; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.Test; public class DelegatingSyncClientClassTest { @Test public void delegatingSyncClientClass() { DelegatingSyncClientClass syncClientDecoratorAbstractClass = new DelegatingSyncClientClass(restJsonServiceModels()); assertThat(syncClientDecoratorAbstractClass, generatesTo("test-abstract-sync-client-class.java")); } }
3,337
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/poet/client/AsyncClientInterfaceTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.client; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.codegen.poet.ClientTestModels.restJsonServiceModels; import static software.amazon.awssdk.codegen.poet.PoetMatchers.generatesTo; import org.junit.Test; import software.amazon.awssdk.codegen.poet.ClassSpec; public class AsyncClientInterfaceTest { @Test public void asyncClientInterface() { ClassSpec asyncClientInterface = new AsyncClientInterface(restJsonServiceModels()); assertThat(asyncClientInterface, generatesTo("test-json-async-client-interface.java")); } }
3,338
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/utils/AuthUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.utils; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.service.AuthType; public class AuthUtilsTest { @ParameterizedTest @MethodSource("serviceValues") public void testIfServiceHasBearerAuth(AuthType serviceAuthType, List<AuthType> opAuthTypes, Boolean expectedResult) { IntermediateModel model = modelWith(serviceAuthType); model.setOperations(createOperations(opAuthTypes)); assertThat(AuthUtils.usesBearerAuth(model)).isEqualTo(expectedResult); } private static Stream<Arguments> serviceValues() { List<AuthType> oneBearerOp = Arrays.asList(AuthType.BEARER, AuthType.S3V4, AuthType.NONE); List<AuthType> noBearerOp = Arrays.asList(AuthType.S3V4, AuthType.S3V4, AuthType.NONE); return Stream.of(Arguments.of(AuthType.BEARER, noBearerOp, true), Arguments.of(AuthType.BEARER, oneBearerOp, true), Arguments.of(AuthType.S3V4, noBearerOp, false), Arguments.of(AuthType.S3V4, oneBearerOp, true)); } @ParameterizedTest @MethodSource("awsAuthServiceValues") public void testIfServiceHasAwsAuthAuth(AuthType serviceAuthType, List<AuthType> opAuthTypes, Boolean expectedResult) { IntermediateModel model = modelWith(serviceAuthType); model.setOperations(createOperations(opAuthTypes)); assertThat(AuthUtils.usesAwsAuth(model)).isEqualTo(expectedResult); } private static Stream<Arguments> awsAuthServiceValues() { List<AuthType> oneAwsAuthOp = Arrays.asList(AuthType.V4, AuthType.BEARER, AuthType.NONE); List<AuthType> noAwsAuthOp = Arrays.asList(AuthType.BEARER, AuthType.NONE); return Stream.of(Arguments.of(AuthType.BEARER, oneAwsAuthOp, true), Arguments.of(AuthType.BEARER, noAwsAuthOp, false), Arguments.of(AuthType.V4, oneAwsAuthOp, true), Arguments.of(AuthType.V4, noAwsAuthOp, true)); } @ParameterizedTest @MethodSource("opValues") public void testIfOperationIsBearerAuth(AuthType serviceAuthType, AuthType opAuthType, Boolean expectedResult) { IntermediateModel model = modelWith(serviceAuthType); OperationModel opModel = opModelWith(opAuthType); assertThat(AuthUtils.isOpBearerAuth(model, opModel)).isEqualTo(expectedResult); } private static Stream<Arguments> opValues() { return Stream.of(Arguments.of(AuthType.BEARER, AuthType.BEARER, true), Arguments.of(AuthType.BEARER, AuthType.S3V4, false), Arguments.of(AuthType.BEARER, AuthType.NONE, true), Arguments.of(AuthType.BEARER, null, true), Arguments.of(AuthType.S3V4, AuthType.BEARER, true), Arguments.of(AuthType.S3V4, AuthType.S3V4, false), Arguments.of(AuthType.S3V4, AuthType.NONE, false), Arguments.of(AuthType.S3V4, null, false)); } private static OperationModel opModelWith(AuthType authType) { OperationModel opModel = new OperationModel(); opModel.setAuthType(authType); return opModel; } private static IntermediateModel modelWith(AuthType authType) { IntermediateModel model = new IntermediateModel(); Metadata metadata = new Metadata(); metadata.setAuthType(authType); model.setMetadata(metadata); return model; } private static Map<String, OperationModel> createOperations(List<AuthType> opAuthTypes) { return IntStream.range(0, opAuthTypes.size()) .boxed() .collect(Collectors.toMap(i -> "Op" + i, i -> opModelWith(opAuthTypes.get(i)))); } }
3,339
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/naming/DefaultNamingStrategyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.naming; import static java.util.Collections.singletonList; 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.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.config.customization.UnderscoresInNameBehavior; import software.amazon.awssdk.codegen.model.config.customization.ShareModelConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.Member; import software.amazon.awssdk.codegen.model.service.ServiceMetadata; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Shape; @RunWith(MockitoJUnitRunner.class) public class DefaultNamingStrategyTest { private CustomizationConfig customizationConfig = CustomizationConfig.create(); private ServiceModel serviceModel = mock(ServiceModel.class); @Mock private Map<String, Shape> mockShapeMap; @Mock private Shape mockParentShape; @Mock private Shape mockShape; @Mock private Shape mockStringShape; @Mock private Member member; @Mock private ServiceMetadata serviceMetadata; private DefaultNamingStrategy strat = new DefaultNamingStrategy(serviceModel, customizationConfig); @Before public void setUp() { } @Test public void enumNamesConvertCorrectly() { validateConversion("Twilio-Sms", "TWILIO_SMS"); validateConversion("t2.micro", "T2_MICRO"); validateConversion("GreaterThanThreshold", "GREATER_THAN_THRESHOLD"); validateConversion("INITIALIZED", "INITIALIZED"); validateConversion("GENERIC_EVENT", "GENERIC_EVENT"); validateConversion("WINDOWS_2012", "WINDOWS_2012"); validateConversion("ec2:spot-fleet-request:TargetCapacity", "EC2_SPOT_FLEET_REQUEST_TARGET_CAPACITY"); validateConversion("elasticmapreduce:instancegroup:InstanceCount", "ELASTICMAPREDUCE_INSTANCEGROUP_INSTANCE_COUNT"); validateConversion("application/vnd.amazonaws.card.generic", "APPLICATION_VND_AMAZONAWS_CARD_GENERIC"); validateConversion("IPV4", "IPV4"); validateConversion("ipv4", "IPV4"); validateConversion("IPv4", "IP_V4"); validateConversion("ipV4", "IP_V4"); validateConversion("IPMatch", "IP_MATCH"); validateConversion("S3", "S3"); validateConversion("EC2Instance", "EC2_INSTANCE"); validateConversion("aws.config", "AWS_CONFIG"); validateConversion("AWS::EC2::CustomerGateway", "AWS_EC2_CUSTOMER_GATEWAY"); validateConversion("application/pdf", "APPLICATION_PDF"); validateConversion("ADConnector", "AD_CONNECTOR"); validateConversion("MS-CHAPv1", "MS_CHAP_V1"); validateConversion("One-Way: Outgoing", "ONE_WAY_OUTGOING"); validateConversion("scram_sha_1", "SCRAM_SHA_1"); validateConversion("EC_prime256v1", "EC_PRIME256_V1"); validateConversion("EC_PRIME256V1", "EC_PRIME256_V1"); validateConversion("EC2v11.4", "EC2_V11_4"); validateConversion("nodejs4.3-edge", "NODEJS4_3_EDGE"); validateConversion("BUILD_GENERAL1_SMALL", "BUILD_GENERAL1_SMALL"); validateConversion("SSE_S3", "SSE_S3"); validateConversion("http1.1", "HTTP1_1"); validateConversion("T100", "T100"); validateConversion("s3:ObjectCreated:*", "S3_OBJECT_CREATED"); validateConversion("s3:ObjectCreated:Put", "S3_OBJECT_CREATED_PUT"); validateConversion("TLSv1", "TLS_V1"); validateConversion("TLSv1.2", "TLS_V1_2"); validateConversion("us-east-1", "US_EAST_1"); validateConversion("io1", "IO1"); validateConversion("testNESTEDAcronym", "TEST_NESTED_ACRONYM"); validateConversion("IoT", "IOT"); validateConversion("textORcsv", "TEXT_OR_CSV"); validateConversion("__foo___", "FOO"); validateConversion("TEST__FOO", "TEST_FOO"); validateConversion("IFrame", "I_FRAME"); validateConversion("TPain", "T_PAIN"); validateConversion("S3EC2", "S3_EC2"); validateConversion("S3Ec2", "S3_EC2"); validateConversion("s3Ec2", "S3_EC2"); validateConversion("s3ec2", "S3_EC2"); } @Test public void test_GetFluentSetterMethodName_NoEnum() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShape.getEnumValues()).thenReturn(null); when(mockShape.getType()).thenReturn("foo"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethod"); } @Test public void test_GetFluentSetterMethodName_NoEnum_WithList() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShapeMap.get(eq("MockStringShape"))).thenReturn(mockStringShape); when(mockShape.getEnumValues()).thenReturn(null); when(mockShape.getType()).thenReturn("list"); when(mockShape.getListMember()).thenReturn(member); when(mockStringShape.getEnumValues()).thenReturn(null); when(mockStringShape.getType()).thenReturn("string"); when(member.getShape()).thenReturn("MockStringShape"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethod"); } @Test public void test_GetFluentSetterMethodName_WithEnumShape_NoListOrMap() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShape.getEnumValues()).thenReturn(new ArrayList<>()); when(mockShape.getType()).thenReturn("foo"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethod"); } @Test public void test_GetFluentSetterMethodName_WithEnumShape_WithList() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShapeMap.get(eq("MockStringShape"))).thenReturn(mockStringShape); when(mockShape.getEnumValues()).thenReturn(null); when(mockShape.getType()).thenReturn("list"); when(mockShape.getListMember()).thenReturn(member); when(mockStringShape.getEnumValues()).thenReturn(Arrays.asList("Enum1", "Enum2")); when(mockStringShape.getType()).thenReturn("string"); when(member.getShape()).thenReturn("MockStringShape"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethodWithStrings"); } @Test public void nonSharedModel_packageName() { String serviceName = "foo"; DefaultNamingStrategy strategy = new DefaultNamingStrategy(serviceModel, CustomizationConfig.create()); assertThat(strategy.getClientPackageName(serviceName)).isEqualTo("foo"); assertThat(strategy.getPaginatorsPackageName(serviceName)).isEqualTo("foo.paginators"); assertThat(strategy.getSmokeTestPackageName(serviceName)).isEqualTo("foo.smoketests"); assertThat(strategy.getModelPackageName(serviceName)).isEqualTo("foo.model"); assertThat(strategy.getRequestTransformPackageName(serviceName)).isEqualTo("foo.transform"); assertThat(strategy.getTransformPackageName(serviceName)).isEqualTo("foo.transform"); } @Test public void sharedModel_notProvidingPackageName_shouldUseServiceName() { CustomizationConfig config = CustomizationConfig.create(); ShareModelConfig shareModelConfig = new ShareModelConfig(); shareModelConfig.setShareModelWith("foo"); config.setShareModelConfig(shareModelConfig); String serviceName = "bar"; DefaultNamingStrategy customizedModel = new DefaultNamingStrategy(serviceModel, config); assertThat(customizedModel.getClientPackageName(serviceName)).isEqualTo("foo.bar"); assertThat(customizedModel.getPaginatorsPackageName(serviceName)).isEqualTo("foo.bar.paginators"); assertThat(customizedModel.getSmokeTestPackageName(serviceName)).isEqualTo("foo.bar.smoketests"); assertThat(customizedModel.getRequestTransformPackageName(serviceName)).isEqualTo("foo.bar.transform"); // should share the same model and non-request transform packages assertThat(customizedModel.getModelPackageName(serviceName)).isEqualTo("foo.model"); assertThat(customizedModel.getTransformPackageName(serviceName)).isEqualTo("foo.transform"); } @Test public void sharedModel_providingPackageName_shouldUseProvidedpackageName() { CustomizationConfig config = CustomizationConfig.create(); ShareModelConfig shareModelConfig = new ShareModelConfig(); shareModelConfig.setShareModelWith("foo"); shareModelConfig.setPackageName("b"); config.setShareModelConfig(shareModelConfig); String serviceName = "bar"; DefaultNamingStrategy customizedModel = new DefaultNamingStrategy(serviceModel, config); assertThat(customizedModel.getClientPackageName(serviceName)).isEqualTo("foo.b"); assertThat(customizedModel.getPaginatorsPackageName(serviceName)).isEqualTo("foo.b.paginators"); assertThat(customizedModel.getSmokeTestPackageName(serviceName)).isEqualTo("foo.b.smoketests"); assertThat(customizedModel.getRequestTransformPackageName(serviceName)).isEqualTo("foo.b.transform"); // should share the same model and non-request transform packages assertThat(customizedModel.getModelPackageName(serviceName)).isEqualTo("foo.model"); assertThat(customizedModel.getTransformPackageName(serviceName)).isEqualTo("foo.transform"); } @Test public void modelNameShouldHavePascalCase() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn("UnitTestService"); assertThat(strat.getRequestClassName("CAPSTest")).isEqualTo("CapsTestRequest"); assertThat(strat.getExceptionName("CAPSTest")).isEqualTo("CapsTestException"); assertThat(strat.getResponseClassName("CAPSTest")).isEqualTo("CapsTestResponse"); assertThat(strat.getResponseClassName("CAPSByIndex")).isEqualTo("CapsByIndexResponse"); assertThat(strat.getRequestClassName("FollowedByS3")).isEqualTo("FollowedByS3Request"); } @Test public void getServiceName_Uses_ServiceId() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn("Foo"); assertThat(strat.getServiceName()).isEqualTo("Foo"); } @Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdIsNull() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(null); strat.getServiceName(); } @Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdIsEmpty() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(""); strat.getServiceName(); } @Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdHasWhiteSpace() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(" "); strat.getServiceName(); } @Test public void getSdkFieldFieldName_SingleWord() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("foo"))) .isEqualTo("FOO_FIELD"); } @Test public void getSdkFieldFieldName_CamalCaseConvertedToScreamCase() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("fooBar"))) .isEqualTo("FOO_BAR_FIELD"); } @Test public void getSdkFieldFieldName_PascalCaseConvertedToScreamCase() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("FooBar"))) .isEqualTo("FOO_BAR_FIELD"); } private void validateConversion(String input, String expectedOutput) { assertThat(strat.getEnumValueName(input)).isEqualTo(expectedOutput); } @Test public void validateDisallowsUnderscoresWithCustomization() { String invalidName = "foo_bar"; verifyFailure(i -> i.getMetadata().setAsyncBuilderInterface(invalidName)); verifyFailure(i -> i.getMetadata().setSyncBuilderInterface(invalidName)); verifyFailure(i -> i.getMetadata().setAsyncInterface(invalidName)); verifyFailure(i -> i.getMetadata().setSyncInterface(invalidName)); verifyFailure(i -> i.getMetadata().setBaseBuilderInterface(invalidName)); verifyFailure(i -> i.getMetadata().setBaseExceptionName(invalidName)); verifyFailure(i -> i.getOperations().put(invalidName, opModel(o -> o.setOperationName(invalidName)))); verifyFailure(i -> i.getWaiters().put(invalidName, null)); verifyFailure(i -> i.getShapes().put(invalidName, shapeModel(s -> s.setShapeName(invalidName)))); verifyFailure(i -> i.getShapes().put(invalidName, shapeWithMember(m -> m.setBeanStyleGetterMethodName(invalidName)))); verifyFailure(i -> i.getShapes().put(invalidName, shapeWithMember(m -> m.setBeanStyleSetterMethodName(invalidName)))); verifyFailure(i -> i.getShapes().put(invalidName, shapeWithMember(m -> m.setFluentEnumGetterMethodName(invalidName)))); verifyFailure(i -> i.getShapes().put(invalidName, shapeWithMember(m -> m.setFluentEnumSetterMethodName(invalidName)))); verifyFailure(i -> i.getShapes().put(invalidName, shapeWithMember(m -> m.setFluentGetterMethodName(invalidName)))); verifyFailure(i -> i.getShapes().put(invalidName, shapeWithMember(m -> m.setFluentSetterMethodName(invalidName)))); verifyFailure(i -> i.getShapes().put(invalidName, shapeWithMember(m -> m.setEnumType(invalidName)))); } @Test public void validateAllowsUnderscoresWithCustomization() { CustomizationConfig customization = CustomizationConfig.create() .withUnderscoresInShapeNameBehavior(UnderscoresInNameBehavior.ALLOW); NamingStrategy strategy = new DefaultNamingStrategy(serviceModel, customization); Metadata metadata = new Metadata(); metadata.setAsyncBuilderInterface("foo_bar"); IntermediateModel model = new IntermediateModel(); model.setMetadata(metadata); strategy.validateCustomerVisibleNaming(model); } private void verifyFailure(Consumer<IntermediateModel> modelModifier) { IntermediateModel model = new IntermediateModel(); model.setMetadata(new Metadata()); modelModifier.accept(model); assertThatThrownBy(() -> strat.validateCustomerVisibleNaming(model)).isInstanceOf(RuntimeException.class); } private OperationModel opModel(Consumer<OperationModel> operationModifier) { OperationModel model = new OperationModel(); operationModifier.accept(model); return model; } private ShapeModel shapeModel(Consumer<ShapeModel> shapeModifier) { ShapeModel model = new ShapeModel(); shapeModifier.accept(model); return model; } private ShapeModel shapeWithMember(Consumer<MemberModel> memberModifier) { MemberModel model = new MemberModel(); memberModifier.accept(model); return shapeModel(s -> s.setMembers(singletonList(model))); } }
3,340
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/model
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/model/service/HostPrefixProcessorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.model.service; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; import org.junit.Test; public class HostPrefixProcessorTest { @Test public void staticHostLabel() { String hostPrefix = "data-"; HostPrefixProcessor processor = new HostPrefixProcessor(hostPrefix); assertThat(processor.hostWithStringSpecifier(), equalTo("data-")); assertThat(processor.c2jNames(), empty()); } @Test public void inputShapeLabels() { String hostPrefix = "{Bucket}-{AccountId}."; HostPrefixProcessor processor = new HostPrefixProcessor(hostPrefix); assertThat(processor.hostWithStringSpecifier(), equalTo("%s-%s.")); assertThat(processor.c2jNames(), contains("Bucket", "AccountId")); } @Test public void emptyCurlyBraces() { // Pattern should not match the first set of curly braces as there is no characters between them String host = "{}.foo"; HostPrefixProcessor processor = new HostPrefixProcessor(host); assertThat(processor.hostWithStringSpecifier(), equalTo("{}.foo")); assertThat(processor.c2jNames(), empty()); } @Test (expected = IllegalArgumentException.class) public void emptyHost() { new HostPrefixProcessor(""); } @Test (expected = IllegalArgumentException.class) public void nullHost() { new HostPrefixProcessor(null); } }
3,341
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/model
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/model/service/PaginatorDefinitionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.model.service; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; public class PaginatorDefinitionTest { @Test public void isValid_ReturnsFalse_WhenInputToken_IsNullOrEmpty() { PaginatorDefinition paginatorDefinition = new PaginatorDefinition(); assertNull(paginatorDefinition.getInputToken()); assertFalse(paginatorDefinition.isValid()); paginatorDefinition.setInputToken(Collections.emptyList()); assertFalse(paginatorDefinition.isValid()); } @Test public void isValid_ReturnsFalse_WhenOutputToken_IsNullOrEmpty() { PaginatorDefinition paginatorDefinition = new PaginatorDefinition(); assertNull(paginatorDefinition.getOutputToken()); assertFalse(paginatorDefinition.isValid()); paginatorDefinition.setOutputToken(Collections.emptyList()); assertFalse(paginatorDefinition.isValid()); } @Test public void isValid_ReturnsFalse_WhenInputTokenIsPresent_AndOutputTokenIsMissing() { PaginatorDefinition paginatorDefinition = new PaginatorDefinition(); paginatorDefinition.setInputToken(Arrays.asList("inputToken")); assertFalse(paginatorDefinition.isValid()); } @Test public void isValid_ReturnsTrue_WhenBothInputTokenAndOutputToken_ArePresent() { PaginatorDefinition paginatorDefinition = new PaginatorDefinition(); paginatorDefinition.setInputToken(Arrays.asList("inputToken")); paginatorDefinition.setOutputToken(Arrays.asList("foo", "bar")); assertTrue(paginatorDefinition.isValid()); } @Test public void isValid_ReturnsTrue_WhenResultKey_IsNull() { PaginatorDefinition paginatorDefinition = new PaginatorDefinition(); paginatorDefinition.setInputToken(Arrays.asList("inputToken")); paginatorDefinition.setOutputToken(Arrays.asList("foo", "bar")); assertNull(paginatorDefinition.getResultKey()); assertTrue(paginatorDefinition.isValid()); } @Test public void isValid_ReturnsTrue_WhenOutputTokenList_ContainsValidString() { PaginatorDefinition paginatorDefinition = new PaginatorDefinition(); paginatorDefinition.setOutputToken(Arrays.asList("Foo", "Foo.Bar")); paginatorDefinition.setInputToken(Arrays.asList("token")); assertTrue(paginatorDefinition.isValid()); } @Test public void isValid_ReturnsFalse_WhenOutputTokenList_ContainsAListMember() { PaginatorDefinition paginatorDefinition = new PaginatorDefinition(); paginatorDefinition.setOutputToken(Arrays.asList("Contents[-1]")); paginatorDefinition.setInputToken(Arrays.asList("token")); assertFalse(paginatorDefinition.isValid()); } @Test public void isValid_ReturnsTrue_WhenOutputTokenList_ContainsOrCharacter() { PaginatorDefinition paginatorDefinition = new PaginatorDefinition(); paginatorDefinition.setOutputToken(Arrays.asList("NextMarker || Contents")); paginatorDefinition.setInputToken(Arrays.asList("token")); assertFalse(paginatorDefinition.isValid()); } }
3,342
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/model
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/model/intermediate/DocumentationBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.model.intermediate; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.codegen.TestStringUtils.toPlatformLfs; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.docs.DocumentationBuilder; public class DocumentationBuilderTest { @Test public void javadocFormattedCorrectly() { String docs = new DocumentationBuilder() .description("Some service docs") .param("paramOne", "param one docs") .param("paramTwo", "param two docs") .returns("This returns something") .syncThrows("FooException", "Thrown when foo happens") .syncThrows("BarException", "Thrown when bar happens") .tag("sample", "FooService.FooOperation") .see("this thing") .see("this other thing") .build(); assertThat(docs).isEqualTo(toPlatformLfs("Some service docs\n" + "\n" + "@param paramOne param one docs\n" + "@param paramTwo param two docs\n" + "@return This returns something\n" + "@throws FooException Thrown when foo happens\n" + "@throws BarException Thrown when bar happens\n" + "@sample FooService.FooOperation\n" + "@see this thing\n" + "@see this other thing\n")); } /** * For async methods that return a {@link java.util.concurrent.CompletableFuture} no exception is thrown from the method, * instead the future is completed exceptionally with the exception. As such we document this in the @returns section * of the Javadocs rather than having @throws for each exception. */ @Test public void asyncReturns_FormatsExceptionsInUnorderedList() { String docs = new DocumentationBuilder() .description("Some service docs") .param("paramOne", "param one docs") .returns("CompletableFuture of success") .asyncThrows("FooException", "Foo docs") .asyncThrows("BarException", "Bar docs") .build(); assertThat(docs).isEqualTo(toPlatformLfs("Some service docs\n" + "\n" + "@param paramOne param one docs\n" + "@return CompletableFuture of success<br/>\n" + "The CompletableFuture returned by this method can be completed exceptionally with the following exceptions.\n" + "<ul>\n" + "<li>FooException Foo docs</li>\n" + "<li>BarException Bar docs</li>\n" + "</ul>\n")); } @Test public void asyncReturnsWithoutDocsForSuccessReturn_FormatsExceptionsInUnorderedList() { String docs = new DocumentationBuilder() .description("Some service docs") .param("paramOne", "param one docs") .asyncThrows("FooException", "Foo docs") .asyncThrows("BarException", "Bar docs") .build(); assertThat(docs).isEqualTo(toPlatformLfs("Some service docs\n" + "\n" + "@param paramOne param one docs\n" + "@return A CompletableFuture indicating when result will be completed.<br/>\n" + "The CompletableFuture returned by this method can be completed exceptionally with the following exceptions.\n" + "<ul>\n" + "<li>FooException Foo docs</li>\n" + "<li>BarException Bar docs</li>\n" + "</ul>\n")); } @Test public void missingValuesAreNotPresent() { String docs = new DocumentationBuilder() .description("Some service docs") .build(); assertThat(docs).isEqualTo(toPlatformLfs("Some service docs\n\n")); } @Test public void allValuesMissing_ProducesEmptyDocString() { String docs = new DocumentationBuilder() .build(); assertThat(docs).isEqualTo(""); } }
3,343
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/model
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModelTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.model.intermediate; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.File; import java.util.Collections; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.IntermediateModelBuilder; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.service.ServiceMetadata; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; public class IntermediateModelTest { @Test public void cannotFindShapeWhenNoShapesExist() { ServiceMetadata metadata = new ServiceMetadata(); metadata.setProtocol(Protocol.REST_JSON.getValue()); metadata.setServiceId("empty-service"); metadata.setSignatureVersion("V4"); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(new ServiceModel(metadata, Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap())) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertThatThrownBy(() -> testModel.getShapeByNameAndC2jName("AnyShape", "AnyShape")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("C2J shape AnyShape with shape name AnyShape does not exist in the intermediate model."); } @Test public void getShapeByNameAndC2jNameVerifiesC2JName() { final File modelFile = new File(IntermediateModelTest.class .getResource("../../poet/client/c2j/shared-output/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertThatThrownBy(() -> testModel.getShapeByNameAndC2jName("PingResponse", "AnyShape")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("C2J shape AnyShape with shape name PingResponse does not exist in the intermediate model."); } }
3,344
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/jmespath/JmesPathParserTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.jmespath; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.codegen.jmespath.component.Comparator; import software.amazon.awssdk.codegen.jmespath.component.Expression; import software.amazon.awssdk.codegen.jmespath.parser.JmesPathParser; public class JmesPathParserTest { @Test public void testSubExpressionWithIdentifier() { Expression expression = JmesPathParser.parse("foo.bar"); assertThat(expression.asSubExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asSubExpression().rightSubExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testSubExpressionWithMultiSelectList() { Expression expression = JmesPathParser.parse("foo.[bar]"); assertThat(expression.asSubExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asSubExpression().rightSubExpression().asMultiSelectList().expressions()).hasSize(1); assertThat(expression.asSubExpression().rightSubExpression().asMultiSelectList().expressions().get(0).asIdentifier()).isEqualTo("bar"); } @Test public void testSubExpressionWithMultiSelectHash() { Expression expression = JmesPathParser.parse("foo.{bar : baz}"); assertThat(expression.asSubExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asSubExpression().rightSubExpression().asMultiSelectHash().keyValueExpressions()).hasSize(1); assertThat(expression.asSubExpression().rightSubExpression().asMultiSelectHash().keyValueExpressions().get(0).key()).isEqualTo("bar"); assertThat(expression.asSubExpression().rightSubExpression().asMultiSelectHash().keyValueExpressions().get(0).value().asIdentifier()).isEqualTo("baz"); } @Test public void testSubExpressionWithFunction() { Expression expression = JmesPathParser.parse("foo.length()"); assertThat(expression.asSubExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asSubExpression().rightSubExpression().asFunctionExpression().function()).isEqualTo("length"); } @Test public void testSubExpressionWithStar() { Expression expression = JmesPathParser.parse("foo.*"); assertThat(expression.asSubExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asSubExpression().rightSubExpression().isWildcardExpression()).isTrue(); } @Test public void testPipeExpression() { Expression expression = JmesPathParser.parse("foo | bar"); assertThat(expression.asPipeExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asPipeExpression().rightExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testOrExpression() { Expression expression = JmesPathParser.parse("foo || bar"); assertThat(expression.asOrExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asOrExpression().rightExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testAndExpression() { Expression expression = JmesPathParser.parse("foo && bar"); assertThat(expression.asAndExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asAndExpression().rightExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testNotExpression() { Expression expression = JmesPathParser.parse("!foo"); assertThat(expression.asNotExpression().expression().asIdentifier()).isEqualTo("foo"); } @Test public void testParenExpression() { Expression expression = JmesPathParser.parse("(foo)"); assertThat(expression.asParenExpression().expression().asIdentifier()).isEqualTo("foo"); } @Test public void testWildcardExpression() { Expression expression = JmesPathParser.parse("*"); assertThat(expression.isWildcardExpression()).isTrue(); } @Test public void testIndexedExpressionWithoutLeftExpressionWithoutContents() { Expression expression = JmesPathParser.parse("[]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().isBracketSpecifierWithoutContents()).isTrue(); } @Test public void testIndexedExpressionWithoutLeftExpressionWithNumberContents() { Expression expression = JmesPathParser.parse("[10]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asNumber()).isEqualTo(10); } @Test public void testIndexedExpressionWithoutLeftExpressionWithStarContents() { Expression expression = JmesPathParser.parse("[*]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().isWildcardExpression()).isTrue(); } @Test public void testIndexedExpressionWithoutLeftExpressionWithQuestionMark() { Expression expression = JmesPathParser.parse("[?foo]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithQuestionMark().expression().asIdentifier()).isEqualTo("foo"); } @Test public void testIndexedExpressionWithLeftExpressionWithoutContents() { Expression expression = JmesPathParser.parse("foo[]"); assertThat(expression.asIndexExpression().expression()).hasValueSatisfying(e -> assertThat(e.asIdentifier()).isEqualTo("foo")); assertThat(expression.asIndexExpression().bracketSpecifier().isBracketSpecifierWithoutContents()).isTrue(); } @Test public void testIndexedExpressionWithLeftExpressionWithContents() { Expression expression = JmesPathParser.parse("foo[10]"); assertThat(expression.asIndexExpression().expression()).hasValueSatisfying(e -> assertThat(e.asIdentifier()).isEqualTo("foo")); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asNumber()).isEqualTo(10); } @Test public void testIndexedExpressionWithLeftExpressionWithStarContents() { Expression expression = JmesPathParser.parse("foo[*]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).hasValueSatisfying(e -> assertThat(e.asIdentifier()).isEqualTo("foo")); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().isWildcardExpression()).isTrue(); } @Test public void testIndexedExpressionWithLeftExpressionWithQuestionMark() { Expression expression = JmesPathParser.parse("foo[?bar]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).hasValueSatisfying(e -> assertThat(e.asIdentifier()).isEqualTo("foo")); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithQuestionMark().expression().asIdentifier()).isEqualTo("bar"); } @Test public void testMultiSelectList2() { Expression expression = JmesPathParser.parse("[foo, bar]"); assertThat(expression.asMultiSelectList().expressions()).hasSize(2); assertThat(expression.asMultiSelectList().expressions().get(0).asIdentifier()).isEqualTo("foo"); assertThat(expression.asMultiSelectList().expressions().get(1).asIdentifier()).isEqualTo("bar"); } @Test public void testMultiSelectList3() { Expression expression = JmesPathParser.parse("[foo, bar, baz]"); assertThat(expression.asMultiSelectList().expressions()).hasSize(3); assertThat(expression.asMultiSelectList().expressions().get(0).asIdentifier()).isEqualTo("foo"); assertThat(expression.asMultiSelectList().expressions().get(1).asIdentifier()).isEqualTo("bar"); assertThat(expression.asMultiSelectList().expressions().get(2).asIdentifier()).isEqualTo("baz"); } @Test public void testNestedMultiSelectListsRight() { Expression expression = JmesPathParser.parse("[foo, [bar, baz]]"); assertThat(expression.asMultiSelectList().expressions()).hasSize(2); assertThat(expression.asMultiSelectList().expressions().get(0).asIdentifier()).isEqualTo("foo"); assertThat(expression.asMultiSelectList().expressions().get(1).asMultiSelectList().expressions()).hasSize(2); assertThat(expression.asMultiSelectList().expressions().get(1).asMultiSelectList().expressions().get(0).asIdentifier()).isEqualTo("bar"); assertThat(expression.asMultiSelectList().expressions().get(1).asMultiSelectList().expressions().get(1).asIdentifier()).isEqualTo("baz"); } @Test public void testNestedMultiSelectListsCenter() { Expression expression = JmesPathParser.parse("[foo, [bar, baz], bam]"); assertThat(expression.asMultiSelectList().expressions()).hasSize(3); assertThat(expression.asMultiSelectList().expressions().get(0).asIdentifier()).isEqualTo("foo"); assertThat(expression.asMultiSelectList().expressions().get(1).asMultiSelectList().expressions()).hasSize(2); assertThat(expression.asMultiSelectList().expressions().get(1).asMultiSelectList().expressions().get(0).asIdentifier()).isEqualTo("bar"); assertThat(expression.asMultiSelectList().expressions().get(1).asMultiSelectList().expressions().get(1).asIdentifier()).isEqualTo("baz"); assertThat(expression.asMultiSelectList().expressions().get(2).asIdentifier()).isEqualTo("bam"); } @Test public void testNestedMultiSelectListsLeft() { Expression expression = JmesPathParser.parse("[[foo, bar], baz]"); assertThat(expression.asMultiSelectList().expressions()).hasSize(2); assertThat(expression.asMultiSelectList().expressions().get(0).asMultiSelectList().expressions().get(0).asIdentifier()).isEqualTo("foo"); assertThat(expression.asMultiSelectList().expressions().get(0).asMultiSelectList().expressions().get(1).asIdentifier()).isEqualTo("bar"); assertThat(expression.asMultiSelectList().expressions().get(1).asIdentifier()).isEqualTo("baz"); } @Test public void testMultiSelectHash2() { Expression expression = JmesPathParser.parse("{fooK : fooV, barK : barV}"); assertThat(expression.asMultiSelectHash().keyValueExpressions()).hasSize(2); assertThat(expression.asMultiSelectHash().keyValueExpressions().get(0).key()).isEqualTo("fooK"); assertThat(expression.asMultiSelectHash().keyValueExpressions().get(0).value().asIdentifier()).isEqualTo("fooV"); assertThat(expression.asMultiSelectHash().keyValueExpressions().get(1).key()).isEqualTo("barK"); assertThat(expression.asMultiSelectHash().keyValueExpressions().get(1).value().asIdentifier()).isEqualTo("barV"); } @Test public void testMultiSelectHash3() { Expression expression = JmesPathParser.parse("{fooK : fooV, barK : barV, bazK : bazV}"); assertThat(expression.asMultiSelectHash().keyValueExpressions()).hasSize(3); assertThat(expression.asMultiSelectHash().keyValueExpressions().get(0).key()).isEqualTo("fooK"); assertThat(expression.asMultiSelectHash().keyValueExpressions().get(0).value().asIdentifier()).isEqualTo("fooV"); assertThat(expression.asMultiSelectHash().keyValueExpressions().get(1).key()).isEqualTo("barK"); assertThat(expression.asMultiSelectHash().keyValueExpressions().get(1).value().asIdentifier()).isEqualTo("barV"); assertThat(expression.asMultiSelectHash().keyValueExpressions().get(2).key()).isEqualTo("bazK"); assertThat(expression.asMultiSelectHash().keyValueExpressions().get(2).value().asIdentifier()).isEqualTo("bazV"); } @Test public void testComparatorExpressionLT() { Expression expression = JmesPathParser.parse("foo < bar"); assertThat(expression.asComparatorExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asComparatorExpression().comparator()).isEqualTo(Comparator.LESS_THAN); assertThat(expression.asComparatorExpression().rightExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testComparatorExpressionGT() { Expression expression = JmesPathParser.parse("foo > bar"); assertThat(expression.asComparatorExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asComparatorExpression().comparator()).isEqualTo(Comparator.GREATER_THAN); assertThat(expression.asComparatorExpression().rightExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testComparatorExpressionLTE() { Expression expression = JmesPathParser.parse("foo <= bar"); assertThat(expression.asComparatorExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asComparatorExpression().comparator()).isEqualTo(Comparator.LESS_THAN_OR_EQUAL); assertThat(expression.asComparatorExpression().rightExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testComparatorExpressionGTE() { Expression expression = JmesPathParser.parse("foo >= bar"); assertThat(expression.asComparatorExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asComparatorExpression().comparator()).isEqualTo(Comparator.GREATER_THAN_OR_EQUAL); assertThat(expression.asComparatorExpression().rightExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testComparatorExpressionEQ() { Expression expression = JmesPathParser.parse("foo == bar"); assertThat(expression.asComparatorExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asComparatorExpression().comparator()).isEqualTo(Comparator.EQUAL); assertThat(expression.asComparatorExpression().rightExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testComparatorExpressionNEQ() { Expression expression = JmesPathParser.parse("foo != bar"); assertThat(expression.asComparatorExpression().leftExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asComparatorExpression().comparator()).isEqualTo(Comparator.NOT_EQUAL); assertThat(expression.asComparatorExpression().rightExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testSliceExpressionWithNoNumbers2() { Expression expression = JmesPathParser.parse("[:]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().start()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().stop()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().step()).isNotPresent(); } @Test public void testSliceExpressionWithNoNumbers3() { Expression expression = JmesPathParser.parse("[::]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().start()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().stop()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().step()).isNotPresent(); } @Test public void testSliceExpressionWithStartNumber2() { Expression expression = JmesPathParser.parse("[10:]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().start()).hasValue(10); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().stop()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().step()).isNotPresent(); } @Test public void testSliceExpressionWithStopNumber2() { Expression expression = JmesPathParser.parse("[:10]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().start()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().stop()).hasValue(10); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().step()).isNotPresent(); } @Test public void testSliceExpressionWithStartStopNumber2() { Expression expression = JmesPathParser.parse("[10:20]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().start()).hasValue(10); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().stop()).hasValue(20); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().step()).isNotPresent(); } @Test public void testSliceExpressionWithStartNumber3() { Expression expression = JmesPathParser.parse("[10::]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().start()).hasValue(10); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().stop()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().step()).isNotPresent(); } @Test public void testSliceExpressionWithStopNumber3() { Expression expression = JmesPathParser.parse("[:10:]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().start()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().stop()).hasValue(10); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().step()).isNotPresent(); } @Test public void testSliceExpressionWithStartStopNumber3() { Expression expression = JmesPathParser.parse("[10:20:]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().start()).hasValue(10); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().stop()).hasValue(20); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().step()).isNotPresent(); } @Test public void testSliceExpressionWithStartStopStepNumber3() { Expression expression = JmesPathParser.parse("[10:20:30]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().start()).hasValue(10); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().stop()).hasValue(20); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().step()).hasValue(30); } @Test public void testSliceExpressionWithStepNumber3() { Expression expression = JmesPathParser.parse("[::30]"); assertThat(expression.isIndexExpression()).isTrue(); assertThat(expression.asIndexExpression().expression()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().start()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().stop()).isNotPresent(); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asSliceExpression().step()).hasValue(30); } @Test public void testFunction0Args() { Expression expression = JmesPathParser.parse("length()"); assertThat(expression.asFunctionExpression().function()).isEqualTo("length"); assertThat(expression.asFunctionExpression().functionArgs()).isEmpty(); } @Test public void testFunction1ExpressionArg() { Expression expression = JmesPathParser.parse("length(foo)"); assertThat(expression.asFunctionExpression().function()).isEqualTo("length"); assertThat(expression.asFunctionExpression().functionArgs()).hasSize(1); assertThat(expression.asFunctionExpression().functionArgs().get(0).asExpression().asIdentifier()).isEqualTo("foo"); } @Test public void testFunction2ExpressionArg() { Expression expression = JmesPathParser.parse("length(foo, bar)"); assertThat(expression.asFunctionExpression().function()).isEqualTo("length"); assertThat(expression.asFunctionExpression().functionArgs()).hasSize(2); assertThat(expression.asFunctionExpression().functionArgs().get(0).asExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asFunctionExpression().functionArgs().get(1).asExpression().asIdentifier()).isEqualTo("bar"); } @Test public void testFunction3ExpressionArg() { Expression expression = JmesPathParser.parse("length(foo, bar, baz)"); assertThat(expression.asFunctionExpression().function()).isEqualTo("length"); assertThat(expression.asFunctionExpression().functionArgs()).hasSize(3); assertThat(expression.asFunctionExpression().functionArgs().get(0).asExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asFunctionExpression().functionArgs().get(1).asExpression().asIdentifier()).isEqualTo("bar"); assertThat(expression.asFunctionExpression().functionArgs().get(2).asExpression().asIdentifier()).isEqualTo("baz"); } @Test public void testFunction1ExpressionTypeArg() { Expression expression = JmesPathParser.parse("length(&foo)"); assertThat(expression.asFunctionExpression().function()).isEqualTo("length"); assertThat(expression.asFunctionExpression().functionArgs()).hasSize(1); assertThat(expression.asFunctionExpression().functionArgs().get(0).asExpressionType().expression().asIdentifier()).isEqualTo("foo"); } @Test public void testFunction2ExpressionTypeArg() { Expression expression = JmesPathParser.parse("length(&foo, &bar)"); assertThat(expression.asFunctionExpression().function()).isEqualTo("length"); assertThat(expression.asFunctionExpression().functionArgs()).hasSize(2); assertThat(expression.asFunctionExpression().functionArgs().get(0).asExpressionType().expression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asFunctionExpression().functionArgs().get(1).asExpressionType().expression().asIdentifier()).isEqualTo("bar"); } @Test public void testFunction3ExpressionTypeArg() { Expression expression = JmesPathParser.parse("length(&foo, &bar, &baz)"); assertThat(expression.asFunctionExpression().function()).isEqualTo("length"); assertThat(expression.asFunctionExpression().functionArgs()).hasSize(3); assertThat(expression.asFunctionExpression().functionArgs().get(0).asExpressionType().expression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asFunctionExpression().functionArgs().get(1).asExpressionType().expression().asIdentifier()).isEqualTo("bar"); assertThat(expression.asFunctionExpression().functionArgs().get(2).asExpressionType().expression().asIdentifier()).isEqualTo("baz"); } @Test public void testFunction3MixedExpressionTypeArg() { Expression expression = JmesPathParser.parse("length(foo, &bar, baz)"); assertThat(expression.asFunctionExpression().function()).isEqualTo("length"); assertThat(expression.asFunctionExpression().functionArgs()).hasSize(3); assertThat(expression.asFunctionExpression().functionArgs().get(0).asExpression().asIdentifier()).isEqualTo("foo"); assertThat(expression.asFunctionExpression().functionArgs().get(1).asExpressionType().expression().asIdentifier()).isEqualTo("bar"); assertThat(expression.asFunctionExpression().functionArgs().get(2).asExpression().asIdentifier()).isEqualTo("baz"); } @Test public void testCurrentNode() { Expression expression = JmesPathParser.parse("@"); assertThat(expression.isCurrentNode()).isTrue(); } @Test public void testEmptyIdentifierUnquoted() { Expression expression = JmesPathParser.parse("foo_bar"); assertThat(expression.asIdentifier()).isEqualTo("foo_bar"); } @Test public void testIdentifierUnquoted() { Expression expression = JmesPathParser.parse("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"); assertThat(expression.asIdentifier()).isEqualTo("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"); } @Test public void testIdentifierQuoted() { Expression expression = JmesPathParser.parse("\"foo bar\""); assertThat(expression.asIdentifier()).isEqualTo("foo bar"); } @Test public void testIdentifierQuotedWithEscapes() { Expression expression = JmesPathParser.parse("\"foo \\\" \\\\ \\/ \\b \\f \\n \\r \\t \\u0000 \\uffff bar\""); assertThat(expression.asIdentifier()).isEqualTo("foo \" \\ / \b \f \n \r \t \u0000 \uffff bar"); } @Test public void testRawStringEmpty() { Expression expression = JmesPathParser.parse("''"); assertThat(expression.asRawString()).isEmpty(); } @Test public void testRawStringWithValue() { Expression expression = JmesPathParser.parse("'foo bar'"); assertThat(expression.asRawString()).isEqualTo("foo bar"); } @Test public void testRawStringWithEscapedSequences() { Expression expression = JmesPathParser.parse("'foo \\' \\\\ \\/ \\b \\f \\n \\r \\t \\u0000 \\uffff bar'"); assertThat(expression.asRawString()).isEqualTo("foo \\' \\\\ \\/ \\b \\f \\n \\r \\t \\u0000 \\uffff bar"); } @Test public void testNegativeNumber() { Expression expression = JmesPathParser.parse("[-10]"); assertThat(expression.asIndexExpression().bracketSpecifier().asBracketSpecifierWithContents().asNumber()).isEqualTo(-10); } }
3,345
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/emitters/PoetGeneratorTaskIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.emitters; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.CombinableMatcher.both; import static software.amazon.awssdk.codegen.TestStringUtils.toPlatformLfs; import static software.amazon.awssdk.utils.FunctionalUtils.safeConsumer; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeSpec; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Test; import software.amazon.awssdk.codegen.poet.ClassSpec; public final class PoetGeneratorTaskIntegrationTest { private static String PACKAGE = "com.blah.foo.bar"; private final List<String> tempDirectories = new ArrayList<>(); @Test public void canGenerateJavaClass() throws Exception { String randomBaseDirectory = Files.createTempDirectory(getClass().getSimpleName()).toString(); tempDirectories.add(randomBaseDirectory); String fileHeader = toPlatformLfs("/*\n * this is the file header\n */"); ClassSpec classSpec = dummyClass(); PoetGeneratorTask sut = new PoetGeneratorTask(randomBaseDirectory, fileHeader, classSpec); sut.compute(); String contents = new String(Files.readAllBytes(determineOutputFile(classSpec, randomBaseDirectory))); assertThat(contents, both(containsString(PACKAGE)).and(startsWith(fileHeader))); } @After public void cleanUp() { tempDirectories.forEach(safeConsumer(tempDir -> { List<Path> files = Files.walk(Paths.get(tempDir)).collect(toList()); Collections.reverse(files); files.forEach(safeConsumer(Files::delete)); })); } private Path determineOutputFile(ClassSpec classSpec, String randomBaseDirectory) { return Paths.get(randomBaseDirectory).resolve(classSpec.className().simpleName() + ".java"); } private ClassSpec dummyClass() { return new ClassSpec() { @Override public TypeSpec poetSpec() { return TypeSpec.enumBuilder("Blah").addEnumConstant("FOO").addEnumConstant("BAR").build(); } @Override public ClassName className() { return ClassName.get(PACKAGE, "Blah"); } }; } }
3,346
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/emitters/UnusedImportRemoverTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.emitters; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.jupiter.api.Test; public class UnusedImportRemoverTest { private static final String FILE_WITH_UNUSED_IMPORTS_JAVA = "content-before-unused-import-removal.txt"; private static final String FILE_WITHOUT_UNUSED_IMPORTS_JAVA = "content-after-unused-import-removal.txt"; private final UnusedImportRemover sut = new UnusedImportRemover(); @Test public void unusedImportsAreRemoved() throws Exception { String content = loadFileContents(FILE_WITH_UNUSED_IMPORTS_JAVA); String expected = loadFileContents(FILE_WITHOUT_UNUSED_IMPORTS_JAVA); String result = sut.apply(content); assertThat(result, equalToIgnoringWhiteSpace(expected)); } @Test public void nonJavaContentIsIgnored() throws Exception { String jsonContent = "{ \"SomeKey\": 4, \"ADict\": { \"SubKey\": \"Subvalue\" } }"; String result = sut.apply(jsonContent); assertThat(result, equalTo(jsonContent)); } private static String loadFileContents(String filename) throws Exception { return new String(Files.readAllBytes(Paths.get(UnusedImportRemoverTest.class.getResource(filename).toURI()))); } }
3,347
0
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/test/java/software/amazon/awssdk/codegen/emitters/CodeTransformerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.emitters; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; public class CodeTransformerTest { @Test public void chainCallsProcessorsInOrderAndPassedResultOfPreviousProcessor() { String input = "hello", intermediate = "world", output = "earth"; CodeTransformer firstProcessor = mockProcessor(input, intermediate), secondProcessor = mockProcessor(intermediate, output); CodeTransformer chain = CodeTransformer.chain(firstProcessor, secondProcessor); assertThat(chain.apply(input), equalTo(output)); } private CodeTransformer mockProcessor(String accepts, String returns) { CodeTransformer processor = mock(CodeTransformer.class); when(processor.apply(accepts)).thenReturn(returns); return processor; } }
3,348
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/IntermediateModelBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import static software.amazon.awssdk.codegen.AddMetadata.constructMetadata; import static software.amazon.awssdk.codegen.RemoveUnusedShapes.removeUnusedShapes; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.customization.processors.DefaultCustomizationProcessor; import software.amazon.awssdk.codegen.internal.Constant; import software.amazon.awssdk.codegen.internal.TypeUtils; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.rules.endpoints.EndpointTestSuiteModel; import software.amazon.awssdk.codegen.model.service.AuthType; import software.amazon.awssdk.codegen.model.service.EndpointRuleSetModel; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.Paginators; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Waiters; import software.amazon.awssdk.codegen.naming.DefaultNamingStrategy; import software.amazon.awssdk.codegen.naming.NamingStrategy; import software.amazon.awssdk.utils.CollectionUtils; /** * Builds an intermediate model to be used by the templates from the service model and * customizations. */ public class IntermediateModelBuilder { private static final Logger log = LoggerFactory.getLogger(IntermediateModelBuilder.class); private final CustomizationConfig customConfig; private final ServiceModel service; private final NamingStrategy namingStrategy; private final TypeUtils typeUtils; private final List<IntermediateModelShapeProcessor> shapeProcessors; private final Paginators paginators; private final Waiters waiters; private final EndpointRuleSetModel endpointRuleSet; private final EndpointTestSuiteModel endpointTestSuiteModel; public IntermediateModelBuilder(C2jModels models) { this.customConfig = models.customizationConfig(); this.service = models.serviceModel(); this.namingStrategy = new DefaultNamingStrategy(service, customConfig); this.typeUtils = new TypeUtils(namingStrategy); this.shapeProcessors = createShapeProcessors(); this.paginators = models.paginatorsModel(); this.waiters = models.waitersModel(); this.endpointRuleSet = models.endpointRuleSetModel(); this.endpointTestSuiteModel = models.endpointTestSuiteModel(); } /** * Create default shape processors. */ private List<IntermediateModelShapeProcessor> createShapeProcessors() { List<IntermediateModelShapeProcessor> processors = new ArrayList<>(); processors.add(new AddInputShapes(this)); processors.add(new AddOutputShapes(this)); processors.add(new AddExceptionShapes(this)); processors.add(new AddModelShapes(this)); processors.add(new AddEmptyInputShape(this)); processors.add(new AddEmptyOutputShape(this)); return processors; } public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); // Iterate through every operation and build an 'endpointOperation' if at least one operation that supports // endpoint discovery is found. If -any operations that require- endpoint discovery are found, then the flag // 'endpointCacheRequired' will be set on the 'endpointOperation'. This 'endpointOperation' summary is then // passed directly into the constructor of the intermediate model and is referred to by the codegen. OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } // Remove deprecated operations and their paginators operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, paginators.getPagination(), namingStrategy, waiters.getWaiters(), endpointRuleSet, endpointTestSuiteModel, service.getClientContextParams()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); // Remove deprecated shapes trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getPaginators(), namingStrategy, fullModel.getWaiters(), fullModel.getEndpointRuleSetModel(), endpointTestSuiteModel, service.getClientContextParams()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); namingStrategy.validateCustomerVisibleNaming(trimmedModel); return trimmedModel; } /** * Link the member to it's corresponding shape (if it exists). * * @param model Final IntermediateModel */ private void linkMembersToShapes(IntermediateModel model) { for (Map.Entry<String, ShapeModel> entry : model.getShapes().entrySet()) { if (entry.getValue().getMembers() != null) { for (MemberModel member : entry.getValue().getMembers()) { member.setShape(Utils.findMemberShapeModelByC2jNameIfExists(model, member.getC2jShape())); } } } } private void linkOperationsToInputOutputShapes(IntermediateModel model) { for (Map.Entry<String, OperationModel> entry : model.getOperations().entrySet()) { Operation operation = service.getOperations().get(entry.getKey()); if (entry.getValue().getInput() != null) { entry.getValue().setInputShape(model.getShapes().get(entry.getValue().getInput().getSimpleType())); } if (operation.getOutput() != null) { String outputShapeName = operation.getOutput().getShape(); ShapeModel outputShape = model.getShapeByNameAndC2jName(entry.getValue().getReturnType().getReturnType(), outputShapeName); entry.getValue().setOutputShape(outputShape); } } } private void linkCustomAuthorizationToRequestShapes(IntermediateModel model) { model.getOperations().values().stream() .filter(OperationModel::isAuthenticated) .forEach(operation -> { Operation c2jOperation = service.getOperation(operation.getOperationName()); ShapeModel shape = operation.getInputShape(); if (shape == null) { throw new RuntimeException(String.format("Operation %s has unknown input shape", operation.getOperationName())); } linkAuthorizationToRequestShapeForAwsProtocol(c2jOperation.getAuthtype(), shape); }); } private void linkAuthorizationToRequestShapeForAwsProtocol(AuthType authType, ShapeModel shape) { if (authType == null) { return; } switch (authType) { case V4: shape.setRequestSignerClassFqcn("software.amazon.awssdk.auth.signer.Aws4Signer"); break; case V4_UNSIGNED_BODY: shape.setRequestSignerClassFqcn("software.amazon.awssdk.auth.signer.Aws4UnsignedPayloadSigner"); break; case BEARER: shape.setRequestSignerClassFqcn("software.amazon.awssdk.auth.token.signer.aws.BearerTokenSigner"); break; case NONE: break; default: throw new IllegalArgumentException("Unsupported authtype for AWS Request: " + authType); } } private void setSimpleMethods(IntermediateModel model) { CustomizationConfig config = model.getCustomizationConfig(); model.getOperations().values().forEach(operation -> { ShapeModel inputShape = operation.getInputShape(); String methodName = operation.getMethodName(); if (config.getVerifiedSimpleMethods().contains(methodName)) { inputShape.setSimpleMethod(true); } else { inputShape.setSimpleMethod(false); boolean methodIsNotExcluded = !config.getExcludedSimpleMethods().contains(methodName) || config.getExcludedSimpleMethods().stream().noneMatch(m -> m.equals("*")) || !config.getBlacklistedSimpleMethods().contains(methodName) || config.getBlacklistedSimpleMethods().stream().noneMatch(m -> m.equals("*")); boolean methodHasNoRequiredMembers = !CollectionUtils.isNullOrEmpty(inputShape.getRequired()); boolean methodIsNotStreaming = !operation.isStreaming(); boolean methodHasSimpleMethodVerb = methodName.matches(Constant.APPROVED_SIMPLE_METHOD_VERBS); if (methodIsNotExcluded && methodHasNoRequiredMembers && methodIsNotStreaming && methodHasSimpleMethodVerb) { log.warn("A potential simple method exists that isn't explicitly excluded or included: " + methodName); } } }); } public CustomizationConfig getCustomConfig() { return customConfig; } public ServiceModel getService() { return service; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public TypeUtils getTypeUtils() { return typeUtils; } public Paginators getPaginators() { return paginators; } }
3,349
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/RemoveUnusedShapes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import software.amazon.awssdk.codegen.model.intermediate.ExceptionModel; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ReturnTypeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.VariableModel; /** * Removes the un-used shapes from the intermediate model. This is done by * re-constructing the shapes map. First add the shapes referenced by the * operations and then adding the shapes referenced by each shapes. */ final class RemoveUnusedShapes { private RemoveUnusedShapes() { } public static Map<String, ShapeModel> removeUnusedShapes(IntermediateModel model) { Map<String, ShapeModel> out = new HashMap<>(); Map<String, ShapeModel> in = model.getShapes(); for (OperationModel opModel : model.getOperations().values()) { addOperationShapes(opModel, in, out); } return out; } private static void addOperationShapes(OperationModel op, Map<String, ShapeModel> in, Map<String, ShapeModel> out) { VariableModel input = op.getInput(); if (input != null) { addShapeAndMembers(input.getSimpleType(), in, out); } ReturnTypeModel output = op.getReturnType(); if (output != null) { addShapeAndMembers(output.getReturnType(), in, out); } List<ExceptionModel> exceptions = op.getExceptions(); if (op.getExceptions() != null) { for (ExceptionModel e : exceptions) { addShapeAndMembers(e.getExceptionName(), in, out); } } } /** * Adds the shape. Recursively adds the shapes represented by its members. */ private static void addShapeAndMembers(String shapeName, Map<String, ShapeModel> in, Map<String, ShapeModel> out) { if (shapeName == null) { return; } ShapeModel shape = in.get(shapeName); if (shape == null) { return; } if (!out.containsKey(shapeName)) { out.put(shapeName, in.get(shapeName)); List<MemberModel> members = shape.getMembers(); if (members != null) { for (MemberModel member : members) { List<String> memberShapes = resolveMemberShapes(member); if (memberShapes == null) { continue; } for (String memberShape : memberShapes) { addShapeAndMembers(memberShape, in, out); } } } } } /** * Recursively resolves the shapes represented by the member. When the member is a map, * both the key shape and the value shape of the map will be resolved, so that the * returning list could have more than one elements. */ private static List<String> resolveMemberShapes(MemberModel member) { if (member == null) { return new LinkedList<>(); } if (member.getEnumType() != null) { return Collections.singletonList(member.getEnumType()); } else if (member.isList()) { return resolveMemberShapes(member.getListModel().getListMemberModel()); } else if (member.isMap()) { List<String> memberShapes = new LinkedList<>(); memberShapes.addAll(resolveMemberShapes(member.getMapModel().getKeyModel())); memberShapes.addAll(resolveMemberShapes(member.getMapModel().getValueModel())); return memberShapes; } else if (member.isSimple()) { // member is scalar, do nothing return new LinkedList<>(); } else { // member is a structure. return Collections.singletonList(member.getVariable().getSimpleType()); } } }
3,350
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/AddModelShapes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import static software.amazon.awssdk.codegen.internal.Utils.isStructure; import java.util.HashMap; import java.util.Map; import java.util.Set; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.intermediate.ShapeUnmarshaller; import software.amazon.awssdk.codegen.model.service.Shape; /** * Constructs the shapes (other than request, response and exception) from the service model. */ final class AddModelShapes extends AddShapes implements IntermediateModelShapeProcessor { AddModelShapes(IntermediateModelBuilder builder) { super(builder); } @Override public Map<String, ShapeModel> process(Map<String, OperationModel> currentOperations, Map<String, ShapeModel> currentShapes) { // Only need to construct model shapes for shapes that have not been previously processed return constructModelShapes(currentShapes.keySet()); } private Map<String, ShapeModel> constructModelShapes(Set<String> shapesToSkip) { // Java output shape models, to be constructed Map<String, ShapeModel> javaShapes = new HashMap<>(); for (Map.Entry<String, Shape> entry : getServiceModel().getShapes().entrySet()) { String shapeName = entry.getKey(); Shape shape = entry.getValue(); ShapeType shapeType = getModelShapeType(shape); if (shapeType != null) { String javaClassName = getNamingStrategy().getShapeClassName(shapeName); if (shapesToSkip.contains(javaClassName)) { continue; } ShapeModel modelShape = generateShapeModel(javaClassName, shapeName); modelShape.setType(shapeType); // We need unmarshaller metadata for all shapes ShapeUnmarshaller unmarshaller = new ShapeUnmarshaller(); unmarshaller.setFlattened(shape.isFlattened()); modelShape.setUnmarshaller(unmarshaller); javaShapes.put(javaClassName, modelShape); } } return javaShapes; } /** * @return null if the given shape is neither a structure nor enum model. */ private ShapeType getModelShapeType(final Shape shape) { if (shape.isException()) { return null; } if (isStructure(shape)) { return ShapeType.Model; } else if (shape.getEnumValues() != null) { return ShapeType.Enum; } return null; } }
3,351
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/AddEmptyOutputShape.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ReturnTypeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.intermediate.ShapeUnmarshaller; import software.amazon.awssdk.codegen.model.intermediate.VariableModel; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.Output; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.naming.NamingStrategy; public class AddEmptyOutputShape implements IntermediateModelShapeProcessor { private final ServiceModel serviceModel; private final NamingStrategy namingStrategy; public AddEmptyOutputShape(IntermediateModelBuilder builder) { this.serviceModel = builder.getService(); this.namingStrategy = builder.getNamingStrategy(); } @Override public Map<String, ShapeModel> process(Map<String, OperationModel> currentOperations, Map<String, ShapeModel> currentShapes) { return addEmptyOutputShapes(currentOperations); } private Map<String, ShapeModel> addEmptyOutputShapes( Map<String, OperationModel> currentOperations) { Map<String, Operation> operations = serviceModel.getOperations(); Map<String, ShapeModel> emptyOutputShapes = new HashMap<>(); for (Map.Entry<String, Operation> entry : operations.entrySet()) { String operationName = entry.getKey(); Operation operation = entry.getValue(); Output output = operation.getOutput(); if (output == null) { String outputShape = namingStrategy.getResponseClassName(operationName); OperationModel operationModel = currentOperations.get(operationName); operationModel.setReturnType(new ReturnTypeModel(outputShape)); ShapeModel shape = new ShapeModel(outputShape) .withType(ShapeType.Response.getValue()); shape.setShapeName(outputShape); VariableModel outputVariable = new VariableModel( namingStrategy.getVariableName(outputShape), outputShape); shape.setVariable(outputVariable); shape.setUnmarshaller(new ShapeUnmarshaller()); emptyOutputShapes.put(outputShape, shape); } } return emptyOutputShapes; } }
3,352
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/AddInputShapes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import static software.amazon.awssdk.codegen.internal.Utils.createInputShapeMarshaller; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.service.Input; import software.amazon.awssdk.codegen.model.service.Operation; /** * Constructs the request shapes for the intermediate model. Analyzes the operations in the service * model to identify the request shapes that are to be generated. */ final class AddInputShapes extends AddShapes implements IntermediateModelShapeProcessor { AddInputShapes(IntermediateModelBuilder builder) { super(builder); } @Override public Map<String, ShapeModel> process(Map<String, OperationModel> currentOperations, Map<String, ShapeModel> currentShapes) { return constructInputShapes(); } private Map<String, ShapeModel> constructInputShapes() { // Java input shape models, to be constructed Map<String, ShapeModel> javaShapes = new HashMap<>(); for (Map.Entry<String, Operation> entry : getServiceModel().getOperations().entrySet()) { String operationName = entry.getKey(); Operation operation = entry.getValue(); Input input = operation.getInput(); if (input != null) { String javaRequestShapeName = getNamingStrategy() .getRequestClassName(operationName); ShapeModel inputShape = generateInputShapeModel(operation, javaRequestShapeName); if (inputShape.getDocumentation() == null) { inputShape.setDocumentation(input.getDocumentation()); } javaShapes.put(javaRequestShapeName, inputShape); } } return javaShapes; } private ShapeModel generateInputShapeModel(Operation operation, String javaInputShapeNameOverride) { Input input = operation.getInput(); String inputShapeName = input.getShape(); ShapeModel shapeModel = generateShapeModel(javaInputShapeNameOverride, inputShapeName); shapeModel.setType(ShapeType.Request.getValue()); shapeModel.setMarshaller( createInputShapeMarshaller(getServiceModel().getMetadata(), operation)); shapeModel.setEndpointDiscovery(operation.getEndpointdiscovery()); return shapeModel; } }
3,353
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/AddOperations.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import static software.amazon.awssdk.codegen.internal.Utils.unCapitalize; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import software.amazon.awssdk.codegen.model.intermediate.ExceptionModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ReturnTypeModel; import software.amazon.awssdk.codegen.model.intermediate.VariableModel; import software.amazon.awssdk.codegen.model.service.AuthType; import software.amazon.awssdk.codegen.model.service.ErrorMap; import software.amazon.awssdk.codegen.model.service.ErrorTrait; import software.amazon.awssdk.codegen.model.service.Input; import software.amazon.awssdk.codegen.model.service.Member; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.Output; import software.amazon.awssdk.codegen.model.service.PaginatorDefinition; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Shape; import software.amazon.awssdk.codegen.naming.NamingStrategy; /** * Constructs the operation model for every operation defined by the service. */ final class AddOperations { private final ServiceModel serviceModel; private final NamingStrategy namingStrategy; private final Map<String, PaginatorDefinition> paginators; private final List<String> deprecatedShapes; AddOperations(IntermediateModelBuilder builder) { this.serviceModel = builder.getService(); this.namingStrategy = builder.getNamingStrategy(); this.paginators = builder.getPaginators().getPagination(); this.deprecatedShapes = builder.getCustomConfig().getDeprecatedShapes(); } private static boolean isAuthenticated(Operation op) { return op.getAuthtype() == null || op.getAuthtype() != AuthType.NONE; } private static String getOperationDocumentation(final Output output, final Shape outputShape) { return output.getDocumentation() != null ? output.getDocumentation() : outputShape.getDocumentation(); } /** * @return True if shape is a Blob type. False otherwise */ private static boolean isBlobShape(Shape shape) { return shape != null && "blob".equals(shape.getType()); } /** * If there is a member in the output shape that is explicitly marked as the payload (with the payload trait) this method * returns the target shape of that member. Otherwise this method returns null. * * @return True if shape is a String type. False otherwise */ private static boolean isStringShape(Shape shape) { return shape != null && "String".equalsIgnoreCase(shape.getType()); } /** * If there is a member in the output shape that is explicitly marked as the payload (with the * payload trait) this method returns the target shape of that member. Otherwise this method * returns null. * * @param c2jShapes All C2J shapes * @param outputShape Output shape of operation that may contain a member designated as the payload */ public static Shape getPayloadShape(Map<String, Shape> c2jShapes, Shape outputShape) { if (outputShape.getPayload() == null) { return null; } Member payloadMember = outputShape.getMembers().get(outputShape.getPayload()); return c2jShapes.get(payloadMember.getShape()); } /** * In query protocol, the wrapped result is the real return type for the given operation. In the c2j model, * if the output shape has only one member, and the member shape is wrapped (wrapper is true), then the * return type is the wrapped member shape instead of the output shape. In the following example, the service API is: * * public Foo operation(OperationRequest operationRequest); * * And the wire log is: * <OperationResponse> * <OperationResult> * <Foo> * ... * </Foo> * </OperationResult> * <OperationMetadata> * </OperationMetadata> * </OperationResponse> * * The C2j model is: * "Operation": { * "input": {"shape": "OperationRequest"}, * "output": { * "shape": "OperationResult", * "resultWrapper": "OperationResult" * } * }, * "OperationResult": { * ... * "members": { * "Foo": {"shape": "Foo"} * } * }, * "Foo" : { * ... * "wrapper" : true * } * * Return the wrapped shape name from the given operation if it conforms to the condition * described above, otherwise, simply return the direct output shape name. */ private static String getResultShapeName(Operation operation, Map<String, Shape> shapes) { Output output = operation.getOutput(); if (output == null) { return null; } Shape outputShape = shapes.get(output.getShape()); if (outputShape.getMembers().keySet().size() != 1) { return output.getShape(); } Member wrappedMember = outputShape.getMembers().values().toArray(new Member[0])[0]; Shape wrappedResult = shapes.get(wrappedMember.getShape()); return wrappedResult.isWrapper() ? wrappedMember.getShape() : output.getShape(); } public Map<String, OperationModel> constructOperations() { Map<String, OperationModel> javaOperationModels = new TreeMap<>(); Map<String, Shape> c2jShapes = serviceModel.getShapes(); for (Map.Entry<String, Operation> entry : serviceModel.getOperations().entrySet()) { String operationName = entry.getKey(); Operation op = entry.getValue(); OperationModel operationModel = new OperationModel(); operationModel.setOperationName(operationName); operationModel.setServiceProtocol(serviceModel.getMetadata().getProtocol()); operationModel.setDeprecated(op.isDeprecated()); operationModel.setDeprecatedMessage(op.getDeprecatedMessage()); operationModel.setDocumentation(op.getDocumentation()); operationModel.setIsAuthenticated(isAuthenticated(op)); operationModel.setAuthType(op.getAuthtype()); operationModel.setPaginated(isPaginated(op)); operationModel.setEndpointOperation(op.isEndpointoperation()); operationModel.setEndpointDiscovery(op.getEndpointdiscovery()); operationModel.setEndpointTrait(op.getEndpoint()); operationModel.setHttpChecksumRequired(op.isHttpChecksumRequired()); operationModel.setHttpChecksum(op.getHttpChecksum()); operationModel.setRequestCompression(op.getRequestCompression()); operationModel.setStaticContextParams(op.getStaticContextParams()); operationModel.setAuth(getAuthFromOperation(op)); Input input = op.getInput(); if (input != null) { String originalShapeName = input.getShape(); String inputShape = namingStrategy.getRequestClassName(operationName); String documentation = input.getDocumentation() != null ? input.getDocumentation() : c2jShapes.get(originalShapeName).getDocumentation(); operationModel.setInput(new VariableModel(unCapitalize(inputShape), inputShape) .withDocumentation(documentation)); } Output output = op.getOutput(); if (output != null) { String outputShapeName = getResultShapeName(op, c2jShapes); Shape outputShape = c2jShapes.get(outputShapeName); String responseClassName = namingStrategy.getResponseClassName(operationName); String documentation = getOperationDocumentation(output, outputShape); operationModel.setReturnType( new ReturnTypeModel(responseClassName).withDocumentation(documentation)); if (isBlobShape(getPayloadShape(c2jShapes, outputShape))) { operationModel.setHasBlobMemberAsPayload(true); } if (isStringShape(getPayloadShape(c2jShapes, outputShape))) { operationModel.setHasStringMemberAsPayload(true); } } if (op.getErrors() != null) { for (ErrorMap error : op.getErrors()) { String documentation = error.getDocumentation() != null ? error.getDocumentation() : c2jShapes.get(error.getShape()).getDocumentation(); Integer httpStatusCode = getHttpStatusCode(error, c2jShapes.get(error.getShape())); if (!deprecatedShapes.contains(error.getShape())) { operationModel.addException( new ExceptionModel(namingStrategy.getExceptionName(error.getShape())) .withDocumentation(documentation) .withHttpStatusCode(httpStatusCode)); } } } javaOperationModels.put(operationName, operationModel); } return javaOperationModels; } /** * Returns the list of authTypes defined for an operation. If the new auth member is defined we use it, otherwise we retrofit * the list with the value of the authType member if present or return an empty list if not. */ private List<AuthType> getAuthFromOperation(Operation op) { List<String> opAuth = op.getAuth(); if (opAuth != null) { return opAuth.stream().map(AuthType::fromValue).collect(Collectors.toList()); } AuthType legacyAuthType = op.getAuthtype(); if (legacyAuthType != null) { return Collections.singletonList(legacyAuthType); } return Collections.emptyList(); } /** * Get HTTP status code either from error trait on the operation reference or the error trait on the shape. * * @param error ErrorMap on operation reference. * @param shape Error shape. * @return HTTP status code or null if not present. */ private Integer getHttpStatusCode(ErrorMap error, Shape shape) { Integer httpStatusCode = getHttpStatusCode(error.getError()); return httpStatusCode == null ? getHttpStatusCode(shape.getError()) : httpStatusCode; } /** * @param errorTrait Error trait. * @return HTTP status code from trait or null if not present. */ private Integer getHttpStatusCode(ErrorTrait errorTrait) { return errorTrait == null ? null : errorTrait.getHttpStatusCode(); } private boolean isPaginated(Operation op) { return paginators.containsKey(op.getName()) && paginators.get(op.getName()).isValid(); } }
3,354
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/AddMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import java.util.Collections; import java.util.Optional; import java.util.stream.Collectors; import software.amazon.awssdk.codegen.internal.Constant; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.Protocol; import software.amazon.awssdk.codegen.model.service.AuthType; import software.amazon.awssdk.codegen.model.service.ServiceMetadata; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.naming.DefaultNamingStrategy; import software.amazon.awssdk.codegen.naming.NamingStrategy; /** * Constructs the metadata that is required for generating the java client from the service meta data. */ final class AddMetadata { private static final String AWS_PACKAGE_PREFIX = "software.amazon.awssdk.services"; private AddMetadata() { } public static Metadata constructMetadata(ServiceModel serviceModel, CustomizationConfig customizationConfig) { Metadata metadata = new Metadata(); NamingStrategy namingStrategy = new DefaultNamingStrategy(serviceModel, customizationConfig); ServiceMetadata serviceMetadata = serviceModel.getMetadata(); String serviceName = namingStrategy.getServiceName(); metadata.withApiVersion(serviceMetadata.getApiVersion()) .withAsyncClient(String.format(Constant.ASYNC_CLIENT_CLASS_NAME_PATTERN, serviceName)) .withAsyncInterface(String.format(Constant.ASYNC_CLIENT_INTERFACE_NAME_PATTERN, serviceName)) .withAsyncBuilder(String.format(Constant.ASYNC_BUILDER_CLASS_NAME_PATTERN, serviceName)) .withAsyncBuilderInterface(String.format(Constant.ASYNC_BUILDER_INTERFACE_NAME_PATTERN, serviceName)) .withBaseBuilderInterface(String.format(Constant.BASE_BUILDER_INTERFACE_NAME_PATTERN, serviceName)) .withBaseBuilder(String.format(Constant.BASE_BUILDER_CLASS_NAME_PATTERN, serviceName)) .withDocumentation(serviceModel.getDocumentation()) .withRootPackageName(AWS_PACKAGE_PREFIX) .withClientPackageName(namingStrategy.getClientPackageName(serviceName)) .withModelPackageName(namingStrategy.getModelPackageName(serviceName)) .withTransformPackageName(namingStrategy.getTransformPackageName(serviceName)) .withRequestTransformPackageName(namingStrategy.getRequestTransformPackageName(serviceName)) .withPaginatorsPackageName(namingStrategy.getPaginatorsPackageName(serviceName)) .withWaitersPackageName(namingStrategy.getWaitersPackageName(serviceName)) .withEndpointRulesPackageName(namingStrategy.getEndpointRulesPackageName(serviceName)) .withAuthSchemePackageName(namingStrategy.getAuthSchemePackageName(serviceName)) .withServiceAbbreviation(serviceMetadata.getServiceAbbreviation()) .withServiceFullName(serviceMetadata.getServiceFullName()) .withServiceName(serviceName) .withSyncClient(String.format(Constant.SYNC_CLIENT_CLASS_NAME_PATTERN, serviceName)) .withSyncInterface(String.format(Constant.SYNC_CLIENT_INTERFACE_NAME_PATTERN, serviceName)) .withSyncBuilder(String.format(Constant.SYNC_BUILDER_CLASS_NAME_PATTERN, serviceName)) .withSyncBuilderInterface(String.format(Constant.SYNC_BUILDER_INTERFACE_NAME_PATTERN, serviceName)) .withBaseExceptionName(String.format(Constant.BASE_EXCEPTION_NAME_PATTERN, serviceName)) .withBaseRequestName(String.format(Constant.BASE_REQUEST_NAME_PATTERN, serviceName)) .withBaseResponseName(String.format(Constant.BASE_RESPONSE_NAME_PATTERN, serviceName)) .withProtocol(Protocol.fromValue(serviceMetadata.getProtocol())) .withJsonVersion(serviceMetadata.getJsonVersion()) .withEndpointPrefix(serviceMetadata.getEndpointPrefix()) .withSigningName(serviceMetadata.getSigningName()) .withAuthType(AuthType.fromValue(serviceMetadata.getSignatureVersion())) .withUid(serviceMetadata.getUid()) .withServiceId(serviceMetadata.getServiceId()) .withSupportsH2(supportsH2(serviceMetadata)) .withJsonVersion(getJsonVersion(metadata, serviceMetadata)) .withAwsQueryCompatible(serviceMetadata.getAwsQueryCompatible()) .withAuth(Optional.ofNullable(serviceMetadata.getAuth()) .orElseGet(() -> Collections.singletonList(serviceMetadata.getSignatureVersion())) .stream() .map(AuthType::fromValue) .collect(Collectors.toList())); return metadata; } private static boolean supportsH2(ServiceMetadata serviceMetadata) { return serviceMetadata.getProtocolSettings() != null && serviceMetadata.getProtocolSettings().containsKey("h2"); } private static String getJsonVersion(Metadata metadata, ServiceMetadata serviceMetadata) { // TODO this should be defaulted in the C2J build tool if (serviceMetadata.getJsonVersion() == null && metadata.isJsonProtocol()) { return "1.1"; } else { return serviceMetadata.getJsonVersion(); } } }
3,355
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/AddShapes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import static software.amazon.awssdk.codegen.internal.TypeUtils.getDataTypeMapping; import static software.amazon.awssdk.codegen.internal.Utils.capitalize; import static software.amazon.awssdk.codegen.internal.Utils.isListShape; import static software.amazon.awssdk.codegen.internal.Utils.isMapShape; import static software.amazon.awssdk.codegen.internal.Utils.isScalar; import java.util.List; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.codegen.internal.TypeUtils; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.EnumModel; import software.amazon.awssdk.codegen.model.intermediate.ListModel; import software.amazon.awssdk.codegen.model.intermediate.MapModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.ParameterHttpMapping; import software.amazon.awssdk.codegen.model.intermediate.Protocol; import software.amazon.awssdk.codegen.model.intermediate.ReturnTypeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.VariableModel; import software.amazon.awssdk.codegen.model.service.Location; import software.amazon.awssdk.codegen.model.service.Member; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Shape; import software.amazon.awssdk.codegen.naming.NamingStrategy; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; abstract class AddShapes { private final IntermediateModelBuilder builder; private final NamingStrategy namingStrategy; AddShapes(IntermediateModelBuilder builder) { this.builder = builder; this.namingStrategy = builder.getNamingStrategy(); } protected final TypeUtils getTypeUtils() { return builder.getTypeUtils(); } protected final NamingStrategy getNamingStrategy() { return namingStrategy; } protected final ServiceModel getServiceModel() { return builder.getService(); } protected final CustomizationConfig getCustomizationConfig() { return builder.getCustomConfig(); } protected final ShapeModel generateShapeModel(String javaClassName, String shapeName) { ShapeModel shapeModel = new ShapeModel(shapeName); shapeModel.setShapeName(javaClassName); Shape shape = getServiceModel().getShapes().get(shapeName); shapeModel.setDocumentation(shape.getDocumentation()); shapeModel.setVariable(new VariableModel(getNamingStrategy().getVariableName(javaClassName), javaClassName)); // contains the list of c2j member names that are required for this shape. shapeModel.setRequired(shape.getRequired()); shapeModel.setDeprecated(shape.isDeprecated()); shapeModel.setDeprecatedMessage(shape.getDeprecatedMessage()); shapeModel.setWrapper(shape.isWrapper()); shapeModel.withIsEventStream(shape.isEventstream()); shapeModel.withIsEvent(shape.isEvent()); shapeModel.withXmlNamespace(shape.getXmlNamespace()); shapeModel.withIsUnion(shape.isUnion()); shapeModel.withIsFault(shape.isFault()); boolean hasHeaderMember = false; boolean hasStatusCodeMember = false; boolean hasPayloadMember = false; boolean hasStreamingMember = false; boolean hasRequiresLength = false; Map<String, Member> members = shape.getMembers(); if (members != null) { for (Map.Entry<String, Member> memberEntry : members.entrySet()) { String c2jMemberName = memberEntry.getKey(); Member c2jMemberDefinition = memberEntry.getValue(); Shape parentShape = shape; MemberModel memberModel = generateMemberModel(c2jMemberName, c2jMemberDefinition, getProtocol(), parentShape, getServiceModel().getShapes()); if (memberModel.getHttp().getLocation() == Location.HEADER) { hasHeaderMember = true; } else if (memberModel.getHttp().getLocation() == Location.STATUS_CODE) { hasStatusCodeMember = true; } else if (memberModel.getHttp().getIsPayload()) { hasPayloadMember = true; if (memberModel.getHttp().getIsStreaming()) { hasStreamingMember = true; } if (memberModel.getHttp().isRequiresLength()) { hasRequiresLength = true; } } shapeModel.addMember(memberModel); } shapeModel.withHasHeaderMember(hasHeaderMember) .withHasStatusCodeMember(hasStatusCodeMember) .withHasPayloadMember(hasPayloadMember) .withHasStreamingMember(hasStreamingMember) .withHasRequiresLengthMember(hasRequiresLength); } List<String> enumValues = shape.getEnumValues(); if (enumValues != null && !enumValues.isEmpty()) { for (String enumValue : enumValues) { shapeModel.addEnum( new EnumModel(getNamingStrategy().getEnumValueName(enumValue), enumValue)); } } return shapeModel; } private MemberModel generateMemberModel(String c2jMemberName, Member c2jMemberDefinition, String protocol, Shape parentShape, Map<String, Shape> allC2jShapes) { String c2jShapeName = c2jMemberDefinition.getShape(); Shape shape = allC2jShapes.get(c2jShapeName); String variableName = getNamingStrategy().getVariableName(c2jMemberName); String variableType = getTypeUtils().getJavaDataType(allC2jShapes, c2jShapeName); String variableDeclarationType = getTypeUtils() .getJavaDataType(allC2jShapes, c2jShapeName, getCustomizationConfig()); //If member is idempotent, then it should be of string type //Else throw IllegalArgumentException. if (c2jMemberDefinition.isIdempotencyToken() && !variableType.equals(String.class.getSimpleName())) { throw new IllegalArgumentException(c2jMemberName + " is idempotent. It's shape should be string type but it is of " + variableType + " type."); } MemberModel memberModel = new MemberModel(); memberModel.withC2jName(c2jMemberName) .withC2jShape(c2jShapeName) .withName(capitalize(c2jMemberName)) .withVariable(new VariableModel(variableName, variableType, variableDeclarationType) .withDocumentation(c2jMemberDefinition.getDocumentation())) .withSetterModel(new VariableModel(variableName, variableType, variableDeclarationType)) .withGetterModel(new ReturnTypeModel(variableType)) .withTimestampFormat(resolveTimestampFormat(c2jMemberDefinition, shape)) .withJsonValue(c2jMemberDefinition.getJsonvalue()); memberModel.setDocumentation(c2jMemberDefinition.getDocumentation()); memberModel.setDeprecated(c2jMemberDefinition.isDeprecated()); memberModel.setDeprecatedMessage(c2jMemberDefinition.getDeprecatedMessage()); memberModel.setSensitive(isSensitiveShapeOrContainer(c2jMemberDefinition, allC2jShapes)); memberModel .withFluentGetterMethodName(namingStrategy.getFluentGetterMethodName(c2jMemberName, parentShape, shape)) .withFluentEnumGetterMethodName(namingStrategy.getFluentEnumGetterMethodName(c2jMemberName, parentShape, shape)) .withFluentSetterMethodName(namingStrategy.getFluentSetterMethodName(c2jMemberName, parentShape, shape)) .withFluentEnumSetterMethodName(namingStrategy.getFluentEnumSetterMethodName(c2jMemberName, parentShape, shape)) .withExistenceCheckMethodName(namingStrategy.getExistenceCheckMethodName(c2jMemberName, parentShape)) .withBeanStyleGetterMethodName(namingStrategy.getBeanStyleGetterMethodName(c2jMemberName, parentShape, shape)) .withBeanStyleSetterMethodName(namingStrategy.getBeanStyleSetterMethodName(c2jMemberName, parentShape, shape)); memberModel.setIdempotencyToken(c2jMemberDefinition.isIdempotencyToken()); memberModel.setEventPayload(c2jMemberDefinition.isEventpayload()); memberModel.setEventHeader(c2jMemberDefinition.isEventheader()); memberModel.setEndpointDiscoveryId(c2jMemberDefinition.isEndpointdiscoveryid()); memberModel.setXmlAttribute(c2jMemberDefinition.isXmlAttribute()); memberModel.setUnionEnumTypeName(namingStrategy.getUnionEnumTypeName(memberModel)); memberModel.setContextParam(c2jMemberDefinition.getContextParam()); memberModel.setRequired(isRequiredMember(c2jMemberName, parentShape)); memberModel.setSynthetic(shape.isSynthetic()); // Pass the xmlNameSpace from the member reference if (c2jMemberDefinition.getXmlNamespace() != null) { memberModel.setXmlNameSpaceUri(c2jMemberDefinition.getXmlNamespace().getUri()); } // Additional member model metadata for list/map/enum types fillContainerTypeMemberMetadata(allC2jShapes, c2jMemberDefinition.getShape(), memberModel, protocol); String deprecatedName = c2jMemberDefinition.getDeprecatedName(); if (StringUtils.isNotBlank(deprecatedName)) { checkForValidDeprecatedName(c2jMemberName, shape); memberModel.setDeprecatedName(deprecatedName); memberModel.setDeprecatedFluentGetterMethodName( namingStrategy.getFluentGetterMethodName(deprecatedName, parentShape, shape)); memberModel.setDeprecatedFluentSetterMethodName( namingStrategy.getFluentSetterMethodName(deprecatedName, parentShape, shape)); memberModel.setDeprecatedBeanStyleSetterMethodName( namingStrategy.getBeanStyleSetterMethodName(deprecatedName, parentShape, shape)); } ParameterHttpMapping httpMapping = generateParameterHttpMapping(parentShape, c2jMemberName, c2jMemberDefinition, protocol, allC2jShapes); String payload = parentShape.getPayload(); boolean shapeIsStreaming = shape.isStreaming(); boolean memberIsStreaming = c2jMemberDefinition.isStreaming(); boolean payloadIsStreaming = shapeIsStreaming || memberIsStreaming; boolean requiresLength = shape.isRequiresLength() || c2jMemberDefinition.isRequiresLength(); httpMapping.withPayload(payload != null && payload.equals(c2jMemberName)) .withStreaming(payloadIsStreaming) .withRequiresLength(requiresLength); memberModel.setHttp(httpMapping); return memberModel; } private void checkForValidDeprecatedName(String c2jMemberName, Shape memberShape) { if (memberShape.getEnumValues() != null) { throw new IllegalStateException(String.format( "Member %s has enum values and a deprecated name. Codegen does not support this.", c2jMemberName)); } if (isListShape(memberShape)) { throw new IllegalStateException(String.format( "Member %s is a list and has a deprecated name. Codegen does not support this.", c2jMemberName)); } if (isMapShape(memberShape)) { throw new IllegalStateException(String.format( "Member %s is a map and has a deprecated name. Codegen does not support this.", c2jMemberName)); } } private boolean isSensitiveShapeOrContainer(Member member, Map<String, Shape> allC2jShapes) { if (member == null) { return false; } return member.isSensitive() || isSensitiveShapeOrContainer(allC2jShapes.get(member.getShape()), allC2jShapes); } private boolean isSensitiveShapeOrContainer(Shape c2jShape, Map<String, Shape> allC2jShapes) { if (c2jShape == null) { return false; } return c2jShape.isSensitive() || isSensitiveShapeOrContainer(c2jShape.getListMember(), allC2jShapes) || isSensitiveShapeOrContainer(c2jShape.getMapKeyType(), allC2jShapes) || isSensitiveShapeOrContainer(c2jShape.getMapValueType(), allC2jShapes); } private String resolveTimestampFormat(Member c2jMemberDefinition, Shape c2jShape) { return c2jMemberDefinition.getTimestampFormat() != null ? c2jMemberDefinition.getTimestampFormat() : c2jShape.getTimestampFormat(); } private ParameterHttpMapping generateParameterHttpMapping(Shape parentShape, String memberName, Member member, String protocol, Map<String, Shape> allC2jShapes) { ParameterHttpMapping mapping = new ParameterHttpMapping(); Shape memberShape = allC2jShapes.get(member.getShape()); mapping.withLocation(Location.forValue(member.getLocation())) .withPayload(member.isPayload()).withStreaming(member.isStreaming()) .withFlattened(isFlattened(member, memberShape)) .withUnmarshallLocationName(deriveUnmarshallerLocationName(memberShape, memberName, member)) .withMarshallLocationName( deriveMarshallerLocationName(memberShape, memberName, member, protocol)) .withIsGreedy(isGreedy(parentShape, allC2jShapes, mapping)); return mapping; } private boolean isFlattened(Member member, Shape memberShape) { return member.isFlattened() || memberShape.isFlattened(); } private boolean isRequiredMember(String memberName, Shape memberShape) { return Optional.ofNullable(memberShape.getRequired()) .map(l -> l.contains(memberName)) .orElse(false); } /** * @param parentShape Shape containing the member in question. * @param allC2jShapes All shapes in the service model. * @param mapping Mapping being built. * @return True if the member is bound to a greedy label, false otherwise. */ private boolean isGreedy(Shape parentShape, Map<String, Shape> allC2jShapes, ParameterHttpMapping mapping) { if (mapping.getLocation() == Location.URI) { // If the location is URI we can assume the parent shape is an input shape. String requestUri = findRequestUri(parentShape, allC2jShapes); if (requestUri.contains(String.format("{%s+}", mapping.getMarshallLocationName()))) { return true; } } return false; } /** * Given an input shape, finds the Request URI for the operation that input is referenced from. * * @param parentShape Input shape to find operation's request URI for. * @param allC2jShapes All shapes in the service model. * @return Request URI for operation. * @throws RuntimeException If operation can't be found. */ private String findRequestUri(Shape parentShape, Map<String, Shape> allC2jShapes) { return builder.getService().getOperations().values().stream() .filter(o -> o.getInput() != null) .filter(o -> allC2jShapes.get(o.getInput().getShape()).equals(parentShape)) .map(o -> o.getHttp().getRequestUri()) .findFirst().orElseThrow(() -> new RuntimeException("Could not find request URI for input shape")); } private String deriveUnmarshallerLocationName(Shape memberShape, String memberName, Member member) { String locationName; if (memberShape.getListMember() != null && memberShape.isFlattened()) { locationName = deriveLocationNameForListMember(memberShape, member); } else { locationName = member.getLocationName(); } if (StringUtils.isNotBlank(locationName)) { return locationName; } return memberName; } private String deriveMarshallerLocationName(Shape memberShape, String memberName, Member member, String protocol) { String queryName = member.getQueryName(); if (StringUtils.isNotBlank(queryName)) { return queryName; } String locationName; if (Protocol.EC2.getValue().equalsIgnoreCase(protocol)) { locationName = deriveLocationNameForEc2(member); } else if (memberShape.getListMember() != null && memberShape.isFlattened()) { locationName = deriveLocationNameForListMember(memberShape, member); } else { locationName = member.getLocationName(); } if (StringUtils.isNotBlank(locationName)) { return locationName; } return memberName; } private String deriveLocationNameForEc2(Member member) { String locationName = member.getLocationName(); if (StringUtils.isNotBlank(locationName)) { return StringUtils.upperCase(locationName.substring(0, 1)) + locationName.substring(1); } return null; } private String deriveLocationNameForListMember(Shape memberShape, Member member) { String locationName = memberShape.getListMember().getLocationName(); if (StringUtils.isNotBlank(locationName)) { return locationName; } return member.getLocationName(); } private void fillContainerTypeMemberMetadata(Map<String, Shape> c2jShapes, String memberC2jShapeName, MemberModel memberModel, String protocol) { Shape memberC2jShape = c2jShapes.get(memberC2jShapeName); if (isListShape(memberC2jShape)) { Member listMemberDefinition = memberC2jShape.getListMember(); String listMemberC2jShapeName = listMemberDefinition.getShape(); MemberModel listMemberModel = generateMemberModel("member", listMemberDefinition, protocol, memberC2jShape, c2jShapes); String listImpl = getDataTypeMapping(TypeUtils.TypeKey.LIST_DEFAULT_IMPL); memberModel.setListModel( new ListModel(getTypeUtils().getJavaDataType(c2jShapes, listMemberC2jShapeName), memberC2jShape.getListMember().getLocationName(), listImpl, getDataTypeMapping(TypeUtils.TypeKey.LIST_INTERFACE), listMemberModel)); } else if (isMapShape(memberC2jShape)) { Member mapKeyMemberDefinition = memberC2jShape.getMapKeyType(); String mapKeyShapeName = mapKeyMemberDefinition.getShape(); Shape mapKeyShape = c2jShapes.get(mapKeyShapeName); Member mapValueMemberDefinition = memberC2jShape.getMapValueType(); // Complex map keys are not supported. Validate.isTrue(isScalar(mapKeyShape), "The key type of %s must be a scalar!", mapKeyShapeName); MemberModel mapKeyModel = generateMemberModel("key", mapKeyMemberDefinition, protocol, memberC2jShape, c2jShapes); MemberModel mapValueModel = generateMemberModel("value", mapValueMemberDefinition, protocol, memberC2jShape, c2jShapes); String mapImpl = getDataTypeMapping(TypeUtils.TypeKey.MAP_DEFAULT_IMPL); String keyLocation = memberC2jShape.getMapKeyType().getLocationName() != null ? memberC2jShape.getMapKeyType().getLocationName() : "key"; String valueLocation = memberC2jShape.getMapValueType().getLocationName() != null ? memberC2jShape.getMapValueType().getLocationName() : "value"; memberModel.setMapModel(new MapModel(mapImpl, getDataTypeMapping(TypeUtils.TypeKey.MAP_INTERFACE), keyLocation, mapKeyModel, valueLocation, mapValueModel)); } else if (memberC2jShape.getEnumValues() != null) { // enum values memberModel.withEnumType(getNamingStrategy().getShapeClassName(memberC2jShapeName)); } } protected String getProtocol() { return getServiceModel().getMetadata().getProtocol(); } }
3,356
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/IntermediateModelShapeProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import java.util.Map; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; /** * Interface used by the {@link IntermediateModelBuilder} to process the service model to add and * modify ShapeModels to the {@link software.amazon.awssdk.codegen.model.intermediate.IntermediateModel}. */ public interface IntermediateModelShapeProcessor { /** * @param currentOperations Current operations that have been added to the intermediate model. * @param currentShapes Current shapes that have been added to the intermediate model * @return Map of shape name to ShapeModel to add to the intermediate model. */ Map<String, ShapeModel> process(Map<String, OperationModel> currentOperations, Map<String, ShapeModel> currentShapes); }
3,357
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/AddOutputShapes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.intermediate.ShapeUnmarshaller; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.Output; import software.amazon.awssdk.codegen.model.service.Shape; /** * Constructs the result shapes for the intermediate model. Analyzes the operations in the service * model to identify the result shapes that are to be generated. */ final class AddOutputShapes extends AddShapes implements IntermediateModelShapeProcessor { AddOutputShapes(IntermediateModelBuilder builder) { super(builder); } @Override public Map<String, ShapeModel> process(Map<String, OperationModel> currentOperations, Map<String, ShapeModel> currentShapes) { return constructOutputShapes(); } private Map<String, ShapeModel> constructOutputShapes() { // C2j model components Map<String, Operation> operations = getServiceModel().getOperations(); Map<String, Shape> c2jShapes = getServiceModel().getShapes(); // Java shape models, to be constructed Map<String, ShapeModel> javaShapes = new HashMap<>(); for (Map.Entry<String, Operation> entry : operations.entrySet()) { String operationName = entry.getKey(); Operation operation = entry.getValue(); Output output = operation.getOutput(); if (output != null) { String javaResponseClassName = getNamingStrategy() .getResponseClassName(operationName); ShapeModel outputShape = generateOutputShapeModel(operation, javaResponseClassName, c2jShapes); if (outputShape.getDocumentation() == null) { outputShape.setDocumentation(output.getDocumentation()); } javaShapes.put(javaResponseClassName, outputShape); } } return javaShapes; } private ShapeModel generateOutputShapeModel(Operation c2jOperationModel, String javaOutputShapeNameOverride, Map<String, Shape> c2jShapes) { Output c2jOutputModel = c2jOperationModel.getOutput(); String c2jOutputShapeName = c2jOutputModel.getShape(); ShapeModel shapeModel = generateShapeModel(javaOutputShapeNameOverride, c2jOutputShapeName); shapeModel.setType(ShapeType.Response.getValue()); // Set up unmarshaller metadata ShapeUnmarshaller shapeUnmarshaller = new ShapeUnmarshaller() .withFlattened(c2jShapes.get(c2jOutputShapeName).isFlattened()) .withResultWrapper(c2jOutputModel.getResultWrapper()); shapeModel.setUnmarshaller(shapeUnmarshaller); return shapeModel; } }
3,358
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/CodeGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import com.squareup.javapoet.ClassName; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.concurrent.ForkJoinTask; import software.amazon.awssdk.codegen.emitters.GeneratorTask; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.emitters.tasks.AwsGeneratorTasks; import software.amazon.awssdk.codegen.internal.Jackson; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; public class CodeGenerator { private static final String MODEL_DIR_NAME = "models"; private final C2jModels models; private final String sourcesDirectory; private final String resourcesDirectory; private final String testsDirectory; /** * The prefix for the file name that contains the intermediate model. */ private final String fileNamePrefix; static { // Make sure ClassName is statically initialized before we do anything in parallel. // Parallel static initialization of ClassName and TypeName can result in a deadlock: // https://github.com/square/javapoet/issues/799 ClassName.get(Object.class); } public CodeGenerator(Builder builder) { this.models = builder.models; this.sourcesDirectory = builder.sourcesDirectory; this.testsDirectory = builder.testsDirectory; this.resourcesDirectory = builder.resourcesDirectory != null ? builder.resourcesDirectory : builder.sourcesDirectory; this.fileNamePrefix = builder.fileNamePrefix; } public static File getModelDirectory(String outputDirectory) { File dir = new File(outputDirectory, MODEL_DIR_NAME); Utils.createDirectory(dir); return dir; } /** * @return Builder instance to construct a {@link CodeGenerator}. */ public static Builder builder() { return new Builder(); } /** * load ServiceModel. load code gen configuration from individual client. generate intermediate model. generate * code. */ public void execute() { try { IntermediateModel intermediateModel = new IntermediateModelBuilder(models).build(); if (fileNamePrefix != null) { writeIntermediateModel(intermediateModel); } emitCode(intermediateModel); } catch (Exception e) { throw new RuntimeException( "Failed to generate code. Exception message : " + e.getMessage(), e); } } private void writeIntermediateModel(IntermediateModel model) throws IOException { File modelDir = getModelDirectory(sourcesDirectory); PrintWriter writer = null; try { File outDir = new File(sourcesDirectory); if (!outDir.exists()) { if (!outDir.mkdirs()) { throw new RuntimeException("Failed to create " + outDir.getAbsolutePath()); } } File outputFile = new File(modelDir, fileNamePrefix + "-intermediate.json"); if (!outputFile.exists()) { if (!outputFile.createNewFile()) { throw new RuntimeException("Error creating file " + outputFile.getAbsolutePath()); } } writer = new PrintWriter(outputFile, "UTF-8"); Jackson.writeWithObjectMapper(model, writer); } finally { if (writer != null) { writer.flush(); writer.close(); } } } private void emitCode(IntermediateModel intermediateModel) { ForkJoinTask.invokeAll(createGeneratorTasks(intermediateModel)); } private GeneratorTask createGeneratorTasks(IntermediateModel intermediateModel) { return new AwsGeneratorTasks(GeneratorTaskParams.create(intermediateModel, sourcesDirectory, testsDirectory, resourcesDirectory)); } /** * Builder for a {@link CodeGenerator}. */ public static final class Builder { private C2jModels models; private String sourcesDirectory; private String resourcesDirectory; private String testsDirectory; private String fileNamePrefix; private Builder() { } public Builder models(C2jModels models) { this.models = models; return this; } public Builder sourcesDirectory(String sourcesDirectory) { this.sourcesDirectory = sourcesDirectory; return this; } public Builder resourcesDirectory(String resourcesDirectory) { this.resourcesDirectory = resourcesDirectory; return this; } public Builder testsDirectory(String smokeTestsDirectory) { this.testsDirectory = smokeTestsDirectory; return this; } public Builder intermediateModelFileNamePrefix(String fileNamePrefix) { this.fileNamePrefix = fileNamePrefix; return this; } /** * @return An immutable {@link CodeGenerator} object. */ public CodeGenerator build() { return new CodeGenerator(this); } } }
3,359
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/AddEmptyInputShape.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import static software.amazon.awssdk.codegen.internal.Utils.createInputShapeMarshaller; import static software.amazon.awssdk.codegen.internal.Utils.unCapitalize; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.intermediate.VariableModel; import software.amazon.awssdk.codegen.model.service.Input; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.naming.NamingStrategy; /** * This class adds empty input shapes to those operations which doesn't accept any input params. It * also creates a shape model for the shape with no members in it. */ final class AddEmptyInputShape implements IntermediateModelShapeProcessor { private final ServiceModel serviceModel; private final NamingStrategy namingStrategy; AddEmptyInputShape(IntermediateModelBuilder builder) { this.serviceModel = builder.getService(); this.namingStrategy = builder.getNamingStrategy(); } @Override public Map<String, ShapeModel> process(Map<String, OperationModel> currentOperations, Map<String, ShapeModel> currentShapes) { return addEmptyInputShapes(currentOperations); } private Map<String, ShapeModel> addEmptyInputShapes( Map<String, OperationModel> javaOperationMap) { Map<String, Operation> operations = serviceModel.getOperations(); Map<String, ShapeModel> emptyInputShapes = new HashMap<>(); for (Map.Entry<String, Operation> entry : operations.entrySet()) { String operationName = entry.getKey(); Operation operation = entry.getValue(); Input input = operation.getInput(); if (input == null) { String inputShape = namingStrategy.getRequestClassName(operationName); OperationModel operationModel = javaOperationMap.get(operationName); operationModel.setInput(new VariableModel(unCapitalize(inputShape), inputShape)); ShapeModel shape = new ShapeModel(inputShape) .withType(ShapeType.Request.getValue()); shape.setShapeName(inputShape); VariableModel inputVariable = new VariableModel( namingStrategy.getVariableName(inputShape), inputShape); shape.setVariable(inputVariable); shape.setMarshaller( createInputShapeMarshaller(serviceModel.getMetadata(), operation)); emptyInputShapes.put(inputShape, shape); } } return emptyInputShapes; } }
3,360
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/AddExceptionShapes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.service.ErrorTrait; import software.amazon.awssdk.codegen.model.service.Shape; /** * Constructs the exception shapes for the intermediate model. Analyzes the operations in the * service model to identify the exception shapes that are to be generated. */ final class AddExceptionShapes extends AddShapes implements IntermediateModelShapeProcessor { AddExceptionShapes(IntermediateModelBuilder builder) { super(builder); } @Override public Map<String, ShapeModel> process(Map<String, OperationModel> currentOperations, Map<String, ShapeModel> currentShapes) { return constructExceptionShapes(); } private Map<String, ShapeModel> constructExceptionShapes() { // Java shape models, to be constructed Map<String, ShapeModel> javaShapes = new HashMap<>(); for (Map.Entry<String, Shape> shape : getServiceModel().getShapes().entrySet()) { if (shape.getValue().isException()) { String errorShapeName = shape.getKey(); String javaClassName = getNamingStrategy().getExceptionName(errorShapeName); ShapeModel exceptionShapeModel = generateShapeModel(javaClassName, errorShapeName); exceptionShapeModel.setType(ShapeType.Exception.getValue()); exceptionShapeModel.setErrorCode(getErrorCode(errorShapeName)); exceptionShapeModel.setHttpStatusCode(getHttpStatusCode(errorShapeName)); if (exceptionShapeModel.getDocumentation() == null) { exceptionShapeModel.setDocumentation(shape.getValue().getDocumentation()); } javaShapes.put(javaClassName, exceptionShapeModel); } } return javaShapes; } /** * The error code may be overridden for query or rest protocols via the error trait on the * exception shape. If the error code isn't overridden and for all other protocols other than * query or rest the error code should just be the shape name */ private String getErrorCode(String errorShapeName) { ErrorTrait errorTrait = getServiceModel().getShapes().get(errorShapeName).getError(); if (isErrorCodeOverridden(errorTrait)) { return errorTrait.getCode(); } else { return errorShapeName; } } private boolean isErrorCodeOverridden(ErrorTrait errorTrait) { return errorTrait != null && !Utils.isNullOrEmpty(errorTrait.getCode()); } private Integer getHttpStatusCode(String errorShapeName) { ErrorTrait errorTrait = getServiceModel().getShapes().get(errorShapeName).getError(); return errorTrait != null ? errorTrait.getHttpStatusCode() : null; } }
3,361
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/C2jModels.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.rules.endpoints.EndpointTestSuiteModel; import software.amazon.awssdk.codegen.model.service.EndpointRuleSetModel; import software.amazon.awssdk.codegen.model.service.Paginators; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Waiters; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Container for service models and config files. */ public class C2jModels { private final ServiceModel serviceModel; private final Waiters waitersModel; private final EndpointRuleSetModel endpointRuleSetModel; private final EndpointTestSuiteModel endpointTestSuiteModel; private final CustomizationConfig customizationConfig; private final Paginators paginatorsModel; private C2jModels(ServiceModel serviceModel, Waiters waitersModel, EndpointRuleSetModel endpointRuleSetModel, EndpointTestSuiteModel endpointTestSuiteModel, CustomizationConfig customizationConfig, Paginators paginatorsModel) { this.serviceModel = serviceModel; this.waitersModel = waitersModel; this.endpointRuleSetModel = endpointRuleSetModel; this.endpointTestSuiteModel = endpointTestSuiteModel; this.customizationConfig = customizationConfig; this.paginatorsModel = paginatorsModel; } public static Builder builder() { return new Builder(); } public ServiceModel serviceModel() { return serviceModel; } public Waiters waitersModel() { return waitersModel; } public CustomizationConfig customizationConfig() { return customizationConfig; } public Paginators paginatorsModel() { return paginatorsModel; } public EndpointRuleSetModel endpointRuleSetModel() { return endpointRuleSetModel; } public EndpointTestSuiteModel endpointTestSuiteModel() { return endpointTestSuiteModel; } public static class Builder implements SdkBuilder<Builder, C2jModels> { private ServiceModel serviceModel; private Waiters waitersModel; private EndpointRuleSetModel endpointRuleSetModel; private EndpointTestSuiteModel endpointTestSuiteModel; private CustomizationConfig customizationConfig; private Paginators paginatorsModel; private Builder() { } public Builder serviceModel(ServiceModel serviceModel) { this.serviceModel = serviceModel; return this; } public Builder waitersModel(Waiters waitersModel) { this.waitersModel = waitersModel; return this; } public Builder customizationConfig(CustomizationConfig customizationConfig) { this.customizationConfig = customizationConfig; return this; } public Builder paginatorsModel(Paginators paginatorsModel) { this.paginatorsModel = paginatorsModel; return this; } public Builder endpointRuleSetModel(EndpointRuleSetModel endpointRuleSetModel) { this.endpointRuleSetModel = endpointRuleSetModel; return this; } public Builder endpointTestSuiteModel(EndpointTestSuiteModel endpointTestSuiteModel) { this.endpointTestSuiteModel = endpointTestSuiteModel; return this; } @Override public C2jModels build() { Waiters waiters = waitersModel != null ? waitersModel : Waiters.none(); Paginators paginators = paginatorsModel != null ? paginatorsModel : Paginators.none(); return new C2jModels(serviceModel, waiters, endpointRuleSetModel, endpointTestSuiteModel, customizationConfig, paginators); } } }
3,362
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/CodegenCustomizationProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; public interface CodegenCustomizationProcessor { /** * Apply the customization by directly modifying the service model, before * the intermediate model is built. */ void preprocess(ServiceModel serviceModel); /** * Apply the customization after the intermediate model is built */ void postprocess(IntermediateModel intermediateModel); }
3,363
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/CodegenCustomizationProcessorChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; public final class CodegenCustomizationProcessorChain implements CodegenCustomizationProcessor { private final CodegenCustomizationProcessor[] processorChain; public CodegenCustomizationProcessorChain(CodegenCustomizationProcessor... processors) { this.processorChain = processors == null ? new CodegenCustomizationProcessor[0] : processors.clone() ; } @Override public void preprocess(ServiceModel serviceModel) { for (CodegenCustomizationProcessor processor : processorChain) { processor.preprocess(serviceModel); } } @Override public void postprocess(IntermediateModel intermediateModel) { for (CodegenCustomizationProcessor processor : processorChain) { processor.postprocess(intermediateModel); } } }
3,364
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/DefaultCustomizationProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessorChain; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; public final class DefaultCustomizationProcessor { private DefaultCustomizationProcessor() { } public static CodegenCustomizationProcessor getProcessorFor( CustomizationConfig config) { return new CodegenCustomizationProcessorChain( new MetadataModifiersProcessor(config.getCustomServiceMetadata()), new RenameShapesProcessor(config.getRenameShapes()), new ShapeModifiersProcessor(config.getShapeModifiers()), new ShapeSubstitutionsProcessor(config.getShapeSubstitutions()), new CustomSdkShapesProcessor(config.getCustomSdkShapes()), new OperationModifiersProcessor(config.getOperationModifiers()), new RemoveExceptionMessagePropertyProcessor(), new UseLegacyEventGenerationSchemeProcessor(), new NewAndLegacyEventStreamProcessor(), new S3RemoveBucketFromUriProcessor(), new S3ControlRemoveAccountIdHostPrefixProcessor(), new ExplicitStringPayloadQueryProtocolProcessor() ); } }
3,365
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/CustomSdkShapesProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import java.util.Map; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.model.config.customization.CustomSdkShapes; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Shape; public class CustomSdkShapesProcessor implements CodegenCustomizationProcessor { private final CustomSdkShapes customSdkShapes; CustomSdkShapesProcessor(CustomSdkShapes customSdkShapes) { this.customSdkShapes = customSdkShapes; } @Override public void preprocess(ServiceModel serviceModel) { if (customSdkShapes == null) { return; } Map<String, Shape> shapes = serviceModel.getShapes(); customSdkShapes.getShapes().forEach((shapeName, shape) -> { shape.setSynthetic(true); shapes.put(shapeName, shape); }); serviceModel.setShapes(shapes); } @Override public void postprocess(IntermediateModel intermediateModel) { // added custom shapes in service model instead of intermediate model } }
3,366
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/NewAndLegacyEventStreamProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; /** * Services that have "legacy" streams, Kinesis and Transcribe Streaming builds should fail if there is a new * evenstream added, that codegen doesn't know about. This is so we can decide if we want to generate the new stream in * the legacy style so they look like the existing streams, or if we use the new style (e.g. because it won't work with * the old style). */ public final class NewAndLegacyEventStreamProcessor implements CodegenCustomizationProcessor { // Map from service ID -> list of event streams we know about and approve private static final Map<String, Set<String>> APPROVED_EVENT_STREAMS; static { Map<String, Set<String>> approvedEventStreams = new HashMap<>(); approvedEventStreams.put("Kinesis", new HashSet<>(Arrays.asList("SubscribeToShardEventStream"))); approvedEventStreams.put("Transcribe Streaming", new HashSet<>(Arrays.asList("AudioStream", "TranscriptResultStream", "MedicalTranscriptResultStream", "CallAnalyticsTranscriptResultStream"))); APPROVED_EVENT_STREAMS = Collections.unmodifiableMap(approvedEventStreams); } @Override public void preprocess(ServiceModel serviceModel) { String serviceId = serviceModel.getMetadata().getServiceId(); if (!APPROVED_EVENT_STREAMS.containsKey(serviceId)) { return; } Set<String> approvedStreams = APPROVED_EVENT_STREAMS.get(serviceId); serviceModel.getShapes().entrySet().stream() .filter(e -> e.getValue().isEventstream()) .forEach(e -> { String name = e.getKey(); if (!approvedStreams.contains(name)) { throw unknownStreamError(serviceId, name); } }); } @Override public void postprocess(IntermediateModel intermediateModel) { // no-op } private static RuntimeException unknownStreamError(String serviceId, String evenstreamName) { String msg = String.format("Encountered a new eventstream for service %s: %s. This service contains " + "evenstreams that are code generated using an older style that requires a customization. Please " + "contact the Java SDK maintainers for assistance.", serviceId, evenstreamName); return new RuntimeException(msg); } }
3,367
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/UseLegacyEventGenerationSchemeProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.ServiceModel; /** * This process enforces constraints placed on the "useLegacyEventGenerationSchemeProcessor"; i.e. that no two members * of the same event stream sharing the same shape have this customization enabled for them. This processor does not * modify the the service or intermediate model. */ public class UseLegacyEventGenerationSchemeProcessor implements CodegenCustomizationProcessor { private static final String CUSTOMIZATION_NAME = "UseLegacyEventGenerationScheme"; private static final Logger log = LoggerFactory.getLogger(UseLegacyEventGenerationSchemeProcessor.class); @Override public void preprocess(ServiceModel serviceModel) { // no-op } @Override public void postprocess(IntermediateModel intermediateModel) { Map<String, List<String>> useLegacyEventGenerationScheme = intermediateModel.getCustomizationConfig() .getUseLegacyEventGenerationScheme(); useLegacyEventGenerationScheme.forEach((eventStream, members) -> { ShapeModel shapeModel = getShapeByC2jName(intermediateModel, eventStream); if (shapeModel == null || !shapeModel.isEventStream()) { log.warn(String.format("Encountered %s for unrecognized eventstream %s", CUSTOMIZATION_NAME, eventStream)); return; } Map<String, Integer> shapeToEventCount = new HashMap<>(); members.forEach(m -> { MemberModel event = shapeModel.getMemberByC2jName(m); if (event != null) { String shapeName = event.getC2jShape(); int count = shapeToEventCount.getOrDefault(shapeName, 0); shapeToEventCount.put(shapeName, ++count); } else { String msg = String.format("Encountered %s customization for unrecognized eventstream member %s#%s", CUSTOMIZATION_NAME, eventStream, m); log.warn(msg); } }); shapeToEventCount.forEach((shape, count) -> { if (count > 1) { throw new IllegalArgumentException(CUSTOMIZATION_NAME + " customization declared for " + eventStream + ", but more than it targets more than one member with the shape " + shape); } }); }); } private ShapeModel getShapeByC2jName(IntermediateModel intermediateModel, String c2jName) { return intermediateModel.getShapes().values().stream() .filter(s -> s.getC2jName().equals(c2jName)) .findAny() .orElse(null); } }
3,368
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/S3RemoveBucketFromUriProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.utils.StringUtils; /** * With Endpoints 2.0, the endpoint rule set for S3 is responsible for taking the {@code Bucket} parameter from the input and * adding it to the request URI. To make this work, we preprocess the model to remove it from the HTTP definition so that the * marshallers don't add it to the path as well. */ public class S3RemoveBucketFromUriProcessor implements CodegenCustomizationProcessor { private static final Logger log = LoggerFactory.getLogger(S3RemoveBucketFromUriProcessor.class); @Override public void preprocess(ServiceModel serviceModel) { if (!isS3(serviceModel)) { return; } log.info("Preprocessing S3 model to remove {Bucket} from request URIs"); serviceModel.getOperations().forEach(this::removeBucketFromUriIfNecessary); } @Override public void postprocess(IntermediateModel intermediateModel) { // no-op } private boolean isS3(ServiceModel serviceModel) { return "S3".equals(serviceModel.getMetadata().getServiceId()); } private void removeBucketFromUriIfNecessary(String opName, Operation operation) { String requestUri = operation.getHttp().getRequestUri(); String newUri = StringUtils.replaceOnce(requestUri, "/{Bucket}", ""); log.info("{}: replacing existing request URI '{}' with '{}", opName, requestUri, newUri); operation.getHttp().setRequestUri(newUri); } }
3,369
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/S3ControlRemoveAccountIdHostPrefixProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.EndpointTrait; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.ServiceModel; /** * With Endpoints 2.0, the endpoint rule set is responsible for adding the prefix, so we remove it from the model to avoid * errors in constructing the endpoint. */ public class S3ControlRemoveAccountIdHostPrefixProcessor implements CodegenCustomizationProcessor { private static final String ACCOUNT_ID_HOST_PREFIX = "{AccountId}."; private static final Logger log = LoggerFactory.getLogger(S3ControlRemoveAccountIdHostPrefixProcessor.class); @Override public void preprocess(ServiceModel serviceModel) { if (!isS3Control(serviceModel)) { return; } log.info("Preprocessing S3 Control model to remove '{AccountId}.' hostPrefix from operations"); serviceModel.getOperations().forEach(this::removeAccountIdHostPrefixIfNecessary); } @Override public void postprocess(IntermediateModel intermediateModel) { // no-op } private boolean isS3Control(ServiceModel serviceModel) { return "S3 Control".equals(serviceModel.getMetadata().getServiceId()); } private void removeAccountIdHostPrefixIfNecessary(String opName, Operation operation) { EndpointTrait endpoint = operation.getEndpoint(); if (endpoint == null) { return; } if (ACCOUNT_ID_HOST_PREFIX.equals(endpoint.getHostPrefix())) { log.info("{}: Removing '{AccountId}.' hostPrefix", opName); endpoint.setHostPrefix(null); } } }
3,370
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/ExplicitStringPayloadQueryProtocolProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import java.util.Map; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.Input; import software.amazon.awssdk.codegen.model.service.Member; import software.amazon.awssdk.codegen.model.service.Output; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Shape; /** * Operations with explicit String payloads are not supported for services with Query protocol. We fail the codegen if the * httpPayload or eventPayload trait is set on a String. */ public class ExplicitStringPayloadQueryProtocolProcessor implements CodegenCustomizationProcessor { @Override public void preprocess(ServiceModel serviceModel) { String protocol = serviceModel.getMetadata().getProtocol(); if (!"ec2".equals(protocol) && !"query".equals(protocol)) { return; } Map<String, Shape> c2jShapes = serviceModel.getShapes(); serviceModel.getOperations().forEach((operationName, op) -> { Input input = op.getInput(); if (input != null && isExplicitStringPayload(c2jShapes, c2jShapes.get(input.getShape()))) { throw new RuntimeException("Operations with explicit String payloads are not supported for Query " + "protocols. Unsupported operation: " + operationName); } Output output = op.getOutput(); if (output != null && isExplicitStringPayload(c2jShapes, c2jShapes.get(output.getShape()))) { throw new RuntimeException("Operations with explicit String payloads are not supported for Query " + "protocols. Unsupported operation: " + operationName); } }); } @Override public void postprocess(IntermediateModel intermediateModel) { // no-op } private boolean isExplicitStringPayload(Map<String, Shape> c2jShapes, Shape shape) { if (shape.getPayload() == null) { return false; } Member payloadMember = shape.getMembers().get(shape.getPayload()); Shape payloadShape = c2jShapes.get(payloadMember.getShape()); return payloadShape != null && "String".equalsIgnoreCase(payloadShape.getType()); } }
3,371
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/ShapeModifiersProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.config.customization.ModifyModelShapeModifier; import software.amazon.awssdk.codegen.model.config.customization.ShapeModifier; import software.amazon.awssdk.codegen.model.intermediate.EnumModel; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.Member; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Shape; /** * This processor handles all the modification on the shape members in the * pre-process step and then removes all the excluded shapes in the post-process * step. * * This processor can also modify the names of the enum values generated by the * code generator. */ final class ShapeModifiersProcessor implements CodegenCustomizationProcessor { private static final String ALL = "*"; private final Map<String, ShapeModifier> shapeModifiers; ShapeModifiersProcessor( Map<String, ShapeModifier> shapeModifiers) { this.shapeModifiers = shapeModifiers; } @Override public void preprocess(ServiceModel serviceModel) { if (shapeModifiers == null) { return; } for (Entry<String, ShapeModifier> entry : shapeModifiers.entrySet()) { String key = entry.getKey(); ShapeModifier modifier = entry.getValue(); if (ALL.equals(key)) { for (Shape shape : serviceModel.getShapes().values()) { preprocessModifyShapeMembers(serviceModel, shape, modifier); } } else { Shape shape = serviceModel.getShapes().get(key); if (shape == null) { throw new IllegalStateException( "ShapeModifier customization found for " + key + ", but this shape doesn't exist in the model!"); } preprocessModifyShapeMembers(serviceModel, shape, modifier); } } } @Override public void postprocess(IntermediateModel intermediateModel) { if (shapeModifiers == null) { return; } for (Entry<String, ShapeModifier> entry : shapeModifiers.entrySet()) { String key = entry.getKey(); ShapeModifier modifier = entry.getValue(); if (ALL.equals(key)) { continue; } List<ShapeModel> shapeModels = Utils.findShapesByC2jName(intermediateModel, key); if (shapeModels.isEmpty()) { throw new IllegalStateException(String.format( "Cannot find c2j shape [%s] in the intermediate model when processing " + "customization config shapeModifiers.%s", key, key)); } shapeModels.forEach(shapeModel -> { if (modifier.getStaxTargetDepthOffset() != null) { shapeModel.getCustomization().setStaxTargetDepthOffset(modifier.getStaxTargetDepthOffset()); } if (modifier.isExcludeShape()) { shapeModel.getCustomization().setSkipGeneratingModelClass(true); shapeModel.getCustomization().setSkipGeneratingMarshaller(true); shapeModel.getCustomization().setSkipGeneratingUnmarshaller(true); } else if (modifier.getModify() != null) { // Modifies properties of a member in shape or shape enum. // This customization currently support modifying enum name // and marshall/unmarshall location of a member in the Shape. modifier.getModify().stream().flatMap(m -> m.entrySet().stream()).forEach(memberEntry -> postprocessModifyMemberProperty(shapeModel, memberEntry.getKey(), memberEntry.getValue()) ); } }); } } /** * Override name of the enums, marshall/unmarshall location of the * members in the given shape model. */ private void postprocessModifyMemberProperty(ShapeModel shapeModel, String memberName, ModifyModelShapeModifier modifyModel) { if (modifyModel.getEmitEnumName() != null) { EnumModel enumModel = shapeModel.findEnumModelByValue(memberName); if (enumModel == null) { throw new IllegalStateException( String.format("Cannot find enum [%s] in the intermediate model when processing " + "customization config shapeModifiers.%s", memberName, memberName)); } enumModel.setName(modifyModel.getEmitEnumName()); } if (modifyModel.getEmitEnumValue() != null) { EnumModel enumModel = shapeModel.findEnumModelByValue(memberName); if (enumModel == null) { throw new IllegalStateException( String.format("Cannot find enum [%s] in the intermediate model when processing " + "customization config shapeModifiers.%s", memberName, memberName)); } enumModel.setValue(modifyModel.getEmitEnumValue()); } if (modifyModel.getMarshallLocationName() != null) { MemberModel memberModel = shapeModel.findMemberModelByC2jName(memberName); memberModel.getHttp().setMarshallLocationName(modifyModel.getMarshallLocationName()); } if (modifyModel.getUnmarshallLocationName() != null) { MemberModel memberModel = shapeModel.findMemberModelByC2jName(memberName); memberModel.getHttp().setUnmarshallLocationName(modifyModel .getUnmarshallLocationName()); } } /** * Exclude/modify/inject shape members */ private void preprocessModifyShapeMembers(ServiceModel serviceModel, Shape shape, ShapeModifier modifier) { if (modifier.getModify() != null) { for (Map<String, ModifyModelShapeModifier> modifies : modifier.getModify()) { for (Entry<String, ModifyModelShapeModifier> entry : modifies.entrySet()) { String memberToModify = entry.getKey(); ModifyModelShapeModifier modifyModel = entry.getValue(); doModifyShapeMembers(serviceModel, shape, memberToModify, modifyModel); } } } if (modifier.getExclude() != null) { for (String memberToExclude : modifier.getExclude()) { if (shape.getRequired() != null && shape.getRequired().contains(memberToExclude)) { throw new IllegalStateException( "ShapeModifier.exclude customization found for " + memberToExclude + ", but this member is marked as required in the model!"); } if (shape.getMembers() != null) { shape.getMembers().remove(memberToExclude); } } } if (modifier.getInject() != null) { for (Map<String, Member> injects : modifier.getInject()) { if (shape.getMembers() == null) { shape.setMembers(new HashMap<>()); } shape.getMembers().putAll(injects); } } if (modifier.isUnion() != null) { shape.setUnion(modifier.isUnion()); } } private void doModifyShapeMembers(ServiceModel serviceModel, Shape shape, String memberToModify, ModifyModelShapeModifier modifyModel) { if (modifyModel.isDeprecated()) { Member member = shape.getMembers().get(memberToModify); member.setDeprecated(true); if (modifyModel.getDeprecatedMessage() != null) { member.setDeprecatedMessage(modifyModel.getDeprecatedMessage()); } } // Currently only supports emitPropertyName which is to rename the member if (modifyModel.getEmitPropertyName() != null) { Member member = shape.getMembers().remove(memberToModify); // if location name is not present, set it to the original name // to avoid breaking marshaller code if (member.getLocationName() == null) { member.setLocationName(memberToModify); } if (modifyModel.isExistingNameDeprecated()) { member.setDeprecatedName(memberToModify); } shape.getMembers().put(modifyModel.getEmitPropertyName(), member); } if (modifyModel.getEmitAsType() != null) { // Must create a shape for the primitive type. Shape newShapeForType = new Shape(); newShapeForType.setType(modifyModel.getEmitAsType()); String shapeName = "SDK_" + modifyModel.getEmitAsType(); serviceModel.getShapes().put(shapeName, newShapeForType); shape.getMembers().get(memberToModify).setShape(shapeName); } } }
3,372
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/OperationModifiersProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.internal.Constant; import software.amazon.awssdk.codegen.model.config.customization.OperationModifier; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.customization.ArtificialResultWrapper; import software.amazon.awssdk.codegen.model.service.Member; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Shape; import software.amazon.awssdk.codegen.model.service.ShapeType; /** * This processor internally keeps track of all the result wrapper shapes it * created during pre-processing, therefore the caller needs to make sure this * processor is only invoked once. */ final class OperationModifiersProcessor implements CodegenCustomizationProcessor { private final Map<String, OperationModifier> operationModifiers; private final Set<String> createdWrapperShapes = new HashSet<>(); OperationModifiersProcessor(Map<String, OperationModifier> operationModifiers) { this.operationModifiers = operationModifiers; } @Override public void preprocess(ServiceModel serviceModel) { if (operationModifiers == null) { return; } for (Entry<String, OperationModifier> entry : operationModifiers.entrySet()) { String operationName = entry.getKey(); OperationModifier modifier = entry.getValue(); if (modifier.isExclude()) { preprocessExclude(serviceModel, operationName); continue; } if (modifier.isUseWrappingResult()) { String createdWrapperShape = preprocessCreateResultWrapperShape( serviceModel, operationName, modifier); // Keep track of all the wrappers we created createdWrapperShapes.add(createdWrapperShape); } } } @Override public void postprocess(IntermediateModel intermediateModel) { if (operationModifiers == null) { return; } // Find all the wrapper shapes in the intermediate model (by its // "original" c2j name), and add the customization metadata for (ShapeModel shape : intermediateModel.getShapes().values()) { if (!createdWrapperShapes.contains(shape.getC2jName())) { continue; } if (shape.getMembers().size() != 1) { throw new IllegalStateException("Result wrapper " + shape.getShapeName() + " has not just one member!"); } MemberModel wrappedMember = shape.getMembers().get(0); /* * "RunInstancesResult" : { * "customization" : { * "artificialResultWrapper" : { * "wrappedMemberName" : "Reservation", * "wrappedMemberSimpleType" : "Reservation" * } * } * } */ shape.getCustomization().setArtificialResultWrapper( createArtificialResultWrapperInfo( shape, wrappedMember)); } } private void preprocessExclude(ServiceModel serviceModel, String operationName) { Operation operation = serviceModel.getOperation(operationName); // Remove input and output shapes of the operation serviceModel.getShapes().remove(operation.getInput().getShape()); serviceModel.getShapes().remove(operation.getOutput().getShape()); serviceModel.getOperations().remove(operationName); } private String preprocessCreateResultWrapperShape(ServiceModel serviceModel, String operationName, OperationModifier modifier) { String wrappedShapeName = modifier.getWrappedResultShape(); Shape wrappedShape = serviceModel.getShapes().get(wrappedShapeName); String wrapperShapeName = operationName + Constant.RESPONSE_CLASS_SUFFIX; String wrappedAsMember = modifier.getWrappedResultMember(); if (serviceModel.getShapes().containsKey(wrapperShapeName)) { throw new IllegalStateException(wrapperShapeName + " shape already exists in the service model."); } Shape wrapperShape = createWrapperShape(wrapperShapeName, wrappedShapeName, wrappedShape, wrappedAsMember); // Add the new shape to the model serviceModel.getShapes().put(wrapperShapeName, wrapperShape); // Update the operation model to point to this new shape Operation operation = serviceModel.getOperations().get(operationName); operation.getOutput().setShape(wrapperShapeName); return wrapperShapeName; } private Shape createWrapperShape(String wrapperShapeName, String wrappedShapeName, Shape wrapped, String wrappedAsMember) { Shape wrapper = new Shape(); wrapper.setType(ShapeType.Structure.getName()); wrapper.setDocumentation("A simple result wrapper around the " + wrappedShapeName + " object that was sent over the wire."); Member member = new Member(); member.setShape(wrappedShapeName); member.setDocumentation(wrapped.getDocumentation()); wrapper.setMembers(Collections.singletonMap(wrappedAsMember, member)); return wrapper; } private ArtificialResultWrapper createArtificialResultWrapperInfo(ShapeModel shape, MemberModel wrappedMember) { ArtificialResultWrapper wrapper = new ArtificialResultWrapper(); wrapper.setWrappedMemberName(wrappedMember.getName()); wrapper.setWrappedMemberSimpleType(wrappedMember.getVariable().getSimpleType()); return wrapper; } }
3,373
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/MetadataModifiersProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.model.config.customization.MetadataConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.service.ServiceMetadata; import software.amazon.awssdk.codegen.model.service.ServiceModel; /** * This processor handles preprocess modifications to service metadata and * postprocess modifications to intermediate model metadata. */ public class MetadataModifiersProcessor implements CodegenCustomizationProcessor { private final MetadataConfig metadataConfig; MetadataModifiersProcessor(MetadataConfig metadataConfig) { this.metadataConfig = metadataConfig; } @Override public void preprocess(ServiceModel serviceModel) { if (metadataConfig == null) { return; } ServiceMetadata serviceMetadata = serviceModel.getMetadata(); String customProtocol = metadataConfig.getProtocol(); if (customProtocol != null) { serviceMetadata.setProtocol(customProtocol); } } @Override public void postprocess(IntermediateModel intermediateModel) { if (metadataConfig == null) { return; } Metadata metadata = intermediateModel.getMetadata(); String contentType = metadataConfig.getContentType(); if (contentType != null) { metadata.setContentType(contentType); } } }
3,374
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/RenameShapesProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import java.util.Map; import java.util.Map.Entry; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ErrorMap; import software.amazon.awssdk.codegen.model.service.Input; import software.amazon.awssdk.codegen.model.service.Member; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.Output; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Shape; public class RenameShapesProcessor implements CodegenCustomizationProcessor { private final Map<String, String> renameShapes; public RenameShapesProcessor(Map<String, String> renameShapes) { this.renameShapes = renameShapes; } /** * Rename shapes for Member, Input, Output, ErrorMap, as well as the key for two maps: * serviceModel.shape() and shapeModifiers */ @Override public void preprocess(ServiceModel serviceModel) { if (renameShapes == null || renameShapes.isEmpty()) { return; } // sanity check for (Entry<String, String> entry : renameShapes.entrySet()) { String originalName = entry.getKey(); String newName = entry.getValue(); Shape originalShape = serviceModel.getShapes().get(originalName); if (originalShape == null) { throw new IllegalStateException( String.format("Cannot find shape [%s] in the model when processing " + "customization config renameShapes.%s", originalName, originalName)); } if (serviceModel.getShapes().containsKey(newName)) { throw new IllegalStateException( String.format("The shape [%s] for the new name is already in the model when processing " + "customization config renameShapes.%s", newName, originalName)); } } for (Entry<String, Shape> entry : serviceModel.getShapes().entrySet()) { String shapeName = entry.getKey(); Shape shape = entry.getValue(); preprocessRenameMemberShapes(shapeName, shape); } for (Operation operation : serviceModel.getOperations().values()) { if (operation.getInput() != null) { preprocessRenameInputShape(operation.getInput()); } if (operation.getOutput() != null) { preprocessRenameOutputShape(operation.getOutput()); } if (operation.getErrors() != null) { for (ErrorMap error : operation.getErrors()) { preprocessRenameErrorShape(error); } } } for (Entry<String, String> entry : renameShapes.entrySet()) { String originalName = entry.getKey(); String newName = entry.getValue(); Shape shape = serviceModel.getShapes().remove(originalName); serviceModel.getShapes().put(newName, shape); } } @Override public void postprocess(IntermediateModel intermediateModel) { // do nothing } /** * Rename all the member shapes within this shape */ private void preprocessRenameMemberShapes(String shapeName, Shape shape) { if (shape.getListMember() != null) { preprocessRenameMemberShape(shape.getListMember()); } if (shape.getMapKeyType() != null) { preprocessRenameMemberShape(shape.getMapKeyType()); } if (shape.getMapValueType() != null) { preprocessRenameMemberShape(shape.getMapValueType()); } if (shape.getMembers() != null) { for (Entry<String, Member> entry : shape.getMembers().entrySet()) { preprocessRenameMemberShape(entry.getValue()); } } } private void preprocessRenameMemberShape(Member member) { if (renameShapes.containsKey(member.getShape())) { member.setShape(renameShapes.get(member.getShape())); } } private void preprocessRenameErrorShape(ErrorMap error) { if (renameShapes.containsKey(error.getShape())) { error.setShape(renameShapes.get(error.getShape())); } } private void preprocessRenameOutputShape(Output output) { if (renameShapes.containsKey(output.getShape())) { output.setShape(renameShapes.get(output.getShape())); } } private void preprocessRenameInputShape(Input input) { if (renameShapes.containsKey(input.getShape())) { input.setShape(renameShapes.get(input.getShape())); } } }
3,375
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/ShapeSubstitutionsProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.config.customization.ShapeSubstitution; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.ErrorMap; import software.amazon.awssdk.codegen.model.service.Member; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Shape; /** * This processor internally keeps track of all the structure members whose * shape is substituted during pre-processing, therefore the caller needs to * make sure this processor is only invoked once. */ final class ShapeSubstitutionsProcessor implements CodegenCustomizationProcessor { private static Logger log = LoggerFactory.getLogger(ShapeSubstitutionsProcessor.class); private final Map<String, ShapeSubstitution> shapeSubstitutions; /** * parentShapeName -> {memberName -> originalShape} */ private final Map<String, Map<String, String>> substitutedShapeMemberReferences = new HashMap<>(); /** * parentShapeName -> {listTypeMemberName -> originalShapeOfTheMemberOfTheListTypeMember...} */ private final Map<String, Map<String, String>> substitutedListMemberReferences = new HashMap<>(); ShapeSubstitutionsProcessor( Map<String, ShapeSubstitution> shapeSubstitutions) { this.shapeSubstitutions = shapeSubstitutions; } @Override public void preprocess(ServiceModel serviceModel) { if (shapeSubstitutions == null) { return; } // Make sure the substituted shapes exist in the service model for (String substitutedShape : shapeSubstitutions.keySet()) { if (!serviceModel.getShapes().containsKey(substitutedShape)) { throw new IllegalStateException( "shapeSubstitution customization found for shape " + substitutedShape + ", which does not exist in the service model."); } } // Make sure the substituted shapes are not referenced by any operation // as the input, output or error shape for (Operation operation : serviceModel.getOperations().values()) { preprocessAssertNoSubstitutedShapeReferenceInOperation(operation); } // Substitute references from within shape members for (Entry<String, Shape> entry : serviceModel.getShapes().entrySet()) { String shapeName = entry.getKey(); Shape shape = entry.getValue(); preprocessSubstituteShapeReferencesInShape(shapeName, shape, serviceModel); } } @Override public void postprocess(IntermediateModel intermediateModel) { if (shapeSubstitutions == null) { return; } for (ShapeModel shapeModel : intermediateModel.getShapes().values()) { postprocessHandleEmitAsMember(shapeModel, intermediateModel); } } private void preprocessAssertNoSubstitutedShapeReferenceInOperation(Operation operation) { // Check input if (operation.getInput() != null && operation.getInput().getShape() != null) { String inputShape = operation.getInput().getShape(); if (shapeSubstitutions.containsKey(inputShape)) { throw new IllegalStateException( "shapeSubstitution customization found for shape " + inputShape + ", but this shape is referenced as the input for operation " + operation.getName()); } } // Check output if (operation.getOutput() != null && operation.getOutput().getShape() != null) { String outputShape = operation.getOutput().getShape(); if (shapeSubstitutions.containsKey(outputShape)) { throw new IllegalStateException( "shapeSubstitution customization found for shape " + outputShape + ", but this shape is referenced as the output for operation " + operation.getName()); } } // Check errors if (operation.getErrors() != null) { for (ErrorMap error : operation.getErrors()) { String errorShape = error.getShape(); if (shapeSubstitutions.containsKey(errorShape)) { throw new IllegalStateException( "shapeSubstitution customization found for shape " + errorShape + ", but this shape is referenced as an error for operation " + operation.getName()); } } } } /** * We only handle emitAsShape in the pre-process stage; emitAsMember is * handled in post-process stage, after the marshaller/unmarshaller location * names are calculated in the intermediate model. */ private void preprocessSubstituteShapeReferencesInShape( String shapeName, Shape shape, ServiceModel serviceModel) { // structure members if (shape.getMembers() != null) { for (Entry<String, Member> entry : shape.getMembers().entrySet()) { String memberName = entry.getKey(); Member member = entry.getValue(); String memberShapeName = member.getShape(); Shape memberShape = serviceModel.getShapes().get(memberShapeName); // First check if it's a list-type member and that the shape of // its list element should be substituted if (Utils.isListShape(memberShape)) { Member nestedListMember = memberShape.getListMember(); String nestedListMemberOriginalShape = nestedListMember.getShape(); ShapeSubstitution appliedSubstitutionOnListMember = substituteMemberShape(nestedListMember); if (appliedSubstitutionOnListMember != null && appliedSubstitutionOnListMember.getEmitFromMember() != null) { // we will handle the emitFromMember customizations in post-process stage trackListMemberSubstitution(shapeName, memberName, nestedListMemberOriginalShape); } } else { // Then check if the shape of the member itself is to be substituted ShapeSubstitution appliedSubstitution = substituteMemberShape(member); if (appliedSubstitution != null && appliedSubstitution.getEmitFromMember() != null) { // we will handle the emitFromMember customizations in post-process stage trackShapeMemberSubstitution(shapeName, memberName, memberShapeName); } } } } else if (shape.getMapKeyType() != null) { // no need to check if the shape is a list, since a list shape is // always referenced by a top-level structure shape and that's already // handled by the code above // map key is not allowed to be substituted String mapKeyShape = shape.getMapKeyType().getShape(); if (shapeSubstitutions.containsKey(mapKeyShape)) { throw new IllegalStateException( "shapeSubstitution customization found for shape " + mapKeyShape + ", but this shape is the key for a map shape."); } } else if (shape.getMapValueType() != null) { // map value is not allowed to be substituted String mapValShape = shape.getMapValueType().getShape(); if (shapeSubstitutions.containsKey(mapValShape)) { throw new IllegalStateException( "shapeSubstitution customization found for shape " + mapValShape + ", but this shape is the value for a map shape."); } } } /** * @return the ShapeSubstitution customization that should be applied to * this member, or null if there is no such customization specified * for this member. */ private ShapeSubstitution substituteMemberShape(Member member) { ShapeSubstitution substitute = shapeSubstitutions.get(member.getShape()); if (substitute != null) { member.setShape(substitute.getEmitAsShape()); return substitute; } return null; } private void postprocessHandleEmitAsMember( ShapeModel shape, IntermediateModel intermediateModel) { /* * For structure members whose shape is substituted, we need to add the * additional marshalling/unmarshalling path to the corresponding member * model */ for (Entry<String, Map<String, String>> ref : substitutedShapeMemberReferences.entrySet()) { String parentShapeC2jName = ref.getKey(); Map<String, String> memberOriginalShapeMap = ref.getValue(); ShapeModel parentShape = Utils.findShapeModelByC2jName( intermediateModel, parentShapeC2jName); for (Entry<String, String> entry : memberOriginalShapeMap.entrySet()) { String memberC2jName = entry.getKey(); String originalShapeC2jName = entry.getValue(); MemberModel member = parentShape.findMemberModelByC2jName(memberC2jName); ShapeModel originalShape = Utils.findShapeModelByC2jName(intermediateModel, originalShapeC2jName); MemberModel emitFromMember = originalShape.findMemberModelByC2jName( shapeSubstitutions.get(originalShapeC2jName) .getEmitFromMember()); // Pass in the original member model's marshalling/unmarshalling location name /** * This customization is specifically added for * EC2 where we replace all occurrences of AttributeValue with Value in * the model classes. However the wire representation is not changed. * * TODO This customization has been added to preserve backwards * compatibility of EC2 APIs. This should be removed as part of next major * version bump. */ if (!shouldSkipAddingMarshallingPath(shapeSubstitutions.get(originalShapeC2jName), parentShapeC2jName)) { member.getHttp().setAdditionalMarshallingPath( emitFromMember.getHttp().getMarshallLocationName()); } member.getHttp().setAdditionalUnmarshallingPath( emitFromMember.getHttp().getUnmarshallLocationName()); } } /* * For list shapes whose member shape is substituted, we need to add the * additional path into the "http" metadata of all the shape members * that reference to this list-type shape. */ for (Entry<String, Map<String, String>> ref : substitutedListMemberReferences.entrySet()) { String parentShapeC2jName = ref.getKey(); // {listTypeMemberName -> nestedListMemberOriginalShape} Map<String, String> nestedListMemberOriginalShapeMap = ref.getValue(); ShapeModel parentShape = Utils.findShapeModelByC2jName( intermediateModel, parentShapeC2jName); for (Entry<String, String> entry : nestedListMemberOriginalShapeMap.entrySet()) { String listTypeMemberC2jName = entry.getKey(); String nestedListMemberOriginalShapeC2jName = entry.getValue(); MemberModel listTypeMember = parentShape.findMemberModelByC2jName(listTypeMemberC2jName); ShapeModel nestedListMemberOriginalShape = Utils.findShapeModelByC2jName(intermediateModel, nestedListMemberOriginalShapeC2jName); MemberModel emitFromMember = nestedListMemberOriginalShape.findMemberModelByC2jName( shapeSubstitutions .get(nestedListMemberOriginalShapeC2jName) .getEmitFromMember() ); /** * This customization is specifically added for * EC2 where we replace all occurrences of AttributeValue with Value in * the model classes. However the wire representation is not changed. * * TODO This customization has been added to preserve backwards * compatibility of EC2 APIs. This should be removed as part of next major * version bump. */ if (!shouldSkipAddingMarshallingPath(shapeSubstitutions.get(nestedListMemberOriginalShapeC2jName), parentShapeC2jName)) { listTypeMember.getListModel().setMemberAdditionalMarshallingPath( emitFromMember.getHttp().getMarshallLocationName()); } listTypeMember.getListModel().setMemberAdditionalUnmarshallingPath( emitFromMember.getHttp().getUnmarshallLocationName()); } } } private void trackShapeMemberSubstitution(String shapeName, String memberName, String originalShape) { log.info("{} -> ({} -> {})", shapeName, memberName, originalShape); if (!substitutedShapeMemberReferences.containsKey(shapeName)) { substitutedShapeMemberReferences.put(shapeName, new HashMap<>()); } substitutedShapeMemberReferences.get(shapeName).put(memberName, originalShape); } private void trackListMemberSubstitution(String shapeName, String listTypeMemberName, String nestedListMemberOriginalShape) { log.info("{} -> ({} -> {})", shapeName, listTypeMemberName, nestedListMemberOriginalShape); if (!substitutedListMemberReferences.containsKey(shapeName)) { substitutedListMemberReferences.put(shapeName, new HashMap<>()); } substitutedListMemberReferences.get(shapeName).put(listTypeMemberName, nestedListMemberOriginalShape); } private boolean shouldSkipAddingMarshallingPath(ShapeSubstitution substitutionConfig, String parentShapeName) { return substitutionConfig.getSkipMarshallPathForShapes() == null ? false : substitutionConfig.getSkipMarshallPathForShapes().contains(parentShapeName); } }
3,376
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/customization/processors/RemoveExceptionMessagePropertyProcessor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.customization.processors; import software.amazon.awssdk.codegen.customization.CodegenCustomizationProcessor; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.service.ServiceModel; /** * This processor removes the member *message* in the exception shapes from the * intermediate model. Every exception class generated extends * SdkException and the *message* member is inherited from that class. */ public class RemoveExceptionMessagePropertyProcessor implements CodegenCustomizationProcessor { private static final boolean IGNORE_CASE = true; @Override public void preprocess(ServiceModel serviceModel) { // Do Nothing } @Override public void postprocess(IntermediateModel intermediateModel) { for (ShapeModel shapeModel : intermediateModel.getShapes().values()) { if (ShapeType.Exception == shapeModel.getShapeType()) { shapeModel.removeMemberByC2jName("message", IGNORE_CASE); } } } }
3,377
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/internal/Jackson.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.internal; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.jr.ob.JSON; import com.fasterxml.jackson.jr.stree.JacksonJrsTreeCodec; import com.fasterxml.jackson.jr.stree.JrsValue; import java.io.File; import java.io.IOException; import java.io.Writer; public final class Jackson { private static final JSON MAPPER; private static final JSON FAIL_ON_UNKNOWN_PROPERTIES_MAPPER; private static volatile ObjectWriter OBJECT_MAPPER; static { JSON.Builder mapperBuilder = JSON.builder() .disable(JSON.Feature.FAIL_ON_UNKNOWN_BEAN_PROPERTY) .enable(JSON.Feature.PRETTY_PRINT_OUTPUT) .enable(JSON.Feature.READ_JSON_ARRAYS_AS_JAVA_ARRAYS) .treeCodec(new JacksonJrsTreeCodec()); mapperBuilder.streamFactory().enable(JsonParser.Feature.ALLOW_COMMENTS); MAPPER = mapperBuilder.build(); mapperBuilder.enable(JSON.Feature.FAIL_ON_UNKNOWN_BEAN_PROPERTY); FAIL_ON_UNKNOWN_PROPERTIES_MAPPER = mapperBuilder.build(); } private Jackson() { } public static JrsValue readJrsValue(String input) throws IOException { return MAPPER.beanFrom(JrsValue.class, input); } public static <T> T load(Class<T> clazz, File file) throws IOException { return MAPPER.beanFrom(clazz, file); } public static <T> T load(Class<T> clazz, String content) throws IOException { return MAPPER.beanFrom(clazz, content); } public static <T> T load(Class<T> clazz, File file, boolean failOnUnknownProperties) throws IOException { if (failOnUnknownProperties) { return FAIL_ON_UNKNOWN_PROPERTIES_MAPPER.beanFrom(clazz, file); } else { return load(clazz, file); } } public static void writeWithObjectMapper(Object value, Writer w) throws IOException { if (OBJECT_MAPPER == null) { synchronized (Jackson.class) { if (OBJECT_MAPPER == null) { OBJECT_MAPPER = new ObjectMapper().configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true) .writerWithDefaultPrettyPrinter(); } } } OBJECT_MAPPER.writeValue(w, value); } }
3,378
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/internal/ClassLoaderHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.internal; import java.io.IOException; import java.io.InputStream; import java.net.URL; /** * @deprecated should be replaced with {@link software.amazon.awssdk.core.internal.util.ClassLoaderHelper} */ @Deprecated public final class ClassLoaderHelper { private ClassLoaderHelper() { } /** * If classesFirst is false, retrieves the resource via the context class loader of the current * thread, and if not found, via the class loaders of the optionally specified classes in the * order of their specification, and if not found, from the class loader of * {@link ClassLoaderHelper} as the last resort. * <p> * If classesFirst is true, retrieves the resource via the optionally specified classes in the * order of their specification, and if not found, via the context class loader of the current * thread, and if not found, from the class loader of {@link ClassLoaderHelper} as the last * resort. * * @param resource * resource to be loaded * @param classesFirst * true if the class loaders of the optionally specified classes take precedence over * the context class loader of the current thread; false if the opposite is true. * @param classes * class loader providers * @return the resource loaded as an URL or null if not found. */ public static URL getResource(String resource, boolean classesFirst, Class<?>... classes) { URL url; if (classesFirst) { url = getResourceViaClasses(resource, classes); if (url == null) { url = getResourceViaContext(resource); } } else { url = getResourceViaContext(resource); if (url == null) { url = getResourceViaClasses(resource, classes); } } return url == null ? ClassLoaderHelper.class.getResource(resource) : url; } private static URL getResourceViaClasses(String resource, Class<?>[] classes) { if (classes != null) { for (Class<?> c : classes) { URL url = c.getResource(resource); if (url != null) { return url; } } } return null; } private static URL getResourceViaContext(String resource) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); return loader == null ? null : loader.getResource(resource); } /** * Retrieves the resource as an input stream via the context class loader of the current thread, * and if not found, via the class loaders of the optionally specified classes in the order of * their specification, and if not found, from the class loader of {@link ClassLoaderHelper} as * the last resort. * * @param resource * resource to be loaded * @param classes * class loader providers * @return the resource loaded as an input stream or null if not found. */ public static InputStream getResourceAsStream(String resource, Class<?>... classes) { return getResourceAsStream(resource, false, classes); } /** * If classesFirst is false, retrieves the resource as an input stream via the context class * loader of the current thread, and if not found, via the class loaders of the optionally * specified classes in the order of their specification, and if not found, from the class * loader of {@link ClassLoaderHelper} as the last resort. * <p> * If classesFirst is true, retrieves the resource as an input stream via the optionally * specified classes in the order of their specification, and if not found, via the context * class loader of the current thread, and if not found, from the class loader of * {@link ClassLoaderHelper} as the last resort. * * @param resource * resource to be loaded * @param classesFirst * true if the class loaders of the optionally specified classes take precedence over * the context class loader of the current thread; false if the opposite is true. * @param classes * class loader providers * @return the resource loaded as an input stream or null if not found. */ public static InputStream getResourceAsStream(String resource, boolean classesFirst, Class<?>... classes) { URL url = getResource(resource, classesFirst, classes); try { return url != null ? url.openStream() : null; } catch (IOException e) { return null; } } }
3,379
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/internal/TypeUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.internal; import static software.amazon.awssdk.codegen.model.service.ShapeType.List; import static software.amazon.awssdk.codegen.model.service.ShapeType.Map; import static software.amazon.awssdk.codegen.model.service.ShapeType.Structure; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.service.Shape; import software.amazon.awssdk.codegen.naming.NamingStrategy; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.document.Document; /** * Used to determine the Java types for the service model. */ public class TypeUtils { public static final class TypeKey { public static final String LIST_INTERFACE = "listInterface"; public static final String LIST_DEFAULT_IMPL = "listDefaultImpl"; public static final String MAP_INTERFACE = "mapInterface"; public static final String MAP_DEFAULT_IMPL = "mapDefaultImpl"; } private static final Map<String, String> DATA_TYPE_MAPPINGS = new HashMap<>(); private static final Map<String, String> MARSHALLING_TYPE_MAPPINGS = new HashMap<>(); static { DATA_TYPE_MAPPINGS.put("string", String.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("boolean", Boolean.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("int", Integer.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("any", Object.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("integer", Integer.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("double", Double.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("short", Short.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("long", Long.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("float", Float.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("byte", Byte.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("timestamp", Instant.class.getName()); DATA_TYPE_MAPPINGS.put("blob", SdkBytes.class.getName()); DATA_TYPE_MAPPINGS.put("stream", InputStream.class.getName()); DATA_TYPE_MAPPINGS.put("bigdecimal", BigDecimal.class.getName()); DATA_TYPE_MAPPINGS.put("biginteger", BigInteger.class.getName()); DATA_TYPE_MAPPINGS.put("list", List.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("map", Map.class.getSimpleName()); DATA_TYPE_MAPPINGS.put("document", Document.class.getName()); DATA_TYPE_MAPPINGS.put(TypeKey.LIST_INTERFACE, List.class.getName()); DATA_TYPE_MAPPINGS.put(TypeKey.LIST_DEFAULT_IMPL, ArrayList.class.getName()); DATA_TYPE_MAPPINGS.put(TypeKey.MAP_INTERFACE, Map.class.getName()); DATA_TYPE_MAPPINGS.put(TypeKey.MAP_DEFAULT_IMPL, HashMap.class.getName()); MARSHALLING_TYPE_MAPPINGS.put("String", "STRING"); MARSHALLING_TYPE_MAPPINGS.put("Integer", "INTEGER"); MARSHALLING_TYPE_MAPPINGS.put("Long", "LONG"); MARSHALLING_TYPE_MAPPINGS.put("Float", "FLOAT"); MARSHALLING_TYPE_MAPPINGS.put("Double", "DOUBLE"); MARSHALLING_TYPE_MAPPINGS.put("Instant", "INSTANT"); MARSHALLING_TYPE_MAPPINGS.put("SdkBytes", "SDK_BYTES"); MARSHALLING_TYPE_MAPPINGS.put("Boolean", "BOOLEAN"); MARSHALLING_TYPE_MAPPINGS.put("BigDecimal", "BIG_DECIMAL"); MARSHALLING_TYPE_MAPPINGS.put("InputStream", "STREAM"); MARSHALLING_TYPE_MAPPINGS.put("Short", "SHORT"); MARSHALLING_TYPE_MAPPINGS.put(null, "NULL"); MARSHALLING_TYPE_MAPPINGS.put("Document", "DOCUMENT"); } private final NamingStrategy namingStrategy; public TypeUtils(NamingStrategy namingStrategy) { this.namingStrategy = namingStrategy; } public static String getMarshallingType(String simpleType) { return MARSHALLING_TYPE_MAPPINGS.get(simpleType); } public static boolean isSimple(String type) { return DATA_TYPE_MAPPINGS.containsKey(type) || DATA_TYPE_MAPPINGS.containsValue(type); } public static String getDataTypeMapping(String type) { return DATA_TYPE_MAPPINGS.get(type); } /** * Returns the default Java type of the specified shape. */ public String getJavaDataType(Map<String, Shape> shapes, String shapeName) { return getJavaDataType(shapes, shapeName, null); } /** * Returns the Java type of the specified shape with potential customization (such as * auto-construct list or map). */ public String getJavaDataType(Map<String, Shape> shapes, String shapeName, CustomizationConfig customConfig) { if (shapeName == null || shapeName.trim().isEmpty()) { throw new IllegalArgumentException( "Cannot derive shape type. Shape name cannot be null or empty"); } Shape shape = shapes.get(shapeName); if (shape == null) { throw new IllegalArgumentException( "Cannot derive shape type. No shape information available for " + shapeName); } String shapeType = shape.getType(); if (shape.isDocument()) { return DATA_TYPE_MAPPINGS.get("document"); } if (Structure.getName().equals(shapeType)) { return namingStrategy.getShapeClassName(shapeName); } else if (List.getName().equals(shapeType)) { String listContainerType = DATA_TYPE_MAPPINGS.get(TypeKey.LIST_INTERFACE); return listContainerType + "<" + getJavaDataType(shapes, shape.getListMember().getShape()) + ">"; } else if (Map.getName().equals(shapeType)) { String mapContainerType = DATA_TYPE_MAPPINGS.get(TypeKey.MAP_INTERFACE); return mapContainerType + "<" + getJavaDataType(shapes, shape.getMapKeyType().getShape()) + "," + getJavaDataType(shapes, shape.getMapValueType().getShape()) + ">"; } else { if (shape.isStreaming()) { return DATA_TYPE_MAPPINGS.get("stream"); } // scalar type. String dataType = DATA_TYPE_MAPPINGS.get(shapeType); if (dataType == null) { throw new RuntimeException( "Equivalent Java data type cannot be found for data type : " + shapeType); } return dataType; } } }
3,380
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/internal/Utils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.internal; import static java.util.stream.Collectors.toList; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.util.List; import java.util.Map; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MapModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.ShapeMarshaller; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.service.Input; import software.amazon.awssdk.codegen.model.service.Operation; import software.amazon.awssdk.codegen.model.service.ServiceMetadata; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Shape; import software.amazon.awssdk.codegen.model.service.XmlNamespace; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.StringUtils; public final class Utils { private Utils() { } public static boolean isScalar(Shape shape) { // enums are treated as scalars in C2j. return !(isListShape(shape) || isStructure(shape) || isMapShape(shape)); } public static boolean isStructure(Shape shape) { return shape.getType().equals("structure"); } public static boolean isListShape(Shape shape) { return shape.getType().equals("list"); } public static boolean isMapShape(Shape shape) { return shape.getType().equals("map"); } public static boolean isEnumShape(Shape shape) { return shape.getEnumValues() != null; } public static boolean isExceptionShape(Shape shape) { return shape.isException() || shape.isFault(); } public static boolean isOrContainsEnumShape(Shape shape, Map<String, Shape> allShapes) { boolean isEnum = isEnumShape(shape); boolean isMapWithEnumMember = isMapShape(shape) && (isOrContainsEnumShape(allShapes.get(shape.getMapKeyType().getShape()), allShapes) || isOrContainsEnumShape(allShapes.get(shape.getMapValueType().getShape()), allShapes)); boolean isListWithEnumMember = isListShape(shape) && isOrContainsEnumShape(allShapes.get(shape.getListMember().getShape()), allShapes); return isEnum || isMapWithEnumMember || isListWithEnumMember; } public static boolean isOrContainsEnum(MemberModel member) { boolean isEnum = member.getEnumType() != null; return isEnum || isMapWithEnumShape(member) || isListWithEnumShape(member); } public static boolean isListWithEnumShape(MemberModel member) { return member.isList() && member.getListModel().getListMemberModel().getEnumType() != null; } public static boolean isMapWithEnumShape(MemberModel member) { return member.isMap() && (isMapKeyWithEnumShape(member.getMapModel()) || isMapValueWithEnumShape(member.getMapModel())); } public static boolean isMapKeyWithEnumShape(MapModel mapModel) { return mapModel.getKeyModel().getEnumType() != null; } public static boolean isMapValueWithEnumShape(MapModel mapModel) { return mapModel.getValueModel().getEnumType() != null; } public static String unCapitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } StringBuilder sb = new StringBuilder(name.length()); int i = 0; do { sb.append(Character.toLowerCase(name.charAt(i++))); } while ((i < name.length() && Character.isUpperCase(name.charAt(i))) // not followed by a lowercase character && !(i < name.length() - 1 && Character.isLowerCase(name.charAt(i + 1)))); sb.append(name.substring(i)); return sb.toString(); } public static String capitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } return name.length() < 2 ? StringUtils.upperCase(name) : StringUtils.upperCase(name.substring(0, 1)) + name.substring(1); } public static String removeLeading(String str, String toRemove) { if (str == null) { return null; } if (str.startsWith(toRemove)) { return str.substring(toRemove.length()); } return str; } public static String removeTrailing(String str, String toRemove) { if (str == null) { return null; } if (str.endsWith(toRemove)) { return str.substring(0, str.length() - toRemove.length()); } return str; } /** * * @param serviceModel Service model to get prefix for. * * @return Prefix to use when writing model files (service and intermediate). */ public static String getFileNamePrefix(ServiceModel serviceModel) { return String.format("%s-%s", serviceModel.getMetadata().getEndpointPrefix(), serviceModel.getMetadata().getApiVersion()); } /** * Converts a directory to a Java package name. * * @param directoryPath Directory to convert. * @return Package name */ public static String directoryToPackage(String directoryPath) { return directoryPath.replace('/', '.'); } /** * Converts a Java package name to a directory. * * @param packageName Java package to convert. * @return directory */ public static String packageToDirectory(String packageName) { return packageName.replace('.', '/'); } public static String getDefaultEndpointWithoutHttpProtocol(String endpoint) { if (endpoint == null) { return null; } if (endpoint.startsWith("http://")) { return endpoint.substring("http://".length()); } if (endpoint.startsWith("https://")) { return endpoint.substring("https://".length()); } return endpoint; } public static File createDirectory(String path) { if (isNullOrEmpty(path)) { throw new IllegalArgumentException( "Invalid path directory. Path directory cannot be null or empty"); } File dir = new File(path); createDirectory(dir); return dir; } public static void createDirectory(File dir) { if (!(dir.exists())) { try { Files.createDirectories(dir.toPath()); } catch (IOException e) { throw new UncheckedIOException("Failed to create " + dir, e); } } } public static File createFile(String dir, String fileName) throws IOException { if (isNullOrEmpty(fileName)) { throw new IllegalArgumentException( "Invalid file name. File name cannot be null or empty"); } createDirectory(dir); File file = new File(dir, fileName); if (!(file.exists())) { if (!(file.createNewFile())) { throw new RuntimeException("Not able to create file . " + file.getAbsolutePath()); } } return file; } public static boolean isNullOrEmpty(String str) { return str == null || str.trim().isEmpty(); } public static void closeQuietly(Closeable closeable) { IoUtils.closeQuietly(closeable, null); } /** * Return an InputStream of the specified resource, failing if it can't be found. * * @param location Location of resource */ public static InputStream getRequiredResourceAsStream(Class<?> clzz, String location) { InputStream resourceStream = clzz.getResourceAsStream(location); if (resourceStream == null) { // Try with a leading "/" if (!location.startsWith("/")) { resourceStream = clzz.getResourceAsStream("/" + location); } if (resourceStream == null) { throw new RuntimeException("Resource file was not found at location " + location); } } return resourceStream; } /** * Search for intermediate shape model by its c2j name. * * @return ShapeModel * @throws IllegalArgumentException if the specified c2j name is not found in the intermediate model. */ public static ShapeModel findShapeModelByC2jName(IntermediateModel intermediateModel, String shapeC2jName) throws IllegalArgumentException { ShapeModel shapeModel = findShapeModelByC2jNameIfExists(intermediateModel, shapeC2jName); if (shapeModel != null) { return shapeModel; } else { throw new IllegalArgumentException( shapeC2jName + " shape (c2j name) does not exist in the intermediate model."); } } /** * Search for intermediate shape model by its c2j name. * * @return ShapeModel or null if the shape doesn't exist (if it's primitive or container type for example) */ public static ShapeModel findShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName) { for (ShapeModel shape : intermediateModel.getShapes().values()) { if (shape.getC2jName().equals(shapeC2jName)) { return shape; } } return null; } /** * Search for a shape model by its C2J name, excluding request and response shapes, which are not candidates to be members * of another shape. * * @return ShapeModel or null if the shape doesn't exist (if it's primitive or container type for example) */ public static ShapeModel findMemberShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName) { ShapeModel candidate = null; for (ShapeModel shape : intermediateModel.getShapes().values()) { if (shape.getShapeType() != ShapeType.Request && shape.getShapeType() != ShapeType.Response && shape.getC2jName().equals(shapeC2jName)) { if (candidate != null) { throw new IllegalStateException("Conflicting candidates for member model with C2J name " + shapeC2jName + ": " + candidate + " and " + shape); } candidate = shape; } } return candidate; } public static List<ShapeModel> findShapesByC2jName(IntermediateModel intermediateModel, String shapeC2jName) { return intermediateModel.getShapes().values().stream().filter(s -> s.getC2jName().equals(shapeC2jName)).collect(toList()); } /** * Create the ShapeMarshaller to the input shape from the specified Operation. * The input shape in the operation could be empty. */ public static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation) { if (operation == null) { throw new IllegalArgumentException( "The operation parameter must be specified!"); } ShapeMarshaller marshaller = new ShapeMarshaller() .withAction(operation.getName()) .withVerb(operation.getHttp().getMethod()) .withRequestUri(operation.getHttp().getRequestUri()); Input input = operation.getInput(); if (input != null) { marshaller.setLocationName(input.getLocationName()); // Pass the xmlNamespace trait from the input reference XmlNamespace xmlNamespace = input.getXmlNamespace(); if (xmlNamespace != null) { marshaller.setXmlNameSpaceUri(xmlNamespace.getUri()); } } if (Metadata.isNotRestProtocol(service.getProtocol())) { marshaller.setTarget(StringUtils.isEmpty(service.getTargetPrefix()) ? operation.getName() : service.getTargetPrefix() + "." + operation.getName()); } return marshaller; } }
3,381
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/internal/Constant.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.internal; import java.nio.file.Path; public final class Constant { public static final String CUSTOMIZATION_CONFIG_FILE = "customization.config"; public static final String ASYNC_CLIENT_INTERFACE_NAME_PATTERN = "%sAsyncClient"; public static final String ASYNC_CLIENT_CLASS_NAME_PATTERN = "Default%sAsyncClient"; public static final String ASYNC_BUILDER_INTERFACE_NAME_PATTERN = "%sAsyncClientBuilder"; public static final String ASYNC_BUILDER_CLASS_NAME_PATTERN = "Default%sAsyncClientBuilder"; public static final String SYNC_CLIENT_INTERFACE_NAME_PATTERN = "%sClient"; public static final String SYNC_CLIENT_CLASS_NAME_PATTERN = "Default%sClient"; /** * Name of the source {@link Path}-typed formal method parameters of streaming input operations. */ public static final String SYNC_CLIENT_SOURCE_PATH_PARAM_NAME = "sourcePath"; /** * Name of the destination {@link Path}-typed formal method parameters of streaming output * operations. */ public static final String SYNC_CLIENT_DESTINATION_PATH_PARAM_NAME = "destinationPath"; public static final String SYNC_BUILDER_INTERFACE_NAME_PATTERN = "%sClientBuilder"; public static final String SYNC_BUILDER_CLASS_NAME_PATTERN = "Default%sClientBuilder"; public static final String BASE_BUILDER_INTERFACE_NAME_PATTERN = "%sBaseClientBuilder"; public static final String BASE_BUILDER_CLASS_NAME_PATTERN = "Default%sBaseClientBuilder"; public static final String BASE_EXCEPTION_NAME_PATTERN = "%sException"; public static final String BASE_REQUEST_NAME_PATTERN = "%sRequest"; public static final String BASE_RESPONSE_NAME_PATTERN = "%sResponse"; public static final String PROTOCOL_CONFIG_LOCATION = "/protocol-config/%s.json"; public static final String JAVA_FILE_NAME_SUFFIX = ".java"; public static final String PROPERTIES_FILE_NAME_SUFFIX = ".properties"; public static final String PACKAGE_NAME_CLIENT_PATTERN = "%s"; public static final String PACKAGE_NAME_MODEL_PATTERN = "%s.model"; public static final String PACKAGE_NAME_TRANSFORM_PATTERN = "%s.transform"; public static final String PACKAGE_NAME_PAGINATORS_PATTERN = "%s.paginators"; public static final String PACKAGE_NAME_WAITERS_PATTERN = "%s.waiters"; public static final String PACKAGE_NAME_RULES_PATTERN = "%s.endpoints"; public static final String PACKAGE_NAME_AUTH_SCHEME_PATTERN = "%s.auth.scheme"; public static final String PACKAGE_NAME_SMOKE_TEST_PATTERN = "%s.smoketests"; public static final String PACKAGE_NAME_CUSTOM_AUTH_PATTERN = "%s.auth"; public static final String AUTH_POLICY_ENUM_CLASS_DIR = "software/amazon/awssdk/auth/policy/actions"; public static final String REQUEST_CLASS_SUFFIX = "Request"; public static final String RESPONSE_CLASS_SUFFIX = "Response"; public static final String EXCEPTION_CLASS_SUFFIX = "Exception"; public static final String FAULT_CLASS_SUFFIX = "Fault"; public static final String CONFLICTING_NAME_SUFFIX = "Value"; public static final String AUTHORIZER_NAME_PREFIX = "I"; public static final String LF = System.lineSeparator(); public static final String AWS_DOCS_HOST = "docs.aws.amazon.com"; public static final String APPROVED_SIMPLE_METHOD_VERBS = "(get|list|describe|lookup|batchGet).*"; public static final String ASYNC_STREAMING_INPUT_PARAM = "requestBody"; public static final String ASYNC_STREAMING_OUTPUT_PARAM = "asyncResponseTransformer"; public static final String SYNC_STREAMING_INPUT_PARAM = "requestBody"; public static final String SYNC_STREAMING_OUTPUT_PARAM = "responseTransformer"; public static final String EVENT_PUBLISHER_PARAM_NAME = "requestStream"; public static final String EVENT_RESPONSE_HANDLER_PARAM_NAME = "asyncResponseHandler"; private Constant() { } }
3,382
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/internal/DocumentationUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.internal; import static software.amazon.awssdk.codegen.internal.Constant.AWS_DOCS_HOST; import static software.amazon.awssdk.codegen.model.intermediate.ShapeType.Model; import static software.amazon.awssdk.codegen.model.intermediate.ShapeType.Request; import static software.amazon.awssdk.codegen.model.intermediate.ShapeType.Response; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; public final class DocumentationUtils { private static final String DEFAULT_SETTER = "Sets the value of the %s property for this object."; private static final String DEFAULT_SETTER_PARAM = "The new value for the %s property for this object."; private static final String DEFAULT_GETTER = "Returns the value of the %s property for this object."; private static final String DEFAULT_GETTER_PARAM = "The value of the %s property for this object."; private static final String DEFAULT_EXISTENCE_CHECK = "For responses, this returns true if the service returned a value for the %s property. This DOES NOT check that the " + "value is non-empty (for which, you should check the {@code isEmpty()} method on the property). This is useful because " + "the SDK will never return a null collection or map, but you may need to differentiate between the service returning " + "nothing (or null) and the service returning an empty collection or map. For requests, this returns true if a value " + "for the property was specified in the request builder, and false if a value was not specified."; private static final String DEFAULT_FLUENT_RETURN = "Returns a reference to this object so that method calls can be chained together."; //TODO probably should move this to a custom config in each service private static final Set<String> SERVICES_EXCLUDED_FROM_CROSS_LINKING = new HashSet<>(Arrays.asList( "apigateway", "budgets", "cloudsearch", "cloudsearchdomain", "discovery", "elastictranscoder", "es", "glacier", "iot", "data.iot", "machinelearning", "rekognition", "s3", "sdb", "swf" )); private DocumentationUtils() { } /** * Returns a documentation with HTML tags prefixed and suffixed removed, or * returns empty string if the input is empty or null. This method is to be * used when constructing documentation for method parameters. * * @param documentation * unprocessed input documentation * @return HTML tag stripped documentation or empty string if input was * null. */ public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf('>'); int closingTagIndex = documentation.lastIndexOf('<'); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } /** * Escapes Java comment breaking illegal character sequences. * * @param documentation * unprocessed input documentation * @return escaped documentation, or empty string if input was null */ public static String escapeIllegalCharacters(String documentation) { if (documentation == null) { return ""; } /* * this specifically handles a case where a '* /' sequence may * be present in documentation and inadvertently terminate that Java * comment line, resulting in broken code. */ documentation = documentation.replaceAll("\\*\\/", "*&#47;"); return documentation; } /** * Create the HTML for a link to the operation/shape core AWS docs site * * @param metadata the UID for the service from that services metadata * @param name the name of the shape/request/operation * * @return a '@see also' HTML link to the doc */ public static String createLinkToServiceDocumentation(Metadata metadata, String name) { if (isCrossLinkingEnabledForService(metadata)) { return String.format("<a href=\"https://%s/goto/WebAPI/%s/%s\" target=\"_top\">AWS API Documentation</a>", AWS_DOCS_HOST, metadata.getUid(), name); } return ""; } /** * Create the HTML for a link to the operation/shape core AWS docs site * * @param metadata the UID for the service from that services metadata * @param shapeModel the model of the shape * * @return a '@see also' HTML link to the doc */ public static String createLinkToServiceDocumentation(Metadata metadata, ShapeModel shapeModel) { return isRequestResponseOrModel(shapeModel) ? createLinkToServiceDocumentation(metadata, shapeModel.getDocumentationShapeName()) : ""; } public static String removeFromEnd(String string, String stringToRemove) { return string.endsWith(stringToRemove) ? string.substring(0, string.length() - stringToRemove.length()) : string; } private static boolean isRequestResponseOrModel(ShapeModel shapeModel) { return shapeModel.getShapeType() == Model || shapeModel.getShapeType() == Request || shapeModel.getShapeType() == Response; } private static boolean isCrossLinkingEnabledForService(Metadata metadata) { return metadata.getUid() != null && metadata.getEndpointPrefix() != null && !SERVICES_EXCLUDED_FROM_CROSS_LINKING.contains(metadata.getEndpointPrefix()); } public static String defaultSetter() { return DEFAULT_SETTER; } public static String defaultSetterParam() { return DEFAULT_SETTER_PARAM; } public static String defaultGetter() { return DEFAULT_GETTER; } public static String defaultGetterParam() { return DEFAULT_GETTER_PARAM; } public static String defaultFluentReturn() { return DEFAULT_FLUENT_RETURN; } public static String defaultExistenceCheck() { return DEFAULT_EXISTENCE_CHECK; } }
3,383
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/StaticImport.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet; import com.squareup.javapoet.ClassName; import java.util.Arrays; import java.util.Collections; /** * A Poet static import definition to enable inclusion of static imports at code generation time */ public interface StaticImport { /** * @return The Poet representation of the class to import (may or may not yet exist) */ ClassName className(); /** * The members to import from the class for example if memberNames() returned List("trim", "isBlank") for * StringUtils.class then the following static imports would be generated: * * import static software.amazon.awssdk.utils.StringUtils.trim; * import static software.amazon.awssdk.utils.StringUtils.isBlank; * * @return The members to import from the class representation */ Iterable<String> memberNames(); /** * A helper implementation to create a {@link StaticImport} from a {@link Class} * @param clz the class to import * @param members the members from that class to import, if none then * is assumed * @return an anonymous implementation of {@link StaticImport} */ static StaticImport staticMethodImport(Class<?> clz, String... members) { return new StaticImport() { @Override public ClassName className() { return ClassName.get(clz); } @Override public Iterable<String> memberNames() { if (members.length > 0) { return Arrays.asList(members); } return Collections.singletonList("*"); } }; } }
3,384
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/ClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeSpec; import java.util.Collections; /** * Represents a Poet generated class */ public interface ClassSpec { /** * @return The actual class specification generated from a <code>PoetSpec.builder()...</code> implementation */ TypeSpec poetSpec(); /** * @return The Poet representation of the class being generated, this may be used by other classes */ ClassName className(); /** * An optional hook to allow inclusion of static imports for example converting: * * <pre><code> * import software.amazon.awssdk.utils.StringUtils; * //... * if(StringUtils.isBlank(value))... * </code></pre> * * to * * <pre><code> * import software.amazon.awssdk.utils.StringUtils.isBlank; * //... * if(isBlank(value))... * </code></pre> * * @return the static imports to include */ default Iterable<StaticImport> staticImports() { return Collections.emptyList(); } }
3,385
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/PoetCollectors.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet; import com.squareup.javapoet.CodeBlock; import java.util.StringJoiner; import java.util.stream.Collector; import java.util.stream.Collectors; /** * A set of {@link Collector} implementations, similar to {@link Collectors}, but for poet types. */ public final class PoetCollectors { private PoetCollectors() { } /** * Join a stream of code blocks into one code block. */ public static Collector<CodeBlock, ?, CodeBlock> toCodeBlock() { return Collector.of(CodeBlock::builder, CodeBlock.Builder::add, PoetCollectors::parallelNotSupported, CodeBlock.Builder::build); } /** * Join a stream of code blocks into one code block, separated by the provided delimiter. Useful for joining an arbitrary * number of method parameters, code statements, etc. */ public static Collector<CodeBlock, ?, CodeBlock> toDelimitedCodeBlock(String delimiter) { return Collector.of(() -> new CodeBlockJoiner(delimiter), CodeBlockJoiner::add, PoetCollectors::parallelNotSupported, CodeBlockJoiner::join); } /** * A joiner, similar to {@link StringJoiner}, used by {@link #toDelimitedCodeBlock(String)} in order to join multiple code * blocks into one block, delimited by a character. * * <p>This class is not thread-safe.</p> */ private static class CodeBlockJoiner { private final CodeBlock.Builder builder = CodeBlock.builder(); private final String delimiter; private boolean builderEmpty = true; /** * Create a code block joiner that will separate statements by the provided delimiter. * @param delimiter The delimiter that should separate each code statement. */ private CodeBlockJoiner(String delimiter) { this.delimiter = delimiter; } /** * Add a code block to the joined result. */ private void add(CodeBlock block) { if (!builderEmpty) { builder.add(CodeBlock.of(delimiter)); } else { builderEmpty = false; } builder.add(block); } /** * Join all code blocks and return the joined result. */ private CodeBlock join() { return builder.build(); } } /** * A convenience method that can be passed as a {@link Collector}'s "combiner" to indicate parallel collecting is not * supported. */ private static <T> T parallelNotSupported(Object... ignoredParams) { throw new UnsupportedOperationException("Parallel collecting is not supported."); } }
3,386
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/PoetUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet; import static software.amazon.awssdk.utils.StringUtils.isNotBlank; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import java.util.Arrays; import java.util.function.Consumer; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.codegen.model.intermediate.DocumentationModel; import software.amazon.awssdk.codegen.model.intermediate.HasDeprecation; public final class PoetUtils { private static final AnnotationSpec GENERATED = AnnotationSpec.builder(Generated.class) .addMember("value", "$S", "software.amazon.awssdk:codegen") .build(); private PoetUtils() { } public static AnnotationSpec generatedAnnotation() { return GENERATED; } public static MethodSpec.Builder toStringBuilder() { return MethodSpec.methodBuilder("toString") .returns(String.class) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class); } public static void addDeprecated(Consumer<Class<?>> builder, HasDeprecation deprecation) { if (deprecation.isDeprecated()) { addDeprecated(builder); } } public static void addDeprecated(Consumer<Class<?>> builder) { builder.accept(Deprecated.class); } public static void addJavadoc(Consumer<String> builder, String javadoc) { if (isNotBlank(javadoc)) { builder.accept(javadoc.replace("$", "$$") + (javadoc.endsWith("\n") ? "" : "\n")); } } public static void addJavadoc(Consumer<String> builder, DocumentationModel docModel) { addJavadoc(builder, docModel.getDocumentation()); } public static TypeSpec.Builder createEnumBuilder(ClassName name) { return TypeSpec.enumBuilder(name).addAnnotation(PoetUtils.generatedAnnotation()).addModifiers(Modifier.PUBLIC); } public static TypeSpec.Builder createInterfaceBuilder(ClassName name) { return TypeSpec.interfaceBuilder(name).addAnnotation(PoetUtils.generatedAnnotation()).addModifiers(Modifier.PUBLIC); } public static TypeSpec.Builder createClassBuilder(ClassName name) { return TypeSpec.classBuilder(name).addAnnotation(PoetUtils.generatedAnnotation()); } public static ParameterizedTypeName createParameterizedTypeName(ClassName className, String... typeVariables) { TypeName[] typeParameters = Arrays.stream(typeVariables).map(TypeVariableName::get).toArray(TypeName[]::new); return ParameterizedTypeName.get(className, typeParameters); } public static ParameterizedTypeName createParameterizedTypeName(Class<?> clazz, String... typeVariables) { return createParameterizedTypeName(ClassName.get(clazz), typeVariables); } public static TypeVariableName createBoundedTypeVariableName(String parameterName, ClassName upperBound, String... typeVariables) { return TypeVariableName.get(parameterName, createParameterizedTypeName(upperBound, typeVariables)); } public static ClassName classNameFromFqcn(String fqcn) { String basePath = fqcn.substring(0, fqcn.lastIndexOf('.')); String className = fqcn.substring(fqcn.lastIndexOf('.') + 1); return ClassName.get(basePath, className); } public static JavaFile buildJavaFile(ClassSpec spec) { JavaFile.Builder builder = JavaFile.builder(spec.className().packageName(), spec.poetSpec()).skipJavaLangImports(true); spec.staticImports().forEach(i -> i.memberNames().forEach(m -> builder.addStaticImport(i.className(), m))); return builder.build(); } }
3,387
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/PoetExtension.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet; import com.squareup.javapoet.ClassName; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; /** * Extension and convenience methods to Poet that use the intermediate model. */ public class PoetExtension { private final IntermediateModel model; public PoetExtension(IntermediateModel model) { this.model = model; } /** * @param className Simple name of class in model package. * @return A Poet {@link ClassName} for the given class in the model package. */ public ClassName getModelClass(String className) { return ClassName.get(model.getMetadata().getFullModelPackageName(), className); } /** * @param className Simple name of class in transform package. * @return A Poet {@link ClassName} for the given class in the transform package. */ public ClassName getTransformClass(String className) { return ClassName.get(model.getMetadata().getFullTransformPackageName(), className); } /** * @param className Simple name of class in transform package. * @return A Poet {@link ClassName} for the given class in the transform package. */ public ClassName getRequestTransformClass(String className) { return ClassName.get(model.getMetadata().getFullRequestTransformPackageName(), className); } /** * @param className Simple name of class in base service package (i.e. software.amazon.awssdk.services.dynamodb). * @return A Poet {@link ClassName} for the given class in the base service package. */ public ClassName getClientClass(String className) { return ClassName.get(model.getMetadata().getFullClientPackageName(), className); } /** * @return A Poet {@link ClassName} for the generated service client configuration. */ public ClassName getServiceConfigClass() { return PoetUtils.classNameFromFqcn(model.getMetadata().getFullClientPackageName() + "." + model.getMetadata().getServiceName() + "ServiceClientConfiguration"); } public ClassName getUserAgentClass() { return ClassName.get(model.getMetadata().getFullClientInternalPackageName(), "UserAgentUtils"); } /** * @param operationName Name of the operation * @return A Poet {@link ClassName} for the response type of a paginated operation in the base service package. * * Example: If operationName is "ListTables", then the response type of the paginated operation * will be "ListTablesIterable" class. */ public ClassName getResponseClassForPaginatedSyncOperation(String operationName) { return ClassName.get(model.getMetadata().getFullPaginatorsPackageName(), operationName + "Iterable"); } public ClassName getSyncWaiterInterface() { return ClassName.get(model.getMetadata().getFullWaitersPackageName(), model.getMetadata().getServiceName() + "Waiter"); } public ClassName getSyncWaiterClass() { return ClassName.get(model.getMetadata().getFullWaitersPackageName(), "Default" + model.getMetadata().getServiceName() + "Waiter"); } public ClassName getAsyncWaiterInterface() { return ClassName.get(model.getMetadata().getFullWaitersPackageName(), model.getMetadata().getServiceName() + "AsyncWaiter"); } public ClassName getAsyncWaiterClass() { return ClassName.get(model.getMetadata().getFullWaitersPackageName(), "Default" + model.getMetadata().getServiceName() + "AsyncWaiter"); } public ClassName getEndpointProviderInterfaceName() { return ClassName.get(model.getMetadata().getFullEndpointRulesPackageName(), model.getMetadata().getServiceName() + "EndpointProvider"); } /** * @param operationName Name of the operation * @return A Poet {@link ClassName} for the response type of a async paginated operation in the base service package. * * Example: If operationName is "ListTables", then the async response type of the paginated operation * will be "ListTablesPublisher" class. */ public ClassName getResponseClassForPaginatedAsyncOperation(String operationName) { return ClassName.get(model.getMetadata().getFullPaginatorsPackageName(), operationName + "Publisher"); } /** * @return ResponseMetadata className. eg: "S3ResponseMetadata" */ public ClassName getResponseMetadataClass() { return ClassName.get(model.getMetadata().getFullModelPackageName(), model.getSdkResponseBaseClassName() + "Metadata"); } /** * @return The correctly cased name of the API. */ public String getApiName(OperationModel operation) { return Utils.capitalize(operation.getOperationName()); } /** * @return The {@link ClassName} for the response pojo. */ public ClassName responsePojoType(OperationModel operation) { return getModelClass(operation.getOutputShape().getShapeName()); } // TODO Should we move the event stream specific methods to a new class /** * @return {@link ClassName} for generated event stream response handler interface. */ public ClassName eventStreamResponseHandlerType(OperationModel operation) { return getModelClass(getApiName(operation) + "ResponseHandler"); } /** * @return {@link ClassName} for the builder interface for the response handler interface */ public ClassName eventStreamResponseHandlerBuilderType(OperationModel operation) { return eventStreamResponseHandlerType(operation).nestedClass("Builder"); } /** * @return {@link ClassName} for the event stream visitor interface. */ public ClassName eventStreamResponseHandlerVisitorType(OperationModel operation) { return eventStreamResponseHandlerType(operation).nestedClass("Visitor"); } /** * @return {@link ClassName} for the builder interface for the event stream visitor interface. */ public ClassName eventStreamResponseHandlerVisitorBuilderType(OperationModel operation) { return eventStreamResponseHandlerVisitorType(operation).nestedClass("Builder"); } /** * @param shapeModel shape model for the class in model package * @return {@link ClassName} for the shape represented by the given {@link ShapeModel}. */ public ClassName getModelClassFromShape(ShapeModel shapeModel) { return getModelClass(shapeModel.getShapeName()); } public boolean isResponse(ShapeModel shapeModel) { return shapeModel.getShapeType() == ShapeType.Response; } public boolean isRequest(ShapeModel shapeModel) { return shapeModel.getShapeType() == ShapeType.Request; } }
3,388
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/eventstream/EventStreamVisitorBuilderInterfaceSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.eventstream; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.util.function.Consumer; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.docs.DocumentationBuilder; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.model.EventStreamSpecHelper; /** * Spec for builder interface for visitor. */ public class EventStreamVisitorBuilderInterfaceSpec implements ClassSpec { private final PoetExtension poetExt; private final OperationModel operationModel; private final ShapeModel eventStreamShape; private final ClassName visitorBuilderType; private final EventStreamSpecHelper eventStreamSpecHelper; EventStreamVisitorBuilderInterfaceSpec(PoetExtension poetExt, IntermediateModel intermediateModel, OperationModel opModel) { this.poetExt = poetExt; this.operationModel = opModel; this.eventStreamShape = EventStreamUtils.getEventStreamInResponse(operationModel.getOutputShape()); this.visitorBuilderType = poetExt.eventStreamResponseHandlerVisitorBuilderType(opModel); this.eventStreamSpecHelper = new EventStreamSpecHelper(eventStreamShape, intermediateModel); } @Override public final TypeSpec poetSpec() { TypeSpec.Builder typeBuilder = createTypeSpec() .addMethod(applyOnDefaultMethodSpecUpdates(createOnDefaultMethodSpec()).build()) .addMethod(applyBuildMethodSpecUpdates(createBuildMethodSpec()).build()); EventStreamUtils.getEvents(eventStreamShape) .forEach(e -> typeBuilder.addMethod( applyOnSubTypeMethodSpecUpdates(typeBuilder, createOnSubTypeMethodSpec(e), e) .build())); return typeBuilder.build(); } protected TypeSpec.Builder createTypeSpec() { String javadocs = "Builder for {@link $1T}. The {@link $1T} class may also be extended for a more " + "traditional style but this builder allows for a more functional way of creating a visitor " + "will callback methods."; return PoetUtils.createInterfaceBuilder(className()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc(javadocs, poetExt.eventStreamResponseHandlerVisitorType(operationModel)); } @Override public ClassName className() { return visitorBuilderType; } private MethodSpec.Builder createOnDefaultMethodSpec() { ParameterizedTypeName eventConsumerType = ParameterizedTypeName.get(ClassName.get(Consumer.class), poetExt.getModelClassFromShape(eventStreamShape)); return MethodSpec.methodBuilder("onDefault") .addModifiers(Modifier.PUBLIC) .addParameter(ParameterSpec.builder(eventConsumerType, "c").build()) .returns(visitorBuilderType); } protected MethodSpec.Builder applyOnDefaultMethodSpecUpdates(MethodSpec.Builder builder) { String javadocs = new DocumentationBuilder() .description("Callback to invoke when either an unknown event is visited or an unhandled event is visited.") .param("c", "Callback to process the event.") .returns("This builder for method chaining.") .build(); return builder.addModifiers(Modifier.ABSTRACT) .addJavadoc(javadocs); } private MethodSpec.Builder createBuildMethodSpec() { return MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .returns(poetExt.eventStreamResponseHandlerVisitorType(operationModel)); } protected MethodSpec.Builder applyBuildMethodSpecUpdates(MethodSpec.Builder builder) { return builder.addModifiers(Modifier.ABSTRACT) .addJavadoc("@return Visitor implementation."); } protected MethodSpec.Builder applyOnSubTypeMethodSpecUpdates(TypeSpec.Builder typeBuilder, MethodSpec.Builder methodBuilder, MemberModel event) { ClassName eventSubType = poetExt.getModelClass(event.getShape().getShapeName()); String javadocs = new DocumentationBuilder() .description("Callback to invoke when a {@link $T} is visited.") .param("c", "Callback to process the event.") .returns("This builder for method chaining.") .build(); return methodBuilder.addModifiers(Modifier.ABSTRACT) .addJavadoc(javadocs, eventSubType); } private MethodSpec.Builder createOnSubTypeMethodSpec(MemberModel event) { ClassName eventSubType = poetExt.getModelClass(event.getShape().getShapeName()); ParameterizedTypeName eventConsumerType = ParameterizedTypeName.get(ClassName.get(Consumer.class), eventSubType); return MethodSpec.methodBuilder(eventStreamSpecHelper.eventConsumerName(event)) .addModifiers(Modifier.PUBLIC) .addParameter(ParameterSpec.builder(eventConsumerType, "c").build()) .returns(visitorBuilderType); } }
3,389
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/eventstream/EventStreamResponseHandlerBuilderImplSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.eventstream; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.eventstream.DefaultEventStreamResponseHandlerBuilder; import software.amazon.awssdk.awscore.eventstream.EventStreamResponseHandlerFromBuilder; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; /** * Generates implementation class for the event stream response handler builder. */ public class EventStreamResponseHandlerBuilderImplSpec extends EventStreamResponseHandlerBuilderInterfaceSpec { private final PoetExtension poetExt; private final OperationModel operationModel; private final ClassName responseHandlerType; private final ClassName responseHandlerBuilderType; private final ClassName eventStreamBaseClass; public EventStreamResponseHandlerBuilderImplSpec(GeneratorTaskParams params, OperationModel operationModel) { super(params.getPoetExtensions(), operationModel); this.poetExt = params.getPoetExtensions(); this.operationModel = operationModel; this.responseHandlerType = poetExt.eventStreamResponseHandlerType(operationModel); this.responseHandlerBuilderType = poetExt.eventStreamResponseHandlerBuilderType(operationModel); this.eventStreamBaseClass = poetExt.getModelClassFromShape( EventStreamUtils.getEventStreamInResponse(operationModel.getOutputShape())); } @Override protected TypeSpec.Builder createTypeSpecBuilder() { ClassName responsePojoType = poetExt.responsePojoType(operationModel); ParameterizedTypeName superBuilderClass = ParameterizedTypeName.get(ClassName.get(DefaultEventStreamResponseHandlerBuilder.class), responsePojoType, eventStreamBaseClass, responseHandlerBuilderType); return PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.FINAL) .addAnnotation(SdkInternalApi.class) .superclass(superBuilderClass) .addSuperinterface(super.className()) .addType(implInnerClass(responsePojoType)); } @Override protected MethodSpec.Builder applySubscriberMethodSpecUpdates(MethodSpec.Builder builder) { return builder .addAnnotation(Override.class) .addCode(CodeBlock.builder() .addStatement("subscriber(e -> e.accept(visitor))") .addStatement("return this") .build()); } @Override protected MethodSpec.Builder applyBuildMethodSpecUpdates(MethodSpec.Builder builder) { return builder .addAnnotation(Override.class) .addCode(CodeBlock.builder() .addStatement("return new Impl(this)") .build()); } @Override public ClassName className() { String className = String.format("Default%sResponseHandlerBuilder", poetExt.getApiName(operationModel)); return poetExt.getModelClass(className); } private TypeSpec implInnerClass(ClassName responseClass) { ParameterizedTypeName superImplClass = ParameterizedTypeName.get(ClassName.get(EventStreamResponseHandlerFromBuilder.class), responseClass, eventStreamBaseClass); return PoetUtils.createClassBuilder(className().nestedClass("Impl")) .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .superclass(superImplClass) .addSuperinterface(responseHandlerType) .addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(ParameterSpec.builder(className(), "builder") .build()) .addStatement("super(builder)") .build()) .build(); } }
3,390
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/eventstream/EventTypeEnumSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.eventstream; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeSpec; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.naming.NamingStrategy; import software.amazon.awssdk.codegen.poet.common.AbstractEnumClass; public class EventTypeEnumSpec extends AbstractEnumClass { private final String enumPackageName; private final IntermediateModel intermediateModel; public EventTypeEnumSpec(String enumPackageName, IntermediateModel intermediateModel, ShapeModel eventStream) { super(eventStream); this.enumPackageName = enumPackageName; this.intermediateModel = intermediateModel; } @Override protected void addDeprecated(TypeSpec.Builder enumBuilder) { // no-op } @Override protected void addJavadoc(TypeSpec.Builder enumBuilder) { enumBuilder.addJavadoc("The known possible types of events for {@code $N}.", getShape().getShapeName()); } @Override protected void addEnumConstants(TypeSpec.Builder enumBuilder) { NamingStrategy namingStrategy = intermediateModel.getNamingStrategy(); getShape().getMembers().stream() .filter(m -> m.getShape().isEvent()) .forEach(m -> { String value = m.getC2jName(); String name = namingStrategy.getEnumValueName(value); enumBuilder.addEnumConstant(name, TypeSpec.anonymousClassBuilder("$S", value).build()); }); } @Override public ClassName className() { return ClassName.get(enumPackageName, "EventType"); } }
3,391
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/eventstream/EventStreamVisitorBuilderImplSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.eventstream; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.function.Consumer; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.model.EventStreamSpecHelper; /** * Generates the implementation for the builder of an event stream visitor. */ public class EventStreamVisitorBuilderImplSpec extends EventStreamVisitorBuilderInterfaceSpec { private final IntermediateModel intermediateModel; private final PoetExtension poetExt; private final OperationModel opModel; private final ClassName visitorType; private final ClassName visitorBuilderType; private final ClassName eventStreamBaseClass; private final EventStreamSpecHelper eventStreamSpecHelper; public EventStreamVisitorBuilderImplSpec(GeneratorTaskParams params, OperationModel operationModel) { super(params.getPoetExtensions(), params.getModel(), operationModel); this.intermediateModel = params.getModel(); this.poetExt = params.getPoetExtensions(); this.opModel = operationModel; this.visitorType = poetExt.eventStreamResponseHandlerVisitorType(opModel); this.visitorBuilderType = poetExt.eventStreamResponseHandlerVisitorBuilderType(opModel); ShapeModel eventStream = EventStreamUtils.getEventStreamInResponse(operationModel.getOutputShape()); this.eventStreamBaseClass = poetExt.getModelClassFromShape(eventStream); this.eventStreamSpecHelper = new EventStreamSpecHelper(eventStream, intermediateModel); } @Override protected TypeSpec.Builder createTypeSpec() { return PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.FINAL) .addAnnotation(SdkInternalApi.class) .addSuperinterface(visitorBuilderType) .addField(FieldSpec.builder(consumerType(eventStreamBaseClass), "onDefault") .addModifiers(Modifier.PRIVATE) .build()) .addType(new VisitorFromBuilderImplSpec().poetSpec()); } private class VisitorFromBuilderImplSpec extends EventStreamVisitorInterfaceSpec { private final MethodSpec.Builder constrBuilder; VisitorFromBuilderImplSpec() { super(intermediateModel, poetExt, opModel); this.constrBuilder = MethodSpec.constructorBuilder() .addParameter(enclosingClassName(), "builder") .addStatement("this.onDefault = builder.onDefault != null ?\n" + "builder.onDefault :\n" + "$T.super::visitDefault", visitorType); } @Override protected TypeSpec.Builder createTypeSpec() { return PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.STATIC) .addField(consumerType(eventStreamBaseClass), "onDefault", Modifier.PRIVATE, Modifier.FINAL) .addSuperinterface(visitorType); } @Override protected TypeSpec.Builder finalizeTypeSpec(TypeSpec.Builder builder) { return builder.addMethod(constrBuilder.build()); } @Override protected MethodSpec.Builder applyVisitDefaultMethodSpecUpdates(MethodSpec.Builder builder) { return builder.addAnnotation(Override.class) .addStatement("onDefault.accept(event)"); } @Override protected MethodSpec.Builder applyVisitSubTypeMethodSpecUpdates(TypeSpec.Builder typeBuilder, MethodSpec.Builder methodBuilder, MemberModel event) { ClassName eventSubType = poetExt.getModelClass(event.getShape().getShapeName()); TypeName eventConsumerType = consumerType(eventSubType); FieldSpec consumerField = FieldSpec.builder(eventConsumerType, eventStreamSpecHelper.eventConsumerName(event)) .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .build(); typeBuilder.addField(consumerField); constrBuilder.addStatement("this.$1L = builder.$1L != null ?\n" + "builder.$1L :\n" + "$2T.super::$3N", consumerField.name, visitorType, eventStreamSpecHelper.visitMethodName(event)); return methodBuilder .addAnnotation(Override.class) .addStatement("$L.accept(event)", consumerField.name); } @Override public ClassName className() { return enclosingClassName().nestedClass("VisitorFromBuilder"); } private ClassName enclosingClassName() { return EventStreamVisitorBuilderImplSpec.this.className(); } } @Override protected MethodSpec.Builder applyOnSubTypeMethodSpecUpdates(TypeSpec.Builder typeBuilder, MethodSpec.Builder methodBuilder, MemberModel event) { ClassName eventSubType = poetExt.getModelClass(event.getShape().getShapeName()); TypeName eventConsumerType = consumerType(eventSubType); FieldSpec consumerField = FieldSpec.builder(eventConsumerType, eventStreamSpecHelper.eventConsumerName(event)) .addModifiers(Modifier.PRIVATE) .build(); typeBuilder.addField(consumerField); return methodBuilder .addAnnotation(Override.class) .addStatement("this.$L = c", consumerField.name) .addStatement("return this"); } @Override protected MethodSpec.Builder applyOnDefaultMethodSpecUpdates(MethodSpec.Builder builder) { return builder.addAnnotation(Override.class) .addStatement("this.onDefault = c") .addStatement("return this"); } @Override protected MethodSpec.Builder applyBuildMethodSpecUpdates(MethodSpec.Builder builder) { return builder.addAnnotation(Override.class) .addStatement("return new $T(this)", className().nestedClass("VisitorFromBuilder")); } @Override public ClassName className() { return poetExt.getModelClass(String.format("Default%sVisitorBuilder", poetExt.getApiName(opModel))); } private TypeName consumerType(ClassName paramType) { return ParameterizedTypeName.get(ClassName.get(Consumer.class), paramType); } }
3,392
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/eventstream/EventStreamResponseHandlerSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.eventstream; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.awscore.eventstream.EventStreamResponseHandler; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; /** * Generates response handler interface for operations with an event stream response. */ public class EventStreamResponseHandlerSpec implements ClassSpec { private final IntermediateModel intermediateModel; private final PoetExtension poetExt; private final OperationModel operationModel; private final String apiName; private final ClassName responsePojoType; private final ClassName responseHandlerBuilderType; private final ClassName eventStreamBaseClass; public EventStreamResponseHandlerSpec(GeneratorTaskParams params, OperationModel operationModel) { this.intermediateModel = params.getModel(); this.poetExt = params.getPoetExtensions(); this.operationModel = operationModel; this.apiName = poetExt.getApiName(operationModel); this.responsePojoType = poetExt.responsePojoType(operationModel); this.responseHandlerBuilderType = poetExt.eventStreamResponseHandlerBuilderType(operationModel); this.eventStreamBaseClass = poetExt.getModelClassFromShape( EventStreamUtils.getEventStreamInResponse(operationModel.getOutputShape())); } @Override public TypeSpec poetSpec() { ParameterizedTypeName superResponseHandlerInterface = ParameterizedTypeName.get( ClassName.get(EventStreamResponseHandler.class), responsePojoType, eventStreamBaseClass); return PoetUtils.createInterfaceBuilder(className()) .addModifiers(Modifier.PUBLIC) .addAnnotation(SdkPublicApi.class) .addSuperinterface(superResponseHandlerInterface) .addJavadoc("Response handler for the $L API.", apiName) .addMethod(builderMethodSpec()) .addType(new EventStreamResponseHandlerBuilderInterfaceSpec(poetExt, operationModel).poetSpec()) .addType(new EventStreamVisitorInterfaceSpec(intermediateModel, poetExt, operationModel).poetSpec()) .build(); } @Override public ClassName className() { return poetExt.eventStreamResponseHandlerType(operationModel); } private MethodSpec builderMethodSpec() { return MethodSpec.methodBuilder("builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc("Create a {@link $T}, used to create a {@link $T}.", responseHandlerBuilderType, className()) .addStatement("return new $T()", poetExt.getModelClass(String.format("Default%sResponseHandlerBuilder", apiName))) .returns(responseHandlerBuilderType) .build(); } }
3,393
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/eventstream/EventStreamResponseHandlerBuilderInterfaceSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.eventstream; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.util.function.Supplier; import javax.lang.model.element.Modifier; import org.reactivestreams.Publisher; import software.amazon.awssdk.awscore.eventstream.EventStreamResponseHandler; import software.amazon.awssdk.codegen.docs.DocumentationBuilder; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; /** * Spec for generated response handler builder */ public class EventStreamResponseHandlerBuilderInterfaceSpec implements ClassSpec { private final PoetExtension poetExtensions; private final OperationModel opModel; private final ClassName responsePojoType; private final ClassName responseHandlerType; public EventStreamResponseHandlerBuilderInterfaceSpec(PoetExtension poetExt, OperationModel operationModel) { this.poetExtensions = poetExt; this.opModel = operationModel; this.responsePojoType = poetExt.responsePojoType(operationModel); this.responseHandlerType = poetExt.eventStreamResponseHandlerType(operationModel); } @Override public final TypeSpec poetSpec() { return createTypeSpecBuilder() .addMethod(applySubscriberMethodSpecUpdates(createSubscriberMethodSpecBuilder()).build()) .addMethod(applyBuildMethodSpecUpdates(createBuildMethodSpecBuilder()).build()) .build(); } /** * Hook to create the {@link TypeSpec} builder implementation. */ protected TypeSpec.Builder createTypeSpecBuilder() { ParameterizedTypeName superBuilderInterface = ParameterizedTypeName.get( ClassName.get(EventStreamResponseHandler.class).nestedClass("Builder"), responsePojoType, poetExtensions.getModelClassFromShape(EventStreamUtils.getEventStreamInResponse(opModel.getOutputShape())), className()); return PoetUtils.createInterfaceBuilder(className()).addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc("Builder for {@link $1T}. This can be used to create the {@link $1T} in a more " + "functional way, you may also directly implement the {@link $1T} interface if " + "preferred.", responseHandlerType) .addSuperinterface(superBuilderInterface); } /** * Hook to customize the 'subscriber' method before building the {@link MethodSpec}. * * @param builder Builder to update. */ protected MethodSpec.Builder applySubscriberMethodSpecUpdates(MethodSpec.Builder builder) { String javadocs = new DocumentationBuilder() .description("Sets the subscriber to the {@link $T} of events. The given " + "{@link $T} will be called for each event received by the " + "publisher. Events are requested sequentially after each event is " + "processed. If you need more control over the backpressure strategy " + "consider using {@link #subscriber($T)} instead.") .param("visitor", "Visitor that will be invoked for each incoming event.") .returns("This builder for method chaining") .build(); ClassName visitorInterface = poetExtensions.eventStreamResponseHandlerVisitorType(opModel); return builder.addModifiers(Modifier.ABSTRACT) .addJavadoc(javadocs, Publisher.class, visitorInterface, Supplier.class); } /** * Creates the {@link MethodSpec.Builder} for the 'subscriber' method that may be customized by subclass. */ private MethodSpec.Builder createSubscriberMethodSpecBuilder() { ClassName visitorInterface = poetExtensions.eventStreamResponseHandlerVisitorType(opModel); return MethodSpec.methodBuilder("subscriber") .addModifiers(Modifier.PUBLIC) .addParameter(ParameterSpec.builder(visitorInterface, "visitor") .build()) .returns(poetExtensions.eventStreamResponseHandlerBuilderType(opModel)); } /** * Hook to customize the 'build' method before building the {@link MethodSpec}. * * @param builder Builder to update. */ protected MethodSpec.Builder applyBuildMethodSpecUpdates(MethodSpec.Builder builder) { return builder.addModifiers(Modifier.ABSTRACT) .addJavadoc("@return A {@link $T} implementation that can be used in the $L API call.", responseHandlerType, poetExtensions.getApiName(opModel)); } /** * Creates the {@link MethodSpec.Builder} for the 'build' method that may be customized by subclass. */ private MethodSpec.Builder createBuildMethodSpecBuilder() { return MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .returns(responseHandlerType); } @Override public ClassName className() { return poetExtensions.eventStreamResponseHandlerBuilderType(opModel); } }
3,394
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/eventstream/EventStreamVisitorInterfaceSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.eventstream; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeSpec; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.docs.DocumentationBuilder; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.model.EventStreamSpecHelper; /** * Spec for generated visitor interface. */ class EventStreamVisitorInterfaceSpec implements ClassSpec { private final PoetExtension poetExt; private final IntermediateModel intermediateModel; private final OperationModel operationModel; private final ShapeModel eventStreamShape; private final ClassName eventStreamBaseClass; private final EventStreamSpecHelper eventStreamSpecHelper; EventStreamVisitorInterfaceSpec(IntermediateModel intermediateModel, PoetExtension poetExt, OperationModel operationModel) { this.poetExt = poetExt; this.intermediateModel = intermediateModel; this.operationModel = operationModel; this.eventStreamShape = EventStreamUtils.getEventStreamInResponse(operationModel.getOutputShape()); this.eventStreamBaseClass = poetExt.getModelClassFromShape(eventStreamShape); this.eventStreamSpecHelper = new EventStreamSpecHelper(eventStreamShape, intermediateModel); } @Override public final TypeSpec poetSpec() { TypeSpec.Builder typeBuilder = createTypeSpec() .addMethod(applyVisitDefaultMethodSpecUpdates(createVisitDefaultMethodSpec()).build()); EventStreamUtils.getEvents(eventStreamShape) .forEach(e -> typeBuilder.addMethod( applyVisitSubTypeMethodSpecUpdates(typeBuilder, createVisitSubTypeMethodSpec(e), e) .build())); return finalizeTypeSpec(typeBuilder).build(); } @Override public ClassName className() { return poetExt.eventStreamResponseHandlerVisitorType(operationModel); } protected TypeSpec.Builder createTypeSpec() { return PoetUtils.createInterfaceBuilder(className()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc("Visitor for subtypes of {@link $T}.", eventStreamBaseClass) .addMethod(createBuilderMethodSpec()) .addType(new EventStreamVisitorBuilderInterfaceSpec(poetExt, intermediateModel, operationModel) .poetSpec()); } protected TypeSpec.Builder finalizeTypeSpec(TypeSpec.Builder builder) { return builder; } private MethodSpec.Builder createVisitDefaultMethodSpec() { return MethodSpec.methodBuilder("visitDefault") .addModifiers(Modifier.PUBLIC) .addParameter(ParameterSpec.builder(eventStreamBaseClass, "event").build()); } protected MethodSpec.Builder applyVisitDefaultMethodSpecUpdates(MethodSpec.Builder builder) { String javadocs = new DocumentationBuilder() .description("A required \"else\" or \"default\" block, invoked when no other more-specific \"visit\" method is " + "appropriate. This is invoked under two circumstances:\n" + "<ol>\n" + "<li>The event encountered is newer than the current version of the SDK, so no other " + "more-specific \"visit\" method could be called. In this case, the provided event will be a " + "generic {@link $1T}. These events can be processed by upgrading the SDK.</li>\n" + "<li>The event is known by the SDK, but the \"visit\" was not overridden above. In this case, the " + "provided event will be a specific type of {@link $1T}.</li>\n" + "</ol>") .param("event", "The event that was not handled by a more-specific \"visit\" method.") .build(); return builder.addModifiers(Modifier.DEFAULT) .addJavadoc(javadocs, eventStreamBaseClass); } private MethodSpec.Builder createVisitSubTypeMethodSpec(MemberModel event) { ClassName eventSubType = poetExt.getModelClass(event.getShape().getShapeName()); return MethodSpec.methodBuilder(visitorMethodName(event)) .addModifiers(Modifier.PUBLIC) .addParameter(ParameterSpec.builder(eventSubType, "event").build()); } protected MethodSpec.Builder applyVisitSubTypeMethodSpecUpdates(TypeSpec.Builder typeBuilder, MethodSpec.Builder methodBuilder, MemberModel event) { ClassName eventSubType = poetExt.getModelClass(event.getShape().getShapeName()); String javadocs = new DocumentationBuilder() .description("Invoked when a {@link $T} is encountered. If this is not overridden, the event will " + "be given to {@link #visitDefault($T)}.") .param("event", "Event being visited") .build(); return methodBuilder.addModifiers(Modifier.DEFAULT) .addStatement("visitDefault(event)") .addJavadoc(javadocs, eventSubType, eventStreamBaseClass); } protected String visitorMethodName(MemberModel event) { return eventStreamSpecHelper.visitMethodName(event); } private MethodSpec createBuilderMethodSpec() { ClassName visitorBuilderType = poetExt.eventStreamResponseHandlerVisitorBuilderType(operationModel); return MethodSpec.methodBuilder("builder") .addJavadoc("@return A new {@link Builder}.", visitorBuilderType) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(visitorBuilderType) .addStatement("return new Default$LVisitorBuilder()", poetExt.getApiName(operationModel)) .build(); } }
3,395
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/eventstream/EventStreamUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.eventstream; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; /** * Utils for event streaming code generation. */ public class EventStreamUtils { private EventStreamUtils() { } /** * Get eventstream member from a request shape model. If shape doesn't have any eventstream member, * throw an IllegalStateException. * * @param requestShape request shape of an operation * @return eventstream member (shape with "eventstream" trait set to true) in the request shape. * If there is no eventstream member, thrown IllegalStateException. */ public static ShapeModel getEventStreamInRequest(ShapeModel requestShape) { return eventStreamFrom(requestShape); } /** * Get eventstream member from a response shape model. If shape doesn't have any eventstream member, * throw an IllegalStateException. * * @param responseShape response shape of an operation * @return eventstream member (shape with "eventstream" trait set to true) in the response shape. * If there is no eventstream member, thrown IllegalStateException. */ public static ShapeModel getEventStreamInResponse(ShapeModel responseShape) { return eventStreamFrom(responseShape); } /** * Get event stream shape from a request/response shape model. Otherwise, throw * * @param shapeModel request or response shape of an operation * @return the EventStream shape * @throws IllegalStateException if there is no associated event stream shape */ private static ShapeModel eventStreamFrom(ShapeModel shapeModel) { if (shapeModel == null || shapeModel.getMembers() == null) { return null; } return shapeModel.getMembers() .stream() .map(MemberModel::getShape) .filter(Objects::nonNull) .filter(ShapeModel::isEventStream) .findFirst() .orElseThrow(() -> new IllegalStateException(String.format( "%s has no event stream member", shapeModel.getC2jName()))); } /** * Returns the event stream {@link ShapeModel} that contains the given event. * * @param model Intermediate model * @param eventShape shape with "event: true" trait * @return the event stream shape (eventstream: true) that contains the given event, or an empty optional if the C2J shape * is marked as an event but the intermediate model representation is not used by an event stream */ public static Optional<ShapeModel> getBaseEventStreamShape(IntermediateModel model, ShapeModel eventShape) { return model.getShapes().values() .stream() .filter(ShapeModel::isEventStream) .filter(s -> s.getMembers().stream().anyMatch(m -> m.getShape().equals(eventShape))) .findFirst(); } public static List<ShapeModel> getBaseEventStreamShapes(IntermediateModel model, ShapeModel eventShape) { return model.getShapes().values() .stream() .filter(ShapeModel::isEventStream) .filter(s -> s.getMembers().stream().anyMatch(m -> m.getShape().equals(eventShape))) .collect(Collectors.toList()); } /** * Returns the stream of event members ('event: true') excluding exceptions * from the input event stream shape ('eventstream: true'). */ public static Stream<MemberModel> getEvents(ShapeModel eventStreamShape) { return getEventMembers(eventStreamShape); } /** * Returns the stream of event members ('event: true') excluding exceptions * from the input event stream shape ('eventstream: true'). */ public static Stream<MemberModel> getEventMembers(ShapeModel eventStreamShape) { if (eventStreamShape == null || eventStreamShape.getMembers() == null) { return Stream.empty(); } return eventStreamShape.getMembers() .stream() .filter(m -> m.getShape() != null && m.getShape().isEvent()); } /** * Returns the all operations that contain the given event stream shape. The event stream can be in operation * request or response shape. */ public static Collection<OperationModel> findOperationsWithEventStream(IntermediateModel model, ShapeModel eventStreamShape) { Collection<OperationModel> operations = model.getOperations().values() .stream() .filter(op -> operationContainsEventStream(op, eventStreamShape)) .collect(Collectors.toList()); if (operations.isEmpty()) { throw new IllegalStateException(String.format( "%s is an event shape but has no corresponding operation in the model", eventStreamShape.getC2jName())); } return operations; } /** * Returns true if the #childEventStreamShape is a member of the #parentShape. Otherwise false. */ public static boolean doesShapeContainsEventStream(ShapeModel parentShape, ShapeModel childEventStreamShape) { return parentShape != null && parentShape.getMembers() != null && parentShape.getMembers().stream() .filter(m -> m.getShape() != null) .filter(m -> m.getShape().equals(childEventStreamShape)) .anyMatch(m -> m.getShape().isEventStream()); } /** * Returns true if the given event shape is a sub-member of any operation request. */ public static boolean isRequestEvent(IntermediateModel model, ShapeModel eventShape) { return getBaseEventStreamShape(model, eventShape) .map(stream -> model.getOperations().values() .stream() .anyMatch(o -> doesShapeContainsEventStream(o.getInputShape(), stream))) .orElse(false); } private static boolean operationContainsEventStream(OperationModel opModel, ShapeModel eventStreamShape) { return doesShapeContainsEventStream(opModel.getInputShape(), eventStreamShape) || doesShapeContainsEventStream(opModel.getOutputShape(), eventStreamShape); } /** * @return true if the provide model is a request/response shape model that contains event stream shape. * Otherwise return false. */ public static boolean isEventStreamParentModel(ShapeModel shapeModel) { return containsEventStream(shapeModel); } private static boolean containsEventStream(ShapeModel shapeModel) { return shapeModel != null && shapeModel.getMembers() != null && shapeModel.getMembers().stream() .filter(m -> m.getShape() != null) .anyMatch(m -> m.getShape().isEventStream()); } }
3,396
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/paginators/SyncResponseClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.paginators; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Collections; import java.util.Iterator; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.service.PaginatorDefinition; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.core.pagination.sync.PaginatedItemsIterable; import software.amazon.awssdk.core.pagination.sync.PaginatedResponsesIterator; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.core.pagination.sync.SyncPageFetcher; /** * Java poet {@link ClassSpec} to generate the response class for sync paginated operations. */ public class SyncResponseClassSpec extends PaginatorsClassSpec { protected static final String ITERATOR_METHOD = "iterator"; public SyncResponseClassSpec(IntermediateModel model, String c2jOperationName, PaginatorDefinition paginatorDefinition) { super(model, c2jOperationName, paginatorDefinition); } @Override public TypeSpec poetSpec() { TypeSpec.Builder specBuilder = TypeSpec.classBuilder(className()) .addModifiers(Modifier.PUBLIC) .addAnnotation(PoetUtils.generatedAnnotation()) .addSuperinterface(getSyncResponseInterface()) .addFields(fields().collect(Collectors.toList())) .addMethod(constructor()) .addMethod(iteratorMethod()) .addMethods(getMethodSpecsForResultKeyList()) .addJavadoc(paginationDocs.getDocsForSyncResponseClass( getClientInterfaceName())) .addType(nextPageFetcherClass().build()); return specBuilder.build(); } @Override public ClassName className() { return poetExtensions.getResponseClassForPaginatedSyncOperation(c2jOperationName); } /** * Returns the interface that is implemented by the Paginated Sync Response class. */ private TypeName getSyncResponseInterface() { return ParameterizedTypeName.get(ClassName.get(SdkIterable.class), responseType()); } /** * @return A Poet {@link ClassName} for the sync client interface */ protected ClassName getClientInterfaceName() { return poetExtensions.getClientClass(model.getMetadata().getSyncInterface()); } protected Stream<FieldSpec> fields() { return Stream.of(syncClientInterfaceField(), requestClassField(), syncPageFetcherField()); } protected FieldSpec syncClientInterfaceField() { return FieldSpec.builder(getClientInterfaceName(), CLIENT_MEMBER, Modifier.PRIVATE, Modifier.FINAL).build(); } private FieldSpec syncPageFetcherField() { return FieldSpec.builder(SyncPageFetcher.class, NEXT_PAGE_FETCHER_MEMBER, Modifier.PRIVATE, Modifier.FINAL).build(); } protected MethodSpec constructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(getClientInterfaceName(), CLIENT_MEMBER) .addParameter(requestType(), REQUEST_MEMBER) .addStatement("this.$L = $L", CLIENT_MEMBER, CLIENT_MEMBER) .addStatement("this.$L = $T.applyPaginatorUserAgent($L)", REQUEST_MEMBER, poetExtensions.getUserAgentClass(), REQUEST_MEMBER) .addStatement("this.$L = new $L()", NEXT_PAGE_FETCHER_MEMBER, nextPageFetcherClassName()) .build(); } /** * A {@link MethodSpec} for the overridden iterator() method which is inherited * from the interface. */ protected MethodSpec iteratorMethod() { return MethodSpec.methodBuilder(ITERATOR_METHOD) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(ParameterizedTypeName.get(ClassName.get(Iterator.class), responseType())) .addStatement("return $1T.builder().$2L($3L).build()", PaginatedResponsesIterator.class, NEXT_PAGE_FETCHER_MEMBER, nextPageFetcherArgument()) .build(); } protected String nextPageFetcherArgument() { return NEXT_PAGE_FETCHER_MEMBER; } /** * Returns iterable of {@link MethodSpec} to generate helper methods for all members * in {@link PaginatorDefinition#getResultKey()}. All the generated methods return an SdkIterable. * * The helper methods to iterate on paginated member will be generated only * if {@link PaginatorDefinition#getResultKey()} is not null and a non-empty list. */ private Iterable<MethodSpec> getMethodSpecsForResultKeyList() { if (paginatorDefinition.getResultKey() != null) { return paginatorDefinition.getResultKey().stream() .map(this::getMethodsSpecForSingleResultKey) .filter(Objects::nonNull) .collect(Collectors.toList()); } return Collections.emptyList(); } /* * Generate a method spec for single element in {@link PaginatorDefinition#getResultKey()} list. * * If the element is "Folders" and its type is "List<FolderMetadata>", generated code looks like: * * public SdkIterable<FolderMetadata> folders() { * Function<DescribeFolderContentsResponse, Iterator<FolderMetadata>> getIterator = response -> { * if (response != null && response.folders() != null) { * return response.folders().iterator(); * } * return Collections.emptyIterator(); * }; * * return PaginatedItemsIterable.builder().pagesIterable(this).itemIteratorFunction(getIterator).build(); * } */ private MethodSpec getMethodsSpecForSingleResultKey(String resultKey) { MemberModel resultKeyModel = memberModelForResponseMember(resultKey); // TODO: Support other types besides List or Map if (!(resultKeyModel.isList() || resultKeyModel.isMap())) { return null; } TypeName resultKeyType = getTypeForResultKey(resultKey); return MethodSpec.methodBuilder(resultKeyModel.getFluentGetterMethodName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(ParameterizedTypeName.get(ClassName.get(SdkIterable.class), resultKeyType)) .addCode("$T getIterator = ", ParameterizedTypeName.get(ClassName.get(Function.class), responseType(), ParameterizedTypeName.get(ClassName.get(Iterator.class), resultKeyType))) .addCode(getIteratorLambdaBlock(resultKey, resultKeyModel)) .addCode("\n") .addStatement("return $T.<$T, $T>builder().pagesIterable(this).itemIteratorFunction(getIterator).build" + "()", PaginatedItemsIterable.class, responseType(), resultKeyType) .addJavadoc(CodeBlock.builder() .add("Returns an iterable to iterate through the paginated {@link $T#$L()} member." + " The returned iterable is used to iterate through the results across all " + "response pages and not a single page.\n", responseType(), resultKeyModel.getFluentGetterMethodName()) .add("\n") .add("This method is useful if you are interested in iterating over the paginated " + "member in the response pages instead of the top level pages. " + "Similar to iteration over pages, this method internally makes service " + "calls to get the next list of results until the iteration stops or " + "there are no more results.") .build()) .build(); } /** * Generates a inner class that implements {@link SyncPageFetcher}. An instance of this class * is passed to {@link PaginatedResponsesIterator} to be used while iterating through pages. */ protected TypeSpec.Builder nextPageFetcherClass() { return TypeSpec.classBuilder(nextPageFetcherClassName()) .addModifiers(Modifier.PRIVATE) .addSuperinterface(ParameterizedTypeName.get(ClassName.get(SyncPageFetcher.class), responseType())) .addMethod(MethodSpec.methodBuilder(HAS_NEXT_PAGE_METHOD) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(responseType(), PREVIOUS_PAGE_METHOD_ARGUMENT) .returns(boolean.class) .addStatement(hasNextPageMethodBody()) .build()) .addMethod(MethodSpec.methodBuilder(NEXT_PAGE_METHOD) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(responseType(), PREVIOUS_PAGE_METHOD_ARGUMENT) .returns(responseType()) .addCode(nextPageMethodBody()) .build()); } }
3,397
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/paginators/PaginatorsClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.paginators; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import java.security.InvalidParameterException; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.docs.PaginationDocs; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.service.PaginatorDefinition; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.model.TypeProvider; import software.amazon.awssdk.core.util.PaginatorUtils; public abstract class PaginatorsClassSpec implements ClassSpec { protected static final String CLIENT_MEMBER = "client"; protected static final String REQUEST_MEMBER = "firstRequest"; protected static final String NEXT_PAGE_FETCHER_MEMBER = "nextPageFetcher"; protected static final String HAS_NEXT_PAGE_METHOD = "hasNextPage"; protected static final String NEXT_PAGE_METHOD = "nextPage"; protected static final String RESUME_METHOD = "resume"; protected static final String PREVIOUS_PAGE_METHOD_ARGUMENT = "previousPage"; protected static final String RESPONSE_LITERAL = "response"; protected static final String LAST_SUCCESSFUL_PAGE_LITERAL = "lastSuccessfulPage"; protected final IntermediateModel model; protected final String c2jOperationName; protected final PaginatorDefinition paginatorDefinition; protected final PoetExtension poetExtensions; protected final TypeProvider typeProvider; protected final OperationModel operationModel; protected final PaginationDocs paginationDocs; public PaginatorsClassSpec(IntermediateModel model, String c2jOperationName, PaginatorDefinition paginatorDefinition) { this.model = model; this.c2jOperationName = c2jOperationName; this.paginatorDefinition = paginatorDefinition; this.poetExtensions = new PoetExtension(model); this.typeProvider = new TypeProvider(model); this.operationModel = model.getOperation(c2jOperationName); this.paginationDocs = new PaginationDocs(model, operationModel, paginatorDefinition); } /** * @return A Poet {@link ClassName} for the operation request type. * * Example: For ListTables operation, it will be "ListTablesRequest" class. */ protected ClassName requestType() { return poetExtensions.getModelClass(operationModel.getInput().getVariableType()); } /** * @return A Poet {@link ClassName} for the sync operation response type. * * Example: For ListTables operation, it will be "ListTablesResponse" class. */ protected ClassName responseType() { return poetExtensions.getModelClass(operationModel.getReturnType().getReturnType()); } // Generates // private final ListTablesRequest firstRequest; protected FieldSpec requestClassField() { return FieldSpec.builder(requestType(), REQUEST_MEMBER, Modifier.PRIVATE, Modifier.FINAL).build(); } protected String nextPageFetcherClassName() { return operationModel.getReturnType().getReturnType() + "Fetcher"; } protected MethodSpec.Builder resumeMethodBuilder() { return MethodSpec.methodBuilder(RESUME_METHOD) .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .addParameter(responseType(), LAST_SUCCESSFUL_PAGE_LITERAL) .returns(className()) .addCode(CodeBlock.builder() .beginControlFlow("if ($L.$L($L))", NEXT_PAGE_FETCHER_MEMBER, HAS_NEXT_PAGE_METHOD, LAST_SUCCESSFUL_PAGE_LITERAL) .addStatement("return new $T($L, $L)", className(), CLIENT_MEMBER, constructRequestFromLastPage(LAST_SUCCESSFUL_PAGE_LITERAL)) .endControlFlow() .build()) .addJavadoc(CodeBlock.builder() .add("<p>A helper method to resume the pages in case of unexpected failures. " + "The method takes the last successful response page as input and returns an " + "instance of {@link $T} that can be used to retrieve the consecutive pages " + "that follows the input page.</p>", className()) .build()); } /* * Returns the {@link TypeName} for a value in the {@link PaginatorDefinition#getResultKey()} list. * * Examples: * If paginated item is represented as List<String>, then member type is String. * If paginated item is represented as List<Foo>, then member type is Foo. * If paginated item is represented as Map<String, List<Foo>>, * then member type is Map.Entry<String, List<Foo>>. */ protected TypeName getTypeForResultKey(String singleResultKey) { MemberModel resultKeyModel = memberModelForResponseMember(singleResultKey); if (resultKeyModel == null) { throw new InvalidParameterException("MemberModel is not found for result key: " + singleResultKey); } if (resultKeyModel.isList()) { return typeProvider.fieldType(resultKeyModel.getListModel().getListMemberModel()); } else if (resultKeyModel.isMap()) { return typeProvider.mapEntryWithConcreteTypes(resultKeyModel.getMapModel()); } else { throw new IllegalArgumentException(String.format("Key %s in paginated operation %s should be either a list or a map", singleResultKey, c2jOperationName)); } } /** * @param input A top level or nested member in response of {@link #c2jOperationName}. * * @return The {@link MemberModel} of the {@link PaginatorDefinition#getResultKey()}. If input value is nested, * then member model of the last child shape is returned. * * For example, if input is StreamDescription.Shards, then the return value is "Shard" which is the member model for * the Shards. */ protected MemberModel memberModelForResponseMember(String input) { String[] hierarchy = input.split("\\."); if (hierarchy.length < 1) { throw new IllegalArgumentException(String.format("Error when splitting value %s for operation %s", input, c2jOperationName)); } ShapeModel shape = operationModel.getOutputShape(); for (int i = 0; i < hierarchy.length - 1; i++) { shape = shape.findMemberModelByC2jName(hierarchy[i]).getShape(); } return shape.getMemberByC2jName(hierarchy[hierarchy.length - 1]); } protected CodeBlock hasNextPageMethodBody() { if (paginatorDefinition.getMoreResults() != null) { return CodeBlock.builder() .add("return $N.$L.booleanValue()", PREVIOUS_PAGE_METHOD_ARGUMENT, fluentGetterMethodForResponseMember(paginatorDefinition.getMoreResults())) .build(); } // If there is no more_results token, then output_token will be a single value return CodeBlock.builder() .add("return $3T.isOutputTokenAvailable($1N.$2L)", PREVIOUS_PAGE_METHOD_ARGUMENT, fluentGetterMethodsForOutputToken().get(0), PaginatorUtils.class) .build(); } /* * Returns {@link CodeBlock} for the NEXT_PAGE_METHOD. * * A sample from dynamoDB listTables paginator: * * if (oldPage == null) { * return client.listTables(firstRequest); * } else { * return client.listTables(firstRequest.toBuilder().exclusiveStartTableName(response.lastEvaluatedTableName()) * .build()); * } */ protected CodeBlock nextPageMethodBody() { return CodeBlock.builder() .beginControlFlow("if ($L == null)", PREVIOUS_PAGE_METHOD_ARGUMENT) .addStatement("return $L.$L($L)", CLIENT_MEMBER, operationModel.getMethodName(), REQUEST_MEMBER) .endControlFlow() .addStatement(codeToGetNextPageIfOldResponseIsNotNull()) .build(); } /** * Generates the code to get next page by using values from old page. * * Sample generated code: * return client.listTables(firstRequest.toBuilder().exclusiveStartTableName(response.lastEvaluatedTableName()).build()); */ protected String codeToGetNextPageIfOldResponseIsNotNull() { return String.format("return %s.%s(%s)", CLIENT_MEMBER, operationModel.getMethodName(), constructRequestFromLastPage(PREVIOUS_PAGE_METHOD_ARGUMENT)); } /** * Generates the code to construct a request object from the last successful page * by setting the fields required to get the next page. * * Sample code: if responsePage string is "response" * firstRequest.toBuilder().exclusiveStartTableName(response.lastEvaluatedTableName()).build() */ protected String constructRequestFromLastPage(String responsePage) { StringBuilder sb = new StringBuilder(); sb.append(String.format("%s.toBuilder()", REQUEST_MEMBER)); List<String> requestSetterNames = fluentSetterMethodNamesForInputToken(); List<String> responseGetterMethods = fluentGetterMethodsForOutputToken(); for (int i = 0; i < paginatorDefinition.getInputToken().size(); i++) { sb.append(String.format(".%s(%s.%s)", requestSetterNames.get(i), responsePage, responseGetterMethods.get(i))); } sb.append(".build()"); return sb.toString(); } /** * Returns a list of fluent setter method names for members in {@link PaginatorDefinition#getInputToken()} list. * The size of list returned by this method is equal to the size of {@link PaginatorDefinition#getInputToken()} list. */ private List<String> fluentSetterMethodNamesForInputToken() { return paginatorDefinition.getInputToken().stream() .map(this::fluentSetterNameForSingleInputToken) .collect(Collectors.toList()); } /** * Returns the fluent setter method name for a single member in the request. * * The values in {@link PaginatorDefinition#getInputToken()} are not nested unlike * {@link PaginatorDefinition#getOutputToken()}. */ private String fluentSetterNameForSingleInputToken(String inputToken) { return operationModel.getInputShape() .findMemberModelByC2jName(inputToken) .getFluentSetterMethodName(); } /** * Returns a list of fluent getter methods for members in {@link PaginatorDefinition#getOutputToken()} list. * The size of list returned by this method is equal to the size of {@link PaginatorDefinition#getOutputToken()} list. */ protected List<String> fluentGetterMethodsForOutputToken() { return paginatorDefinition.getOutputToken().stream() .map(this::fluentGetterMethodForResponseMember) .collect(Collectors.toList()); } /** * Returns the fluent getter method for a single member in the response. * The returned String includes the '()' after each method name. * * The input member can be a nested String. An example would be StreamDescription.LastEvaluatedShardId * which represents LastEvaluatedShardId member in StreamDescription class. The return value for it * would be "streamDescription().lastEvaluatedShardId()" * * @param member A top level or nested member in response of {@link #c2jOperationName}. */ protected String fluentGetterMethodForResponseMember(String member) { String[] hierarchy = member.split("\\."); if (hierarchy.length < 1) { throw new IllegalArgumentException(String.format("Error when splitting member %s for operation %s", member, c2jOperationName)); } ShapeModel parentShape = operationModel.getOutputShape(); StringBuilder getterMethod = new StringBuilder(); for (String str : hierarchy) { getterMethod.append(".") .append(parentShape.findMemberModelByC2jName(str).getFluentGetterMethodName()) .append("()"); parentShape = parentShape.findMemberModelByC2jName(str).getShape(); } return getterMethod.substring(1); } protected CodeBlock getIteratorLambdaBlock(String resultKey, MemberModel resultKeyModel) { String conditionalStatement = getConditionalStatementforIteratorLambda(resultKey); String fluentGetter = fluentGetterMethodForResponseMember(resultKey); CodeBlock iteratorBlock = null; if (resultKeyModel.isList()) { iteratorBlock = CodeBlock.builder().addStatement("return $L.$L.iterator()", RESPONSE_LITERAL, fluentGetter).build(); } else if (resultKeyModel.isMap()) { iteratorBlock = CodeBlock.builder().addStatement("return $L.$L.entrySet().iterator()", RESPONSE_LITERAL, fluentGetter).build(); } CodeBlock conditionalBlock = CodeBlock.builder() .beginControlFlow("if ($L)", conditionalStatement) .add(iteratorBlock) .endControlFlow() .addStatement("return $T.emptyIterator()", TypeName.get(Collections.class)) .build(); return CodeBlock.builder() .add("$L -> { $L };", RESPONSE_LITERAL, conditionalBlock) .build(); } /** * Returns a conditional statement string that verifies the fluent methods to return result key are not null. * * If resultKey is StreamDescription.LastEvaluatedShardId, output of this method would be * "response != null && response.streamDescription() != null && response.streamDescription().lastEvaluatedShardId() != null" * * @param resultKey A top level or nested member in response of {@link #c2jOperationName}. */ private String getConditionalStatementforIteratorLambda(String resultKey) { String[] hierarchy = resultKey.split("\\."); if (hierarchy.length < 1) { throw new IllegalArgumentException(String.format("Error when splitting member %s for operation %s", resultKey, c2jOperationName)); } String currentFluentMethod = RESPONSE_LITERAL; ShapeModel parentShape = operationModel.getOutputShape(); StringBuilder conditionStatement = new StringBuilder(String.format("%s != null", currentFluentMethod)); for (String str : hierarchy) { currentFluentMethod = String.format("%s.%s()", currentFluentMethod, parentShape.findMemberModelByC2jName(str) .getFluentGetterMethodName()); conditionStatement.append(" && "); conditionStatement.append(String.format("%s != null", currentFluentMethod)); parentShape = parentShape.findMemberModelByC2jName(str).getShape(); } return conditionStatement.toString(); } }
3,398
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/paginators/AsyncResponseClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.paginators; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.Collections; import java.util.Iterator; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import org.reactivestreams.Subscriber; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.service.PaginatorDefinition; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.pagination.async.AsyncPageFetcher; import software.amazon.awssdk.core.pagination.async.PaginatedItemsPublisher; import software.amazon.awssdk.core.pagination.async.ResponsesSubscription; /** * Java poet {@link ClassSpec} to generate the response class for async paginated operations. */ public class AsyncResponseClassSpec extends PaginatorsClassSpec { protected static final String LAST_PAGE_FIELD = "isLastPage"; private static final String SUBSCRIBER = "subscriber"; private static final String SUBSCRIBE_METHOD = "subscribe"; public AsyncResponseClassSpec(IntermediateModel model, String c2jOperationName, PaginatorDefinition paginatorDefinition) { super(model, c2jOperationName, paginatorDefinition); } @Override public TypeSpec poetSpec() { TypeSpec.Builder specBuilder = TypeSpec.classBuilder(className()) .addModifiers(Modifier.PUBLIC) .addAnnotation(PoetUtils.generatedAnnotation()) .addSuperinterface(getAsyncResponseInterface()) .addFields(fields().collect(Collectors.toList())) .addMethod(publicConstructor()) .addMethod(privateConstructor()) .addMethod(subscribeMethod()) .addMethods(getMethodSpecsForResultKeyList()) .addJavadoc(paginationDocs.getDocsForAsyncResponseClass( getAsyncClientInterfaceName())) .addType(nextPageFetcherClass().build()); return specBuilder.build(); } @Override public ClassName className() { return poetExtensions.getResponseClassForPaginatedAsyncOperation(c2jOperationName); } /** * Returns the interface that is implemented by the Paginated Async Response class. */ private TypeName getAsyncResponseInterface() { return ParameterizedTypeName.get(ClassName.get(SdkPublisher.class), responseType()); } /** * @return A Poet {@link ClassName} for the async client interface */ protected ClassName getAsyncClientInterfaceName() { return poetExtensions.getClientClass(model.getMetadata().getAsyncInterface()); } protected Stream<FieldSpec> fields() { return Stream.of(asyncClientInterfaceField(), requestClassField(), asyncPageFetcherField(), lastPageField()); } protected FieldSpec asyncClientInterfaceField() { return FieldSpec.builder(getAsyncClientInterfaceName(), CLIENT_MEMBER, Modifier.PRIVATE, Modifier.FINAL).build(); } private FieldSpec asyncPageFetcherField() { return FieldSpec.builder(AsyncPageFetcher.class, NEXT_PAGE_FETCHER_MEMBER, Modifier.PRIVATE, Modifier.FINAL).build(); } protected FieldSpec lastPageField() { return FieldSpec.builder(boolean.class, LAST_PAGE_FIELD, Modifier.PRIVATE).build(); } protected MethodSpec publicConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(getAsyncClientInterfaceName(), CLIENT_MEMBER) .addParameter(requestType(), REQUEST_MEMBER) .addStatement("this($L, $L, false)", CLIENT_MEMBER, REQUEST_MEMBER) .build(); } protected MethodSpec privateConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(getAsyncClientInterfaceName(), CLIENT_MEMBER) .addParameter(requestType(), REQUEST_MEMBER) .addParameter(boolean.class, LAST_PAGE_FIELD) .addStatement("this.$L = $L", CLIENT_MEMBER, CLIENT_MEMBER) .addStatement("this.$L = $T.applyPaginatorUserAgent($L)", REQUEST_MEMBER, poetExtensions.getUserAgentClass(), REQUEST_MEMBER) .addStatement("this.$L = $L", LAST_PAGE_FIELD, LAST_PAGE_FIELD) .addStatement("this.$L = new $L()", NEXT_PAGE_FETCHER_MEMBER, nextPageFetcherClassName()) .build(); } /** * A {@link MethodSpec} for the subscribe() method which is inherited from the interface. */ private MethodSpec subscribeMethod() { return MethodSpec.methodBuilder(SUBSCRIBE_METHOD) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(ParameterizedTypeName.get(ClassName.get(Subscriber.class), WildcardTypeName.supertypeOf(responseType())), SUBSCRIBER) .addStatement("$1L.onSubscribe($2T.builder().$1L($1L).$3L($4L).build())", SUBSCRIBER, ResponsesSubscription.class, NEXT_PAGE_FETCHER_MEMBER, nextPageFetcherArgument()) .build(); } protected String nextPageFetcherArgument() { return NEXT_PAGE_FETCHER_MEMBER; } /** * Returns iterable of {@link MethodSpec} to generate helper methods for all members * in {@link PaginatorDefinition#getResultKey()}. * * The helper methods return a publisher that can be used to stream over the collection of result keys. * These methods will only be generated if {@link PaginatorDefinition#getResultKey()} is not null and a non-empty list. */ private Iterable<MethodSpec> getMethodSpecsForResultKeyList() { if (paginatorDefinition.getResultKey() != null) { return paginatorDefinition.getResultKey().stream() .map(this::getMethodsSpecForSingleResultKey) .filter(Objects::nonNull) .collect(Collectors.toList()); } return Collections.emptyList(); } /* * Generate a method spec for single element in {@link PaginatorDefinition#getResultKey()} list. * * If the element is "Folders" and its type is "List<FolderMetadata>", generated code looks like: * * public SdkPublisher<FolderMetadata> folders() { * Function<DescribeFolderContentsResponse, Iterator<FolderMetadata>> getIterator = response -> { * if (response != null && response.folders() != null) { * return response.folders().iterator(); * } * return Collections.emptyIterator(); * }; * return PaginatedItemsPublisher.builder().nextPageFetcher(new DescribeFolderContentsResponseFetcher()) .iteratorFunction(getIterator) .isLastPage(isLastPage) .build(); * } */ private MethodSpec getMethodsSpecForSingleResultKey(String resultKey) { MemberModel resultKeyModel = memberModelForResponseMember(resultKey); // TODO: Support other types besides List or Map if (!(resultKeyModel.isList() || resultKeyModel.isMap())) { return null; } TypeName resultKeyType = getTypeForResultKey(resultKey); return MethodSpec.methodBuilder(resultKeyModel.getFluentGetterMethodName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(ParameterizedTypeName.get(ClassName.get(SdkPublisher.class), resultKeyType)) .addCode("$T getIterator = ", ParameterizedTypeName.get(ClassName.get(Function.class), responseType(), ParameterizedTypeName.get(ClassName.get(Iterator.class), resultKeyType))) .addCode(getIteratorLambdaBlock(resultKey, resultKeyModel)) .addCode("\n") .addStatement("return $1T.builder().$2L(new $3L()).iteratorFunction(getIterator).$4L($4L).build()", PaginatedItemsPublisher.class, NEXT_PAGE_FETCHER_MEMBER, nextPageFetcherClassName(), LAST_PAGE_FIELD) .addJavadoc(CodeBlock.builder() .add("Returns a publisher that can be used to get a stream of data. You need to " + "subscribe to the publisher to request the stream of data. The publisher " + "has a helper forEach method that takes in a {@link $T} and then applies " + "that consumer to each response returned by the service.", TypeName.get(Consumer.class)) .build()) .build(); } /**aW * Generates a inner class that implements {@link AsyncPageFetcher}. This is a helper class that can be used * to find if there are more pages in the response and to get the next page if exists. */ protected TypeSpec.Builder nextPageFetcherClass() { return TypeSpec.classBuilder(nextPageFetcherClassName()) .addModifiers(Modifier.PRIVATE) .addSuperinterface(ParameterizedTypeName.get(ClassName.get(AsyncPageFetcher.class), responseType())) .addMethod(MethodSpec.methodBuilder(HAS_NEXT_PAGE_METHOD) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(responseType(), PREVIOUS_PAGE_METHOD_ARGUMENT, Modifier.FINAL) .returns(boolean.class) .addStatement(hasNextPageMethodBody()) .build()) .addMethod(MethodSpec.methodBuilder(NEXT_PAGE_METHOD) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(responseType(), PREVIOUS_PAGE_METHOD_ARGUMENT, Modifier.FINAL) .returns(ParameterizedTypeName.get(ClassName.get(CompletableFuture.class), responseType())) .addCode(nextPageMethodBody()) .build()); } }
3,399