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/main/java/software/amazon/awssdk/codegen/poet/paginators
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/paginators/customizations/SameTokenAsyncResponseClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.customizations; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; 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.service.PaginatorDefinition; import software.amazon.awssdk.codegen.poet.paginators.AsyncResponseClassSpec; import software.amazon.awssdk.core.util.PaginatorUtils; /** * Customized response class spec for async paginated operations that indicate the * last page by returning the same token passed in the request object. * * See Cloudwatch logs GetLogEvents API for example, * https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogEvents.html */ public class SameTokenAsyncResponseClassSpec extends AsyncResponseClassSpec { private static final String LAST_TOKEN_MEMBER = "lastToken"; public SameTokenAsyncResponseClassSpec(IntermediateModel model, String c2jOperationName, PaginatorDefinition paginatorDefinition) { super(model, c2jOperationName, paginatorDefinition); } @Override protected Stream<FieldSpec> fields() { return Stream.of(asyncClientInterfaceField(), requestClassField(), lastPageField()); } @Override 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 = $L", REQUEST_MEMBER, REQUEST_MEMBER) .addStatement("this.$L = $L", LAST_PAGE_FIELD, LAST_PAGE_FIELD) .build(); } @Override protected String nextPageFetcherArgument() { return String.format("new %s()", nextPageFetcherClassName()); } @Override protected TypeSpec.Builder nextPageFetcherClass() { return super.nextPageFetcherClass() .addField(FieldSpec.builder(Object.class, LAST_TOKEN_MEMBER, Modifier.PRIVATE) .build()); } @Override 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) .add("!$1N.$2L.equals($3L)", PREVIOUS_PAGE_METHOD_ARGUMENT, fluentGetterMethodsForOutputToken().get(0), LAST_TOKEN_MEMBER) .build(); } @Override protected CodeBlock nextPageMethodBody() { return CodeBlock.builder() .beginControlFlow("if ($L == null)", PREVIOUS_PAGE_METHOD_ARGUMENT) .addStatement("$L = null", LAST_TOKEN_MEMBER) .addStatement("return $L.$L($L)", CLIENT_MEMBER, operationModel.getMethodName(), REQUEST_MEMBER) .endControlFlow() .addStatement("$1L = $2L.$3L", LAST_TOKEN_MEMBER, PREVIOUS_PAGE_METHOD_ARGUMENT, fluentGetterMethodsForOutputToken().get(0)) .addStatement(codeToGetNextPageIfOldResponseIsNotNull()) .build(); } }
3,400
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/paginators
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/paginators/customizations/SameTokenSyncResponseClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.customizations; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; 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.service.PaginatorDefinition; import software.amazon.awssdk.codegen.poet.paginators.SyncResponseClassSpec; import software.amazon.awssdk.core.util.PaginatorUtils; /** * Customized response class spec for sync paginated operations that indicate the * last page by returning the same token passed in the request object. * * See Cloudwatch logs GetLogEvents API for example, * https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogEvents.html */ public class SameTokenSyncResponseClassSpec extends SyncResponseClassSpec { private static final String LAST_TOKEN_MEMBER = "lastToken"; public SameTokenSyncResponseClassSpec(IntermediateModel model, String c2jOperationName, PaginatorDefinition paginatorDefinition) { super(model, c2jOperationName, paginatorDefinition); } @Override protected Stream<FieldSpec> fields() { return Stream.of(syncClientInterfaceField(), requestClassField()); } @Override 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 = $L", REQUEST_MEMBER, REQUEST_MEMBER) .build(); } @Override protected String nextPageFetcherArgument() { return String.format("new %s()", nextPageFetcherClassName()); } @Override protected TypeSpec.Builder nextPageFetcherClass() { return super.nextPageFetcherClass() .addField(FieldSpec.builder(Object.class, LAST_TOKEN_MEMBER, Modifier.PRIVATE) .build()); } @Override 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) .add("!$1N.$2L.equals($3L)", PREVIOUS_PAGE_METHOD_ARGUMENT, fluentGetterMethodsForOutputToken().get(0), LAST_TOKEN_MEMBER) .build(); } @Override protected CodeBlock nextPageMethodBody() { return CodeBlock.builder() .beginControlFlow("if ($L == null)", PREVIOUS_PAGE_METHOD_ARGUMENT) .addStatement("$L = null", LAST_TOKEN_MEMBER) .addStatement("return $L.$L($L)", CLIENT_MEMBER, operationModel.getMethodName(), REQUEST_MEMBER) .endControlFlow() .addStatement("$1L = $2L.$3L", LAST_TOKEN_MEMBER, PREVIOUS_PAGE_METHOD_ARGUMENT, fluentGetterMethodsForOutputToken().get(0)) .addStatement(codeToGetNextPageIfOldResponseIsNotNull()) .build(); } }
3,401
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth/scheme/AuthSchemeInterceptorSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.auth.scheme; 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 com.squareup.javapoet.TypeVariableName; import com.squareup.javapoet.WildcardTypeName; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.rules.EndpointRulesSpecUtils; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.util.MetricUtils; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.identity.spi.ResolveIdentityRequest; import software.amazon.awssdk.identity.spi.TokenIdentity; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public final class AuthSchemeInterceptorSpec implements ClassSpec { private final AuthSchemeSpecUtils authSchemeSpecUtils; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public AuthSchemeInterceptorSpec(IntermediateModel intermediateModel) { this.authSchemeSpecUtils = new AuthSchemeSpecUtils(intermediateModel); this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(intermediateModel); } @Override public ClassName className() { return authSchemeSpecUtils.authSchemeInterceptor(); } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = PoetUtils.createClassBuilder(className()) .addSuperinterface(ExecutionInterceptor.class) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(SdkInternalApi.class); builder.addField(FieldSpec.builder(Logger.class, "LOG", Modifier.PRIVATE, Modifier.STATIC) .initializer("$T.loggerFor($T.class)", Logger.class, className()) .build()); builder.addMethod(generateBeforeExecution()) .addMethod(generateResolveAuthOptions()) .addMethod(generateSelectAuthScheme()) .addMethod(generateAuthSchemeParams()) .addMethod(generateTrySelectAuthScheme()) .addMethod(generateGetIdentityMetric()); return builder.build(); } private MethodSpec generateBeforeExecution() { MethodSpec.Builder builder = MethodSpec.methodBuilder("beforeExecution") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(Context.BeforeExecution.class, "context") .addParameter(ExecutionAttributes.class, "executionAttributes"); builder.addStatement("$T authOptions = resolveAuthOptions(context, executionAttributes)", listOf(AuthSchemeOption.class)) .addStatement("$T selectedAuthScheme = selectAuthScheme(authOptions, executionAttributes)", wildcardSelectedAuthScheme()) .addStatement("$T.putSelectedAuthScheme(executionAttributes, selectedAuthScheme)", endpointRulesSpecUtils.rulesRuntimeClassName("AuthSchemeUtils")); return builder.build(); } private MethodSpec generateResolveAuthOptions() { MethodSpec.Builder builder = MethodSpec.methodBuilder("resolveAuthOptions") .addModifiers(Modifier.PRIVATE) .returns(listOf(AuthSchemeOption.class)) .addParameter(Context.BeforeExecution.class, "context") .addParameter(ExecutionAttributes.class, "executionAttributes"); builder.addStatement("$1T authSchemeProvider = $2T.isInstanceOf($1T.class, executionAttributes" + ".getAttribute($3T.AUTH_SCHEME_RESOLVER), $4S)", authSchemeSpecUtils.providerInterfaceName(), Validate.class, SdkInternalExecutionAttribute.class, "Expected an instance of " + authSchemeSpecUtils.providerInterfaceName().simpleName()); builder.addStatement("$T params = authSchemeParams(context.request(), executionAttributes)", authSchemeSpecUtils.parametersInterfaceName()); builder.addStatement("return authSchemeProvider.resolveAuthScheme(params)"); return builder.build(); } private MethodSpec generateAuthSchemeParams() { MethodSpec.Builder builder = MethodSpec.methodBuilder("authSchemeParams") .addModifiers(Modifier.PRIVATE) .returns(authSchemeSpecUtils.parametersInterfaceName()) .addParameter(SdkRequest.class, "request") .addParameter(ExecutionAttributes.class, "executionAttributes"); if (!authSchemeSpecUtils.useEndpointBasedAuthProvider()) { builder.addStatement("$T operation = executionAttributes.getAttribute($T.OPERATION_NAME)", String.class, SdkExecutionAttribute.class); if (authSchemeSpecUtils.usesSigV4()) { builder.addStatement("$T region = executionAttributes.getAttribute($T.AWS_REGION)", Region.class, AwsExecutionAttribute.class); builder.addStatement("return $T.builder()" + ".operation(operation)" + ".region(region)" + ".build()", authSchemeSpecUtils.parametersInterfaceName()); } else { builder.addStatement("return $T.builder()" + ".operation(operation)" + ".build()", authSchemeSpecUtils.parametersInterfaceName()); } return builder.build(); } builder.addStatement("$T endpointParams = $T.ruleParams(request, executionAttributes)", endpointRulesSpecUtils.parametersClassName(), endpointRulesSpecUtils.resolverInterceptorName()); builder.addStatement("$1T.Builder builder = $1T.builder()", authSchemeSpecUtils.parametersInterfaceName()); boolean regionIncluded = false; for (String paramName : endpointRulesSpecUtils.parameters().keySet()) { if (!authSchemeSpecUtils.includeParamForProvider(paramName)) { continue; } regionIncluded = regionIncluded || paramName.equalsIgnoreCase("region"); String methodName = endpointRulesSpecUtils.paramMethodName(paramName); builder.addStatement("builder.$1N(endpointParams.$1N())", methodName); } builder.addStatement("$T operation = executionAttributes.getAttribute($T.OPERATION_NAME)", String.class, SdkExecutionAttribute.class); builder.addStatement("builder.operation(operation)"); if (authSchemeSpecUtils.usesSigV4() && !regionIncluded) { builder.addStatement("$T region = executionAttributes.getAttribute($T.AWS_REGION)", Region.class, AwsExecutionAttribute.class); builder.addStatement("builder.region(region)"); } builder.addStatement("return builder.build()"); return builder.build(); } private MethodSpec generateSelectAuthScheme() { MethodSpec.Builder builder = MethodSpec.methodBuilder("selectAuthScheme") .addModifiers(Modifier.PRIVATE) .returns(wildcardSelectedAuthScheme()) .addParameter(listOf(AuthSchemeOption.class), "authOptions") .addParameter(ExecutionAttributes.class, "executionAttributes"); builder.addStatement("$T metricCollector = executionAttributes.getAttribute($T.API_CALL_METRIC_COLLECTOR)", MetricCollector.class, SdkExecutionAttribute.class) .addStatement("$T authSchemes = executionAttributes.getAttribute($T.AUTH_SCHEMES)", mapOf(String.class, wildcardAuthScheme()), SdkInternalExecutionAttribute.class) .addStatement("$T identityProviders = executionAttributes.getAttribute($T.IDENTITY_PROVIDERS)", IdentityProviders.class, SdkInternalExecutionAttribute.class) .addStatement("$T discardedReasons = new $T<>()", listOfStringSuppliers(), ArrayList.class); builder.beginControlFlow("for ($T authOption : authOptions)", AuthSchemeOption.class); { builder.addStatement("$T authScheme = authSchemes.get(authOption.schemeId())", wildcardAuthScheme()) .addStatement("$T selectedAuthScheme = trySelectAuthScheme(authOption, authScheme, identityProviders, " + "discardedReasons, metricCollector)", wildcardSelectedAuthScheme()); builder.beginControlFlow("if (selectedAuthScheme != null)"); { addLogDebugDiscardedOptions(builder); builder.addStatement("return selectedAuthScheme") .endControlFlow(); } // end foreach builder.endControlFlow(); } builder.addStatement("throw $T.builder()" + ".message($S + discardedReasons.stream().map($T::get).collect($T.joining(\", \")))" + ".build()", SdkException.class, "Failed to determine how to authenticate the user: ", Supplier.class, Collectors.class); return builder.build(); } private MethodSpec generateTrySelectAuthScheme() { MethodSpec.Builder builder = MethodSpec.methodBuilder("trySelectAuthScheme") .addModifiers(Modifier.PRIVATE) .returns(namedSelectedAuthScheme()) .addParameter(AuthSchemeOption.class, "authOption") .addParameter(namedAuthScheme(), "authScheme") .addParameter(IdentityProviders.class, "identityProviders") .addParameter(listOfStringSuppliers(), "discardedReasons") .addParameter(MetricCollector.class, "metricCollector") .addTypeVariable(TypeVariableName.get("T", Identity.class)); builder.beginControlFlow("if (authScheme == null)"); { builder.addStatement("discardedReasons.add(() -> String.format($S, authOption.schemeId()))", "'%s' is not enabled for this request.") .addStatement("return null") .endControlFlow(); } builder.addStatement("$T identityProvider = authScheme.identityProvider(identityProviders)", namedIdentityProvider()); builder.beginControlFlow("if (identityProvider == null)"); { builder.addStatement("discardedReasons.add(() -> String.format($S, authOption.schemeId()))", "'%s' does not have an identity provider configured.") .addStatement("return null") .endControlFlow(); } builder.addStatement("$T.Builder identityRequestBuilder = $T.builder()", ResolveIdentityRequest.class, ResolveIdentityRequest.class); builder.addStatement("authOption.forEachIdentityProperty(identityRequestBuilder::putProperty)"); builder.addStatement("$T identity", namedIdentityFuture()); builder.addStatement("$T metric = getIdentityMetric(identityProvider)", durationSdkMetric()); builder.beginControlFlow("if (metric == null)") .addStatement("identity = identityProvider.resolveIdentity(identityRequestBuilder.build())") .nextControlFlow("else") .addStatement("identity = $T.reportDuration(" + "() -> identityProvider.resolveIdentity(identityRequestBuilder.build()), metricCollector, metric)", MetricUtils.class) .endControlFlow(); builder.addStatement("return new $T<>(identity, authScheme.signer(), authOption)", SelectedAuthScheme.class); return builder.build(); } private MethodSpec generateGetIdentityMetric() { MethodSpec.Builder builder = MethodSpec.methodBuilder("getIdentityMetric") .addModifiers(Modifier.PRIVATE) .returns(durationSdkMetric()) .addParameter(wildcardIdentityProvider(), "identityProvider"); builder.addStatement("Class<?> identityType = identityProvider.identityType()") .beginControlFlow("if (identityType == $T.class)", AwsCredentialsIdentity.class) .addStatement("return $T.CREDENTIALS_FETCH_DURATION", CoreMetric.class) .endControlFlow() .beginControlFlow("if (identityType == $T.class)", TokenIdentity.class) .addStatement("return $T.TOKEN_FETCH_DURATION", CoreMetric.class) .endControlFlow() .addStatement("return null"); return builder.build(); } private void addLogDebugDiscardedOptions(MethodSpec.Builder builder) { builder.beginControlFlow("if (!discardedReasons.isEmpty())"); { builder.addStatement("LOG.debug(() -> String.format(\"%s auth will be used, discarded: '%s'\", " + "authOption.schemeId(), " + "discardedReasons.stream().map($T::get).collect($T.joining(\", \"))))", Supplier.class, Collectors.class) .endControlFlow(); } } // IdentityProvider<T> private TypeName namedIdentityProvider() { return ParameterizedTypeName.get(ClassName.get(IdentityProvider.class), TypeVariableName.get("T")); } // IdentityProvider<?> private TypeName wildcardIdentityProvider() { return ParameterizedTypeName.get(ClassName.get(IdentityProvider.class), WildcardTypeName.subtypeOf(Object.class)); } // CompletableFuture<? extends T> private TypeName namedIdentityFuture() { return ParameterizedTypeName.get(ClassName.get(CompletableFuture.class), WildcardTypeName.subtypeOf(TypeVariableName.get("T"))); } // AuthScheme<T> private TypeName namedAuthScheme() { return ParameterizedTypeName.get(ClassName.get(AuthScheme.class), TypeVariableName.get("T", Identity.class)); } // AuthScheme<?> private TypeName wildcardAuthScheme() { return ParameterizedTypeName.get(ClassName.get(AuthScheme.class), WildcardTypeName.subtypeOf(Object.class)); } // SelectedAuthScheme<T> private TypeName namedSelectedAuthScheme() { return ParameterizedTypeName.get(ClassName.get(SelectedAuthScheme.class), TypeVariableName.get("T", Identity.class)); } // SelectedAuthScheme<?> private TypeName wildcardSelectedAuthScheme() { return ParameterizedTypeName.get(ClassName.get(SelectedAuthScheme.class), WildcardTypeName.subtypeOf(Identity.class)); } // List<Supplier<String>> private TypeName listOfStringSuppliers() { return listOf(ParameterizedTypeName.get(Supplier.class, String.class)); } // Map<key, value> private TypeName mapOf(Object keyType, Object valueType) { return ParameterizedTypeName.get(ClassName.get(Map.class), toTypeName(keyType), toTypeName(valueType)); } // List<values> private TypeName listOf(Object valueType) { return ParameterizedTypeName.get(ClassName.get(List.class), toTypeName(valueType)); } // SdkMetric<Duration> private ParameterizedTypeName durationSdkMetric() { return ParameterizedTypeName.get(ClassName.get(SdkMetric.class), toTypeName(Duration.class)); } private TypeName toTypeName(Object valueType) { TypeName result; if (valueType instanceof Class<?>) { result = ClassName.get((Class<?>) valueType); } else if (valueType instanceof TypeName) { result = (TypeName) valueType; } else { throw new IllegalArgumentException("Don't know how to convert " + valueType + " to TypeName"); } return result; } }
3,402
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth/scheme/AuthSchemeParamsSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.auth.scheme; 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.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Map; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.rules.EndpointRulesSpecUtils; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; public final class AuthSchemeParamsSpec implements ClassSpec { private final IntermediateModel intermediateModel; private final AuthSchemeSpecUtils authSchemeSpecUtils; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public AuthSchemeParamsSpec(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; this.authSchemeSpecUtils = new AuthSchemeSpecUtils(intermediateModel); this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(intermediateModel); } @Override public ClassName className() { return authSchemeSpecUtils.parametersInterfaceName(); } @Override public TypeSpec poetSpec() { TypeSpec.Builder b = PoetUtils.createInterfaceBuilder(className()) .addSuperinterface(toCopyableBuilderInterface()) .addModifiers(Modifier.PUBLIC) .addAnnotation(SdkPublicApi.class) .addJavadoc(interfaceJavadoc()) .addMethod(builderMethod()) .addType(builderInterfaceSpec()); addAccessorMethods(b); addToBuilder(b); return b.build(); } private CodeBlock interfaceJavadoc() { CodeBlock.Builder b = CodeBlock.builder(); b.add("The parameters object used to resolve the auth schemes for the $N service.", intermediateModel.getMetadata().getServiceName()); return b.build(); } private MethodSpec builderMethod() { return MethodSpec.methodBuilder("builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(authSchemeSpecUtils.parametersInterfaceBuilderInterfaceName()) .addStatement("return $T.builder()", authSchemeSpecUtils.parametersDefaultImplName()) .addJavadoc("Get a new builder for creating a {@link $T}.", authSchemeSpecUtils.parametersInterfaceName()) .build(); } private TypeSpec builderInterfaceSpec() { TypeSpec.Builder b = TypeSpec.interfaceBuilder(authSchemeSpecUtils.parametersInterfaceBuilderInterfaceName()) .addSuperinterface(copyableBuilderInterface()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc("A builder for a {@link $T}.", authSchemeSpecUtils.parametersInterfaceName()); addBuilderSetterMethods(b); b.addMethod(MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(className()) .addJavadoc("Returns a {@link $T} object that is created from the properties that have been set " + "on the builder.", authSchemeSpecUtils.parametersInterfaceName()) .build()); return b.build(); } private void addAccessorMethods(TypeSpec.Builder b) { b.addMethod(MethodSpec.methodBuilder("operation") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(String.class) .addJavadoc("Returns the operation for which to resolve the auth scheme.") .build()); if (authSchemeSpecUtils.usesSigV4()) { b.addMethod(MethodSpec.methodBuilder("region") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(Region.class) .addJavadoc("Returns the region. The region parameter may be used with the $S auth scheme.", AwsV4AuthScheme.SCHEME_ID) .build()); } if (authSchemeSpecUtils.generateEndpointBasedParams()) { parameters().forEach((name, model) -> { if (authSchemeSpecUtils.includeParam(name)) { MethodSpec accessor = endpointRulesSpecUtils.parameterInterfaceAccessorMethod(name, model); if (model.getDocumentation() != null) { accessor = accessor.toBuilder().addJavadoc(model.getDocumentation()).build(); } b.addMethod(accessor); } }); } } private void addToBuilder(TypeSpec.Builder b) { ClassName builderClassName = authSchemeSpecUtils.parametersInterfaceBuilderInterfaceName(); b.addMethod(MethodSpec.methodBuilder("toBuilder") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(builderClassName) .addJavadoc("Returns a {@link $T} to customize the parameters.", builderClassName) .build()); } private void addBuilderSetterMethods(TypeSpec.Builder b) { b.addMethod(MethodSpec.methodBuilder("operation") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addParameter(ParameterSpec.builder(String.class, "operation").build()) .returns(authSchemeSpecUtils.parametersInterfaceBuilderInterfaceName()) .addJavadoc("Set the operation for which to resolve the auth scheme.") .build()); if (authSchemeSpecUtils.usesSigV4()) { b.addMethod(MethodSpec.methodBuilder("region") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addParameter(ParameterSpec.builder(Region.class, "region").build()) .returns(authSchemeSpecUtils.parametersInterfaceBuilderInterfaceName()) .addJavadoc("Set the region. The region parameter may be used with the $S auth scheme.", AwsV4AuthScheme.SCHEME_ID) .build()); } if (authSchemeSpecUtils.generateEndpointBasedParams()) { parameters().forEach((name, model) -> { if (authSchemeSpecUtils.includeParam(name)) { ClassName parametersInterfaceName = authSchemeSpecUtils.parametersInterfaceName(); MethodSpec setter = endpointRulesSpecUtils .parameterBuilderSetterMethodDeclaration(parametersInterfaceName, name, model); if (model.getDocumentation() != null) { setter = setter.toBuilder().addJavadoc(model.getDocumentation()).build(); } b.addMethod(setter); } }); } } private Map<String, ParameterModel> parameters() { return intermediateModel.getEndpointRuleSetModel().getParameters(); } private TypeName toCopyableBuilderInterface() { return ParameterizedTypeName.get(ClassName.get(ToCopyableBuilder.class), className().nestedClass("Builder"), className()); } private TypeName copyableBuilderInterface() { return ParameterizedTypeName.get(ClassName.get(CopyableBuilder.class), className().nestedClass("Builder"), className()); } }
3,403
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth/scheme/AuthSchemeCodegenMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.auth.scheme; import com.squareup.javapoet.MethodSpec; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.BiConsumer; import software.amazon.awssdk.codegen.model.service.AuthType; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.scheme.BearerAuthScheme; import software.amazon.awssdk.http.auth.scheme.NoAuthAuthScheme; import software.amazon.awssdk.utils.Validate; public final class AuthSchemeCodegenMetadata { static final AuthSchemeCodegenMetadata SIGV4 = builder() .schemeId(AwsV4AuthScheme.SCHEME_ID) .authSchemeClass(AwsV4AuthScheme.class) .addProperty(SignerPropertyValueProvider.builder() .containingClass(AwsV4HttpSigner.class) .fieldName("SERVICE_SIGNING_NAME") .valueEmitter((spec, utils) -> spec.addCode("$S", utils.signingName())) .build()) .addProperty(SignerPropertyValueProvider.builder() .containingClass(AwsV4HttpSigner.class) .fieldName("REGION_NAME") .valueEmitter((spec, utils) -> spec.addCode("$L", "params.region().id()")) .build()) .build(); static final AuthSchemeCodegenMetadata SIGV4_UNSIGNED_BODY = SIGV4.toBuilder() .addProperty(SignerPropertyValueProvider.builder() .containingClass(AwsV4HttpSigner.class) .fieldName("PAYLOAD_SIGNING_ENABLED") .valueEmitter((spec, utils) -> spec.addCode("$L", false)) .build()) .build(); static final AuthSchemeCodegenMetadata S3 = SIGV4.toBuilder() .addProperty(SignerPropertyValueProvider.builder() .containingClass(AwsV4HttpSigner.class) .fieldName("DOUBLE_URL_ENCODE") .valueEmitter((spec, utils) -> spec.addCode("$L", "false")) .build()) .addProperty(SignerPropertyValueProvider.builder() .containingClass(AwsV4HttpSigner.class) .fieldName("NORMALIZE_PATH") .valueEmitter((spec, utils) -> spec.addCode("$L", "false")) .build()) .addProperty(SignerPropertyValueProvider.builder() .containingClass(AwsV4HttpSigner.class) .fieldName("PAYLOAD_SIGNING_ENABLED") .valueEmitter((spec, utils) -> spec.addCode("$L", false)) .build()) .build(); static final AuthSchemeCodegenMetadata S3V4 = SIGV4.toBuilder() .addProperty(SignerPropertyValueProvider.builder() .containingClass(AwsV4HttpSigner.class) .fieldName("DOUBLE_URL_ENCODE") .valueEmitter((spec, utils) -> spec.addCode("$L", "false")) .build()) .addProperty(SignerPropertyValueProvider.builder() .containingClass(AwsV4HttpSigner.class) .fieldName("NORMALIZE_PATH") .valueEmitter((spec, utils) -> spec.addCode("$L", "false")) .build()) .build(); static final AuthSchemeCodegenMetadata BEARER = builder() .schemeId(BearerAuthScheme.SCHEME_ID) .authSchemeClass(BearerAuthScheme.class) .build(); static final AuthSchemeCodegenMetadata NO_AUTH = builder() .schemeId(NoAuthAuthScheme.SCHEME_ID) .authSchemeClass(NoAuthAuthScheme.class) .build(); private final String schemeId; private final List<SignerPropertyValueProvider> properties; private final Class<?> authSchemeClass; private AuthSchemeCodegenMetadata(Builder builder) { this.schemeId = Validate.paramNotNull(builder.schemeId, "schemeId"); this.properties = Collections.unmodifiableList(Validate.paramNotNull(builder.properties, "properties")); this.authSchemeClass = Validate.paramNotNull(builder.authSchemeClass, "authSchemeClass"); } public String schemeId() { return schemeId; } public Class<?> authSchemeClass() { return authSchemeClass; } public List<SignerPropertyValueProvider> properties() { return properties; } public Builder toBuilder() { return new Builder(this); } private static Builder builder() { return new Builder(); } public static AuthSchemeCodegenMetadata fromAuthType(AuthType type) { switch (type) { case BEARER: return BEARER; case NONE: return NO_AUTH; case V4: return SIGV4; case V4_UNSIGNED_BODY: return SIGV4_UNSIGNED_BODY; case S3: return S3; case S3V4: return S3V4; default: throw new IllegalArgumentException("Unknown auth type: " + type); } } private static class Builder { private String schemeId; private List<SignerPropertyValueProvider> properties = new ArrayList<>(); private Class<?> authSchemeClass; Builder() { } Builder(AuthSchemeCodegenMetadata other) { this.schemeId = other.schemeId; this.properties.addAll(other.properties); this.authSchemeClass = other.authSchemeClass; } public Builder schemeId(String schemeId) { this.schemeId = schemeId; return this; } public Builder addProperty(SignerPropertyValueProvider property) { this.properties.add(property); return this; } public Builder authSchemeClass(Class<?> authSchemeClass) { this.authSchemeClass = authSchemeClass; return this; } public AuthSchemeCodegenMetadata build() { return new AuthSchemeCodegenMetadata(this); } } static class SignerPropertyValueProvider { private final Class<?> containingClass; private final String fieldName; private final BiConsumer<MethodSpec.Builder, AuthSchemeSpecUtils> valueEmitter; SignerPropertyValueProvider(Builder builder) { this.containingClass = Validate.paramNotNull(builder.containingClass, "containingClass"); this.valueEmitter = Validate.paramNotNull(builder.valueEmitter, "valueEmitter"); this.fieldName = Validate.paramNotNull(builder.fieldName, "fieldName"); } public Class<?> containingClass() { return containingClass; } public String fieldName() { return fieldName; } public void emitValue(MethodSpec.Builder spec, AuthSchemeSpecUtils utils) { valueEmitter.accept(spec, utils); } private static Builder builder() { return new Builder(); } static class Builder { private Class<?> containingClass; private String fieldName; private BiConsumer<MethodSpec.Builder, AuthSchemeSpecUtils> valueEmitter; public Builder containingClass(Class<?> containingClass) { this.containingClass = containingClass; return this; } public Builder fieldName(String fieldName) { this.fieldName = fieldName; return this; } public Builder valueEmitter(BiConsumer<MethodSpec.Builder, AuthSchemeSpecUtils> valueEmitter) { this.valueEmitter = valueEmitter; return this; } public SignerPropertyValueProvider build() { return new SignerPropertyValueProvider(this); } } } }
3,404
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth/scheme/EndpointBasedAuthSchemeProviderSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.auth.scheme; 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.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.endpoints.AwsEndpointAttribute; import software.amazon.awssdk.awscore.endpoints.authscheme.EndpointAuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4AuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4aAuthScheme; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.rules.EndpointRulesSpecUtils; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4aAuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.http.auth.aws.signer.RegionSet; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Validate; public class EndpointBasedAuthSchemeProviderSpec implements ClassSpec { private final AuthSchemeSpecUtils authSchemeSpecUtils; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public EndpointBasedAuthSchemeProviderSpec(IntermediateModel intermediateModel) { this.authSchemeSpecUtils = new AuthSchemeSpecUtils(intermediateModel); this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(intermediateModel); } @Override public ClassName className() { return authSchemeSpecUtils.defaultAuthSchemeProviderName(); } @Override public TypeSpec poetSpec() { return PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(SdkInternalApi.class) .addSuperinterface(authSchemeSpecUtils.providerInterfaceName()) .addMethod(constructor()) .addField(defaultInstance()) .addField(modeledResolverInstance()) .addField(endpointDelegateInstance()) .addMethod(createMethod()) .addMethod(resolveAuthSchemeMethod()) .build(); } private MethodSpec constructor() { return MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build(); } private FieldSpec defaultInstance() { return FieldSpec.builder(className(), "DEFAULT") .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("new $T()", className()) .build(); } private FieldSpec endpointDelegateInstance() { return FieldSpec.builder(endpointRulesSpecUtils.providerInterfaceName(), "DELEGATE") .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("$T.defaultProvider()", endpointRulesSpecUtils.providerInterfaceName()) .build(); } private FieldSpec modeledResolverInstance() { return FieldSpec.builder(authSchemeSpecUtils.providerInterfaceName(), "MODELED_RESOLVER") .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("$T.create()", authSchemeSpecUtils.modeledAuthSchemeProviderName()) .build(); } private MethodSpec createMethod() { return MethodSpec.methodBuilder("create") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(authSchemeSpecUtils.providerInterfaceName()) .addStatement("return DEFAULT") .build(); } private MethodSpec resolveAuthSchemeMethod() { MethodSpec.Builder spec = MethodSpec.methodBuilder("resolveAuthScheme") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(authSchemeSpecUtils.resolverReturnType()) .addParameter(authSchemeSpecUtils.parametersInterfaceName(), "params"); spec.addCode("$1T endpointParameters = $1T.builder()\n$>", endpointRulesSpecUtils.parametersClassName()); parameters().forEach((name, model) -> { if (authSchemeSpecUtils.includeParamForProvider(name)) { spec.addCode(".$1L(params.$1L())\n", endpointRulesSpecUtils.paramMethodName(name)); } }); spec.addStatement(".build()"); spec.addStatement("$T endpoint = $T.joinLikeSync(DELEGATE.resolveEndpoint(endpointParameters))", Endpoint.class, CompletableFutureUtils.class); spec.addStatement("$T authSchemes = endpoint.attribute($T.AUTH_SCHEMES)", ParameterizedTypeName.get(List.class, EndpointAuthScheme.class), AwsEndpointAttribute.class); spec.beginControlFlow("if (authSchemes == null)"); spec.addStatement("return MODELED_RESOLVER.resolveAuthScheme(params)"); spec.endControlFlow(); spec.addStatement("$T options = new $T<>()", ParameterizedTypeName.get(List.class, AuthSchemeOption.class), TypeName.get(ArrayList.class)); spec.beginControlFlow("for ($T authScheme : authSchemes)", EndpointAuthScheme.class); addAuthSchemeSwitch(spec); spec.endControlFlow(); return spec.addStatement("return $T.unmodifiableList(options)", Collections.class) .build(); } private void addAuthSchemeSwitch(MethodSpec.Builder spec) { spec.addStatement("$T name = authScheme.name()", String.class); spec.beginControlFlow("switch(name)"); addAuthSchemeSwitchSigV4Case(spec); addAuthSchemeSwitchSigV4aCase(spec); addAuthSchemeSwitchDefaultCase(spec); spec.endControlFlow(); } private void addAuthSchemeSwitchSigV4Case(MethodSpec.Builder spec) { spec.addCode("case $S:", "sigv4"); spec.addStatement("$T sigv4AuthScheme = $T.isInstanceOf($T.class, authScheme, $S, authScheme.getClass().getName())", SigV4AuthScheme.class, Validate.class, SigV4AuthScheme.class, "Expecting auth scheme of class SigV4AuthScheme, got instead object of class %s"); spec.addCode("options.add($T.builder().schemeId($S)", AuthSchemeOption.class, AwsV4AuthScheme.SCHEME_ID) .addCode(".putSignerProperty($T.SERVICE_SIGNING_NAME, sigv4AuthScheme.signingName())", AwsV4HttpSigner.class) .addCode(".putSignerProperty($T.REGION_NAME, sigv4AuthScheme.signingRegion())", AwsV4HttpSigner.class) .addCode(".putSignerProperty($T.DOUBLE_URL_ENCODE, !sigv4AuthScheme.disableDoubleEncoding())", AwsV4HttpSigner.class) .addCode(".build());"); spec.addStatement("break"); } private void addAuthSchemeSwitchSigV4aCase(MethodSpec.Builder spec) { spec.addCode("case $S:", "sigv4a"); spec.addStatement("$T sigv4aAuthScheme = $T.isInstanceOf($T.class, authScheme, $S, authScheme.getClass().getName())", SigV4aAuthScheme.class, Validate.class, SigV4aAuthScheme.class, "Expecting auth scheme of class SigV4AuthScheme, got instead object of class %s"); spec.addStatement("$1T regionSet = $1T.create(sigv4aAuthScheme.signingRegionSet())", RegionSet.class); spec.addCode("options.add($T.builder().schemeId($S)", AuthSchemeOption.class, AwsV4aAuthScheme.SCHEME_ID) .addCode(".putSignerProperty($T.SERVICE_SIGNING_NAME, sigv4aAuthScheme.signingName())", AwsV4aHttpSigner.class) .addCode(".putSignerProperty($T.REGION_SET, regionSet)", AwsV4aHttpSigner.class) .addCode(".putSignerProperty($T.DOUBLE_URL_ENCODE, !sigv4aAuthScheme.disableDoubleEncoding())", AwsV4aHttpSigner.class) .addCode(".build());"); spec.addStatement("break"); } private void addAuthSchemeSwitchDefaultCase(MethodSpec.Builder spec) { spec.addCode("default:"); spec.addStatement("throw new $T($S + name)", IllegalArgumentException.class, "Unknown auth scheme: "); } private Map<String, ParameterModel> parameters() { return endpointRulesSpecUtils.parameters(); } }
3,405
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth/scheme/ModelBasedAuthSchemeProviderSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.auth.scheme; import static software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeCodegenMetadata.SignerPropertyValueProvider; import static software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeCodegenMetadata.fromAuthType; 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.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.AuthType; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; public class ModelBasedAuthSchemeProviderSpec implements ClassSpec { private final AuthSchemeSpecUtils authSchemeSpecUtils; public ModelBasedAuthSchemeProviderSpec(IntermediateModel intermediateModel) { this.authSchemeSpecUtils = new AuthSchemeSpecUtils(intermediateModel); } @Override public ClassName className() { if (authSchemeSpecUtils.useEndpointBasedAuthProvider()) { return authSchemeSpecUtils.modeledAuthSchemeProviderName(); } return authSchemeSpecUtils.defaultAuthSchemeProviderName(); } @Override public TypeSpec poetSpec() { return PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(SdkInternalApi.class) .addSuperinterface(authSchemeSpecUtils.providerInterfaceName()) .addMethod(constructor()) .addField(defaultInstance()) .addMethod(createMethod()) .addMethod(resolveAuthSchemeMethod()) .build(); } private FieldSpec defaultInstance() { return FieldSpec.builder(className(), "DEFAULT") .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("new $T()", className()) .build(); } private MethodSpec constructor() { return MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build(); } private MethodSpec createMethod() { return MethodSpec.methodBuilder("create") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(className()) .addStatement("return DEFAULT") .build(); } private MethodSpec resolveAuthSchemeMethod() { MethodSpec.Builder spec = MethodSpec.methodBuilder("resolveAuthScheme") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(authSchemeSpecUtils.resolverReturnType()) .addParameter(authSchemeSpecUtils.parametersInterfaceName(), "params"); spec.addStatement("$T options = new $T<>()", ParameterizedTypeName.get(List.class, AuthSchemeOption.class), TypeName.get(ArrayList.class)); Map<List<String>, List<AuthType>> operationsToAuthType = authSchemeSpecUtils.operationsToAuthType(); // All the operations share the same set of auth schemes, no need to create a switch statement. if (operationsToAuthType.size() == 1) { List<AuthType> types = operationsToAuthType.get(Collections.emptyList()); for (AuthType authType : types) { addAuthTypeProperties(spec, authType); } return spec.addStatement("return $T.unmodifiableList(options)", Collections.class) .build(); } spec.beginControlFlow("switch(params.operation())"); operationsToAuthType.forEach((ops, schemes) -> { if (!ops.isEmpty()) { addCasesForOperations(spec, ops, schemes); } }); addCasesForOperations(spec, Collections.emptyList(), operationsToAuthType.get(Collections.emptyList())); spec.endControlFlow(); return spec.addStatement("return $T.unmodifiableList(options)", Collections.class) .build(); } private void addCasesForOperations(MethodSpec.Builder spec, List<String> operations, List<AuthType> schemes) { if (operations.isEmpty()) { spec.addCode("default:"); } else { for (String name : operations) { spec.addCode("case $S:", name); } } for (AuthType authType : schemes) { addAuthTypeProperties(spec, authType); } spec.addStatement("break"); } public void addAuthTypeProperties(MethodSpec.Builder spec, AuthType authType) { AuthSchemeCodegenMetadata metadata = fromAuthType(authType); spec.addCode("options.add($T.builder().schemeId($S)", AuthSchemeOption.class, metadata.schemeId()); for (SignerPropertyValueProvider property : metadata.properties()) { spec.addCode(".putSignerProperty($T.$N, ", property.containingClass(), property.fieldName()); property.emitValue(spec, authSchemeSpecUtils); spec.addCode(")"); } spec.addCode(".build());\n"); } }
3,406
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth/scheme/AuthSchemeProviderSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.auth.scheme; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; 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.SdkPublicApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeProvider; public class AuthSchemeProviderSpec implements ClassSpec { private final IntermediateModel intermediateModel; private final AuthSchemeSpecUtils authSchemeSpecUtils; public AuthSchemeProviderSpec(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; this.authSchemeSpecUtils = new AuthSchemeSpecUtils(intermediateModel); } @Override public ClassName className() { return authSchemeSpecUtils.providerInterfaceName(); } @Override public TypeSpec poetSpec() { return PoetUtils.createInterfaceBuilder(className()) .addSuperinterface(AuthSchemeProvider.class) .addModifiers(Modifier.PUBLIC) .addAnnotation(SdkPublicApi.class) .addJavadoc(interfaceJavadoc()) .addMethod(resolveAuthSchemeMethod()) .addMethod(resolveAuthSchemeConsumerBuilderMethod()) .addMethod(defaultProviderMethod()) .build(); } private MethodSpec resolveAuthSchemeMethod() { MethodSpec.Builder b = MethodSpec.methodBuilder("resolveAuthScheme"); b.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT); b.addParameter(authSchemeSpecUtils.parametersInterfaceName(), "authSchemeParams"); b.returns(authSchemeSpecUtils.resolverReturnType()); b.addJavadoc(resolveMethodJavadoc()); return b.build(); } private MethodSpec resolveAuthSchemeConsumerBuilderMethod() { ClassName parametersInterface = authSchemeSpecUtils.parametersInterfaceName(); ClassName parametersBuilderInterface = parametersInterface.nestedClass("Builder"); TypeName consumerType = ParameterizedTypeName.get(ClassName.get(Consumer.class), parametersBuilderInterface); MethodSpec.Builder b = MethodSpec.methodBuilder("resolveAuthScheme"); b.addModifiers(Modifier.PUBLIC, Modifier.DEFAULT); b.addParameter(consumerType, "consumer"); b.returns(authSchemeSpecUtils.resolverReturnType()); b.addJavadoc(resolveMethodJavadoc()); b.addStatement("$T builder = $T.builder()", parametersBuilderInterface, parametersInterface); b.addStatement("consumer.accept(builder)"); b.addStatement("return resolveAuthScheme(builder.build())"); return b.build(); } private MethodSpec defaultProviderMethod() { return MethodSpec.methodBuilder("defaultProvider") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(className()) .addJavadoc("Get the default auth scheme provider.") .addStatement("return $T.create()", authSchemeSpecUtils.defaultAuthSchemeProviderName()) .build(); } private CodeBlock interfaceJavadoc() { CodeBlock.Builder b = CodeBlock.builder(); b.add("An auth scheme provider for $N service. The auth scheme provider takes a set of parameters using {@link $T}, and " + "resolves a list of {@link $T} based on the given parameters.", intermediateModel.getMetadata().getServiceName(), authSchemeSpecUtils.parametersInterfaceName(), AuthSchemeOption.class); return b.build(); } private CodeBlock resolveMethodJavadoc() { CodeBlock.Builder b = CodeBlock.builder(); b.add("Resolve the auth schemes based on the given set of parameters."); return b.build(); } }
3,407
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth/scheme/AuthSchemeSpecUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.auth.scheme; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.service.AuthType; import software.amazon.awssdk.codegen.utils.AuthUtils; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4aAuthScheme; import software.amazon.awssdk.http.auth.scheme.NoAuthAuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; public final class AuthSchemeSpecUtils { private static final Set<String> DEFAULT_AUTH_SCHEME_PARAMS = Collections.unmodifiableSet(setOf("region", "operation")); private final IntermediateModel intermediateModel; private final boolean useSraAuth; private final Set<String> allowedEndpointAuthSchemeParams; private final boolean allowedEndpointAuthSchemeParamsConfigured; public AuthSchemeSpecUtils(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; CustomizationConfig customization = intermediateModel.getCustomizationConfig(); this.useSraAuth = customization.useSraAuth(); if (customization.getAllowedEndpointAuthSchemeParamsConfigured()) { this.allowedEndpointAuthSchemeParams = Collections.unmodifiableSet( new HashSet<>(customization.getAllowedEndpointAuthSchemeParams())); this.allowedEndpointAuthSchemeParamsConfigured = true; } else { this.allowedEndpointAuthSchemeParams = Collections.emptySet(); this.allowedEndpointAuthSchemeParamsConfigured = false; } } public boolean useSraAuth() { return useSraAuth; } private String basePackage() { return intermediateModel.getMetadata().getFullAuthSchemePackageName(); } private String internalPackage() { return intermediateModel.getMetadata().getFullInternalAuthSchemePackageName(); } public ClassName parametersInterfaceName() { return ClassName.get(basePackage(), intermediateModel.getMetadata().getServiceName() + "AuthSchemeParams"); } public ClassName parametersInterfaceBuilderInterfaceName() { return parametersInterfaceName().nestedClass("Builder"); } public ClassName parametersDefaultImplName() { return ClassName.get(internalPackage(), "Default" + parametersInterfaceName().simpleName()); } public ClassName parametersDefaultBuilderImplName() { return ClassName.get(internalPackage(), "Default" + parametersInterfaceName().simpleName()); } public ClassName providerInterfaceName() { return ClassName.get(basePackage(), intermediateModel.getMetadata().getServiceName() + "AuthSchemeProvider"); } public ClassName defaultAuthSchemeProviderName() { return ClassName.get(internalPackage(), "Default" + providerInterfaceName().simpleName()); } public ClassName modeledAuthSchemeProviderName() { return ClassName.get(internalPackage(), "Modeled" + providerInterfaceName().simpleName()); } public ClassName authSchemeInterceptor() { return ClassName.get(internalPackage(), intermediateModel.getMetadata().getServiceName() + "AuthSchemeInterceptor"); } public TypeName resolverReturnType() { return ParameterizedTypeName.get(List.class, AuthSchemeOption.class); } public boolean usesSigV4() { return AuthUtils.usesAwsAuth(intermediateModel); } public boolean useEndpointBasedAuthProvider() { // Endpoint based auth provider is gated using the same setting that enables the use of auth scheme params. One does // not make sense without the other so there's no much point on creating another setting if both have to be at the same // time enabled or disabled. return generateEndpointBasedParams(); } public String paramMethodName(String name) { return intermediateModel.getNamingStrategy().getVariableName(name); } public boolean generateEndpointBasedParams() { return intermediateModel.getCustomizationConfig().isEnableEndpointAuthSchemeParams(); } public boolean includeParam(String name) { if (allowedEndpointAuthSchemeParamsConfigured) { return allowedEndpointAuthSchemeParams.contains(name); } // If no explicit allowed endpoint auth scheme params are configured then by default we include all of them except the // ones already defined by default. return !DEFAULT_AUTH_SCHEME_PARAMS.contains(name.toLowerCase(Locale.US)); } public boolean includeParamForProvider(String name) { if (allowedEndpointAuthSchemeParamsConfigured) { if (DEFAULT_AUTH_SCHEME_PARAMS.contains(name.toLowerCase(Locale.US))) { return true; } return allowedEndpointAuthSchemeParams.contains(name); } return true; } public String serviceName() { return intermediateModel.getMetadata().getServiceName(); } public String signingName() { return intermediateModel.getMetadata().getSigningName(); } public Map<List<String>, List<AuthType>> operationsToAuthType() { Map<List<AuthType>, List<String>> authSchemesToOperations = intermediateModel.getOperations() .entrySet() .stream() .filter(kvp -> !kvp.getValue().getAuth().isEmpty()) .collect(Collectors.groupingBy(kvp -> kvp.getValue().getAuth(), Collectors.mapping(Map.Entry::getKey, Collectors.toList()))); Map<List<String>, List<AuthType>> operationsToAuthType = authSchemesToOperations .entrySet() .stream() .sorted(Comparator.comparing(left -> left.getValue().get(0))) .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey, (a, b) -> b, LinkedHashMap::new)); List<AuthType> serviceDefaults = serviceDefaultAuthTypes(); // Get the list of operations that share the same auth schemes as the system defaults and remove it from the result. We // will take care of all of these in the fallback `default` case. List<String> operationsWithDefaults = authSchemesToOperations.remove(serviceDefaults); operationsToAuthType.remove(operationsWithDefaults); operationsToAuthType.put(Collections.emptyList(), serviceDefaults); return operationsToAuthType; } public List<AuthType> serviceDefaultAuthTypes() { List<AuthType> modeled = intermediateModel.getMetadata().getAuth(); if (!modeled.isEmpty()) { return modeled; } return Collections.singletonList(intermediateModel.getMetadata().getAuthType()); } public Set<Class<?>> allServiceConcreteAuthSchemeClasses() { Set<Class<?>> result = Stream.concat(intermediateModel.getOperations() .values() .stream() .map(OperationModel::getAuth) .flatMap(List::stream), intermediateModel.getMetadata().getAuth().stream()) .map(AuthSchemeCodegenMetadata::fromAuthType) .map(AuthSchemeCodegenMetadata::authSchemeClass) .collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Class::getSimpleName)))); if (useEndpointBasedAuthProvider()) { // sigv4a is not modeled but needed for the endpoints based auth-scheme cases. result.add(AwsV4aAuthScheme.class); } // Make the no-auth scheme available. result.add(NoAuthAuthScheme.class); return result; } private static Set<String> setOf(String v1, String v2) { Set<String> set = new HashSet<>(); set.add(v1); set.add(v2); return set; } }
3,408
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/auth/scheme/DefaultAuthSchemeParamsSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.auth.scheme; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Map; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.rules.EndpointRulesSpecUtils; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.Validate; public class DefaultAuthSchemeParamsSpec implements ClassSpec { private final IntermediateModel intermediateModel; private final AuthSchemeSpecUtils authSchemeSpecUtils; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public DefaultAuthSchemeParamsSpec(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; this.authSchemeSpecUtils = new AuthSchemeSpecUtils(intermediateModel); this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(intermediateModel); } @Override public ClassName className() { return authSchemeSpecUtils.parametersDefaultImplName(); } @Override public TypeSpec poetSpec() { TypeSpec.Builder b = PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(SdkInternalApi.class) .addSuperinterface(authSchemeSpecUtils.parametersInterfaceName()) .addMethod(constructor()) .addMethod(builderMethod()) .addType(builderImplSpec()); addFieldsAndAccessors(b); addToBuilder(b); return b.build(); } private MethodSpec constructor() { MethodSpec.Builder b = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(builderClassName(), "builder") .addStatement("this.operation = $T.paramNotNull(builder.operation, \"operation\")", Validate.class); if (authSchemeSpecUtils.usesSigV4()) { b.addStatement("this.region = builder.region"); } if (authSchemeSpecUtils.generateEndpointBasedParams()) { parameters().forEach((name, model) -> { if (authSchemeSpecUtils.includeParam(name)) { String fieldName = authSchemeSpecUtils.paramMethodName(name); boolean isRequired = isParamRequired(model); if (isRequired) { b.addStatement("this.$1N = $2T.paramNotNull(builder.$1N, $1S)", fieldName, Validate.class); } else { b.addStatement("this.$1N = builder.$1N", fieldName); } } }); } return b.build(); } private boolean isParamRequired(ParameterModel model) { Boolean isRequired = model.isRequired(); return (isRequired != null && isRequired) || model.getDefault() != null; } private MethodSpec builderMethod() { return MethodSpec.methodBuilder("builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(authSchemeSpecUtils.parametersInterfaceBuilderInterfaceName()) .addStatement("return new $T()", builderClassName()) .build(); } private TypeSpec builderImplSpec() { TypeSpec.Builder b = TypeSpec.classBuilder(builderClassName()) .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .addSuperinterface(authSchemeSpecUtils.parametersInterfaceBuilderInterfaceName()); addBuilderConstructors(b); addBuilderFieldsAndSetter(b); b.addMethod(MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(authSchemeSpecUtils.parametersInterfaceName()) .addStatement("return new $T(this)", className()) .build()); return b.build(); } private void addBuilderConstructors(TypeSpec.Builder b) { b.addMethod(MethodSpec.constructorBuilder() .build()); MethodSpec.Builder builderFromInstance = MethodSpec.constructorBuilder() .addParameter(className(), "params"); builderFromInstance.addStatement("this.operation = params.operation"); if (authSchemeSpecUtils.usesSigV4()) { builderFromInstance.addStatement("this.region = params.region"); } if (authSchemeSpecUtils.generateEndpointBasedParams()) { parameters().forEach((name, model) -> { if (authSchemeSpecUtils.includeParam(name)) { builderFromInstance.addStatement("this.$1N = params.$1N", endpointRulesSpecUtils.variableName(name)); } }); } b.addMethod(builderFromInstance.build()); } private void addFieldsAndAccessors(TypeSpec.Builder b) { b.addField(FieldSpec.builder(String.class, "operation") .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .build()); b.addMethod(MethodSpec.methodBuilder("operation") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(String.class) .addStatement("return operation") .build()); if (authSchemeSpecUtils.usesSigV4()) { b.addField(FieldSpec.builder(Region.class, "region") .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .build()); b.addMethod(MethodSpec.methodBuilder("region") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(Region.class) .addStatement("return region") .build()); } if (authSchemeSpecUtils.generateEndpointBasedParams()) { parameters().forEach((name, model) -> { if (authSchemeSpecUtils.includeParam(name)) { b.addField(endpointRulesSpecUtils.parameterClassField(name, model)); b.addMethod(endpointRulesSpecUtils.parameterClassAccessorMethod(name, model) .toBuilder() .addAnnotation(Override.class) .build()); } }); } } private void addToBuilder(TypeSpec.Builder b) { b.addMethod(MethodSpec.methodBuilder("toBuilder") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(authSchemeSpecUtils.parametersInterfaceBuilderInterfaceName()) .addStatement("return new $T(this)", builderClassName()) .build()); } private void addBuilderFieldsAndSetter(TypeSpec.Builder b) { b.addField(FieldSpec.builder(String.class, "operation") .addModifiers(Modifier.PRIVATE) .build()); b.addMethod(builderSetterMethod("operation", TypeName.get(String.class))); if (authSchemeSpecUtils.usesSigV4()) { b.addField(FieldSpec.builder(Region.class, "region") .addModifiers(Modifier.PRIVATE) .build()); b.addMethod(builderSetterMethod("region", TypeName.get(Region.class))); } if (authSchemeSpecUtils.generateEndpointBasedParams()) { parameters().forEach((name, model) -> { if (authSchemeSpecUtils.includeParam(name)) { b.addField(endpointRulesSpecUtils.parameterBuilderFieldSpec(name, model)); b.addMethod(endpointRulesSpecUtils.parameterBuilderSetterMethod(className(), name, model)); } }); } } private MethodSpec builderSetterMethod(String field, TypeName type) { return MethodSpec.methodBuilder(field) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(ParameterSpec.builder(type, field).build()) .returns(builderClassName()) .addStatement("this.$L = $L", field, field) .addStatement("return this") .build(); } private ClassName builderClassName() { return className().nestedClass("Builder"); } private Map<String, ParameterModel> parameters() { return intermediateModel.getEndpointRuleSetModel().getParameters(); } }
3,409
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/endpointdiscovery/EndpointDiscoveryCacheLoaderGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; 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; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryCacheLoader; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryEndpoint; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryRequest; import software.amazon.awssdk.utils.Validate; public class EndpointDiscoveryCacheLoaderGenerator implements ClassSpec { private static final String CLIENT_FIELD = "client"; private final IntermediateModel model; private final PoetExtension poetExtensions; public EndpointDiscoveryCacheLoaderGenerator(GeneratorTaskParams generatorTaskParams) { this.model = generatorTaskParams.getModel(); this.poetExtensions = generatorTaskParams.getPoetExtensions(); } @Override public TypeSpec poetSpec() { return TypeSpec.classBuilder(className()) .addAnnotation(SdkInternalApi.class) .addAnnotation(PoetUtils.generatedAnnotation()) .addSuperinterface(EndpointDiscoveryCacheLoader.class) .addField(FieldSpec.builder(poetExtensions.getClientClass(model.getMetadata().getSyncInterface()), CLIENT_FIELD) .addModifiers(FINAL, PRIVATE) .build()) .addMethod(constructor()) .addMethod(create()) .addMethod(discoverEndpoint(model.getEndpointOperation().get())) .build(); } @Override public ClassName className() { return poetExtensions.getClientClass(model.getNamingStrategy().getServiceName() + "EndpointDiscoveryCacheLoader"); } private MethodSpec create() { return MethodSpec.methodBuilder("create") .addModifiers(STATIC, PUBLIC) .returns(className()) .addParameter(poetExtensions.getClientClass(model.getMetadata().getSyncInterface()), CLIENT_FIELD) .addStatement("return new $T($L)", className(), CLIENT_FIELD) .build(); } private MethodSpec constructor() { return MethodSpec.constructorBuilder() .addModifiers(PRIVATE) .addParameter(poetExtensions.getClientClass(model.getMetadata().getSyncInterface()), CLIENT_FIELD) .addStatement("this.$L = $L", CLIENT_FIELD, CLIENT_FIELD) .build(); } private MethodSpec discoverEndpoint(OperationModel opModel) { ParameterizedTypeName returnType = ParameterizedTypeName.get(CompletableFuture.class, EndpointDiscoveryEndpoint.class); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("discoverEndpoint") .addModifiers(PUBLIC) .addAnnotation(Override.class) .addParameter(EndpointDiscoveryRequest.class, "endpointDiscoveryRequest") .returns(returnType); if (!opModel.getInputShape().isHasHeaderMember()) { ClassName endpointClass = poetExtensions.getModelClass("Endpoint"); methodBuilder.addCode("return $T.supplyAsync(() -> {", CompletableFuture.class) .addStatement("$1T requestConfig = $1T.from(endpointDiscoveryRequest.overrideConfiguration()" + ".orElse(null))", AwsRequestOverrideConfiguration.class) .addStatement("$T response = $L.$L($L.builder().overrideConfiguration(requestConfig).build())", poetExtensions.getModelClass(opModel.getOutputShape().getC2jName()), CLIENT_FIELD, opModel.getMethodName(), poetExtensions.getModelClass(opModel.getInputShape().getC2jName())) .addStatement("$T<$T> endpoints = response.endpoints()", List.class, endpointClass) .addStatement("$T.notEmpty(endpoints, \"Endpoints returned by service for endpoint discovery must " + "not be empty.\")", Validate.class) .addStatement("$T endpoint = endpoints.get(0)", endpointClass) .addStatement("return $T.builder().endpoint(toUri(endpoint.address(), $L.defaultEndpoint()))" + ".expirationTime($T.now().plus(endpoint.cachePeriodInMinutes(), $T.MINUTES)).build()", EndpointDiscoveryEndpoint.class, "endpointDiscoveryRequest", Instant.class, ChronoUnit.class) .addStatement("})"); } return methodBuilder.build(); } }
3,410
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/endpointdiscovery/EndpointDiscoveryAsyncCacheLoaderGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; 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; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryCacheLoader; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryEndpoint; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryRequest; import software.amazon.awssdk.utils.Validate; public class EndpointDiscoveryAsyncCacheLoaderGenerator implements ClassSpec { private static final String CLIENT_FIELD = "client"; private final IntermediateModel model; private final PoetExtension poetExtensions; public EndpointDiscoveryAsyncCacheLoaderGenerator(GeneratorTaskParams generatorTaskParams) { this.model = generatorTaskParams.getModel(); this.poetExtensions = generatorTaskParams.getPoetExtensions(); } @Override public TypeSpec poetSpec() { return TypeSpec.classBuilder(className()) .addAnnotation(SdkInternalApi.class) .addAnnotation(PoetUtils.generatedAnnotation()) .addSuperinterface(EndpointDiscoveryCacheLoader.class) .addField(FieldSpec.builder(poetExtensions.getClientClass(model.getMetadata().getAsyncInterface()), CLIENT_FIELD) .addModifiers(FINAL, PRIVATE) .build()) .addMethod(constructor()) .addMethod(create()) .addMethod(discoverEndpoint(model.getEndpointOperation().get())) .build(); } @Override public ClassName className() { return poetExtensions.getClientClass(model.getNamingStrategy().getServiceName() + "AsyncEndpointDiscoveryCacheLoader"); } private MethodSpec constructor() { return MethodSpec.constructorBuilder() .addParameter(poetExtensions.getClientClass(model.getMetadata().getAsyncInterface()), CLIENT_FIELD) .addStatement("this.$L = $L", CLIENT_FIELD, CLIENT_FIELD) .build(); } private MethodSpec create() { return MethodSpec.methodBuilder("create") .addModifiers(STATIC, PUBLIC) .returns(className()) .addParameter(poetExtensions.getClientClass(model.getMetadata().getAsyncInterface()), CLIENT_FIELD) .addStatement("return new $T($L)", className(), CLIENT_FIELD) .build(); } private MethodSpec discoverEndpoint(OperationModel opModel) { ParameterizedTypeName returnType = ParameterizedTypeName.get(CompletableFuture.class, EndpointDiscoveryEndpoint.class); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("discoverEndpoint") .addModifiers(PUBLIC) .addAnnotation(Override.class) .addParameter(EndpointDiscoveryRequest.class, "endpointDiscoveryRequest") .returns(returnType); if (!opModel.getInputShape().isHasHeaderMember()) { ClassName endpointClass = poetExtensions.getModelClass("Endpoint"); methodBuilder.addStatement("$1T requestConfig = $1T.from(endpointDiscoveryRequest.overrideConfiguration()" + ".orElse(null))", AwsRequestOverrideConfiguration.class) .addCode("return $L.$L($L.builder().overrideConfiguration(requestConfig).build()).thenApply(r -> {", CLIENT_FIELD, opModel.getMethodName(), poetExtensions.getModelClass(opModel.getInputShape().getC2jName())) .addStatement("$T<$T> endpoints = r.endpoints()", List.class, endpointClass) .addStatement("$T.notEmpty(endpoints, \"Endpoints returned by service for endpoint discovery must " + "not be empty.\")", Validate.class) .addStatement("$T endpoint = endpoints.get(0)", endpointClass) .addStatement("return $T.builder().endpoint(toUri(endpoint.address(), $L.defaultEndpoint()))" + ".expirationTime($T.now().plus(endpoint.cachePeriodInMinutes(), $T.MINUTES)).build()", EndpointDiscoveryEndpoint.class, "endpointDiscoveryRequest", Instant.class, ChronoUnit.class) .addStatement("})"); } return methodBuilder.build(); } }
3,411
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/waiters/JmesPathAcceptorGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.fasterxml.jackson.jr.stree.JrsBoolean; import com.fasterxml.jackson.jr.stree.JrsValue; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import software.amazon.awssdk.codegen.jmespath.component.AndExpression; import software.amazon.awssdk.codegen.jmespath.component.BracketSpecifier; import software.amazon.awssdk.codegen.jmespath.component.BracketSpecifierWithContents; import software.amazon.awssdk.codegen.jmespath.component.BracketSpecifierWithQuestionMark; import software.amazon.awssdk.codegen.jmespath.component.BracketSpecifierWithoutContents; import software.amazon.awssdk.codegen.jmespath.component.ComparatorExpression; import software.amazon.awssdk.codegen.jmespath.component.CurrentNode; import software.amazon.awssdk.codegen.jmespath.component.Expression; import software.amazon.awssdk.codegen.jmespath.component.ExpressionType; import software.amazon.awssdk.codegen.jmespath.component.FunctionArg; import software.amazon.awssdk.codegen.jmespath.component.FunctionExpression; import software.amazon.awssdk.codegen.jmespath.component.IndexExpression; import software.amazon.awssdk.codegen.jmespath.component.Literal; import software.amazon.awssdk.codegen.jmespath.component.MultiSelectHash; import software.amazon.awssdk.codegen.jmespath.component.MultiSelectList; import software.amazon.awssdk.codegen.jmespath.component.NotExpression; import software.amazon.awssdk.codegen.jmespath.component.OrExpression; import software.amazon.awssdk.codegen.jmespath.component.ParenExpression; import software.amazon.awssdk.codegen.jmespath.component.PipeExpression; import software.amazon.awssdk.codegen.jmespath.component.SliceExpression; import software.amazon.awssdk.codegen.jmespath.component.SubExpression; import software.amazon.awssdk.codegen.jmespath.component.SubExpressionRight; import software.amazon.awssdk.codegen.jmespath.component.WildcardExpression; import software.amazon.awssdk.codegen.jmespath.parser.JmesPathParser; import software.amazon.awssdk.codegen.jmespath.parser.JmesPathVisitor; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.utils.Validate; /** * A code interpreter for converting JMESPath expressions into Java expressions. * * This can convert a JMESPath expression into a statement that executes against an {@link SdkPojo}. The statements generated by * this interpreter make heavy use of the {@link WaitersRuntime}. */ public class JmesPathAcceptorGenerator { private final ClassName waitersRuntimeClass; public JmesPathAcceptorGenerator(ClassName waitersRuntimeClass) { this.waitersRuntimeClass = waitersRuntimeClass; } /** * Interpret the provided expression into a java statement that executes against the provided input value. This inputValue * should be a JMESPath Value in scope. */ public CodeBlock interpret(String expression, String inputValue) { CodeBlock.Builder codeBlock = CodeBlock.builder(); Visitor visitor = new Visitor(codeBlock, inputValue); JmesPathParser.parse(expression).visit(visitor); return visitor.codeBlock.build(); } /** * An implementation of {@link JmesPathVisitor} used by {@link #interpret(String, String)}. */ private class Visitor implements JmesPathVisitor { private final CodeBlock.Builder codeBlock; private final Deque<String> variables = new ArrayDeque<>(); private int variableIndex = 0; private Visitor(CodeBlock.Builder codeBlock, String inputValue) { this.codeBlock = codeBlock; this.codeBlock.add(inputValue); this.variables.push(inputValue); } @Override public void visitExpression(Expression input) { input.visit(this); } @Override public void visitSubExpression(SubExpression input) { visitExpression(input.leftExpression()); visitSubExpressionRight(input.rightSubExpression()); } @Override public void visitSubExpressionRight(SubExpressionRight input) { input.visit(this); } @Override public void visitIndexExpression(IndexExpression input) { input.expression().ifPresent(this::visitExpression); visitBracketSpecifier(input.bracketSpecifier()); } @Override public void visitBracketSpecifier(BracketSpecifier input) { input.visit(this); } @Override public void visitBracketSpecifierWithContents(BracketSpecifierWithContents input) { if (input.isNumber()) { codeBlock.add(".index(" + input.asNumber() + ")"); } else { throw new UnsupportedOperationException(); } } @Override public void visitBracketSpecifierWithoutContents(BracketSpecifierWithoutContents input) { codeBlock.add(".flatten()"); } @Override public void visitBracketSpecifierWithQuestionMark(BracketSpecifierWithQuestionMark input) { pushVariable(); codeBlock.add(".filter($1N -> $1N", currentVariable()); visitExpression(input.expression()); codeBlock.add(")"); popVariable(); } @Override public void visitSliceExpression(SliceExpression input) { throw new UnsupportedOperationException(); } @Override public void visitComparatorExpression(ComparatorExpression input) { visitExpression(input.leftExpression()); codeBlock.add(".compare($S, $N", input.comparator().tokenSymbol(), currentVariable()); visitExpression(input.rightExpression()); codeBlock.add(")"); } @Override public void visitOrExpression(OrExpression input) { visitExpression(input.leftExpression()); codeBlock.add(".or($N", currentVariable()); visitExpression(input.rightExpression()); codeBlock.add(")"); } @Override public void visitAndExpression(AndExpression input) { visitExpression(input.leftExpression()); codeBlock.add(".and($N", currentVariable()); visitExpression(input.rightExpression()); codeBlock.add(")"); } @Override public void visitNotExpression(NotExpression input) { codeBlock.add(".constant($N", currentVariable()); visitExpression(input.expression()); codeBlock.add(".not())"); } @Override public void visitParenExpression(ParenExpression input) { visitExpression(input.expression()); } @Override public void visitWildcardExpression(WildcardExpression input) { codeBlock.add(".wildcard()"); } @Override public void visitMultiSelectList(MultiSelectList input) { codeBlock.add(".multiSelectList("); boolean first = true; for (Expression expression : input.expressions()) { if (!first) { codeBlock.add(", "); } else { first = false; } pushVariable(); codeBlock.add("$1N -> $1N", currentVariable()); visitExpression(expression); popVariable(); } codeBlock.add(")"); } @Override public void visitMultiSelectHash(MultiSelectHash input) { throw new UnsupportedOperationException(); } @Override public void visitExpressionType(ExpressionType asExpressionType) { throw new UnsupportedOperationException(); } @Override public void visitFunctionExpression(FunctionExpression input) { switch (input.function()) { case "length": visitLengthFunction(input.functionArgs()); break; case "contains": visitContainsFunction(input.functionArgs()); break; default: throw new IllegalArgumentException("Unsupported function: " + input.function()); } } private void visitLengthFunction(List<FunctionArg> functionArgs) { Validate.isTrue(functionArgs.size() == 1, "length function only supports 1 parameter."); Validate.isTrue(functionArgs.get(0).isExpression(), "length's first parameter must be an expression."); visitExpression(functionArgs.get(0).asExpression()); codeBlock.add(".length()"); } private void visitContainsFunction(List<FunctionArg> functionArgs) { Validate.isTrue(functionArgs.size() == 2, "contains function only supports 2 parameter."); Validate.isTrue(functionArgs.get(0).isExpression(), "contain's first parameter must be an expression."); Validate.isTrue(functionArgs.get(1).isExpression(), "contain's second parameter must be an expression."); visitExpression(functionArgs.get(0).asExpression()); codeBlock.add(".contains($N", currentVariable()); visitExpression(functionArgs.get(1).asExpression()); codeBlock.add(")"); } @Override public void visitPipeExpression(PipeExpression input) { throw new UnsupportedOperationException(); } @Override public void visitCurrentNode(CurrentNode input) { throw new UnsupportedOperationException(); } @Override public void visitRawString(String input) { codeBlock.add(".constant($S)", input); } @Override public void visitLiteral(Literal input) { JrsValue jsonValue = input.jsonValue(); if (jsonValue.isNumber()) { codeBlock.add(".constant($L)", Integer.parseInt(jsonValue.asText())); } else if (jsonValue instanceof JrsBoolean) { codeBlock.add(".constant($L)", ((JrsBoolean) jsonValue).booleanValue()); } else { throw new IllegalArgumentException("Unsupported JSON node type: " + input.jsonValue().getClass().getSimpleName()); } } @Override public void visitIdentifier(String input) { codeBlock.add(".field($S)", input); } @Override public void visitNumber(int input) { codeBlock.add(".constant($L)", waitersRuntimeClass.nestedClass("Value"), input); } /** * Push a variable onto the variable stack. This is used so that lambda expressions can address their closest-scoped * variable. For example, the right-hand-side of an AND expression needs to address the same variable as the * left-hand-side of the expression. */ public void pushVariable() { variables.push("x" + variableIndex++); } /** * Retrieve the current variable on the top of the stack. */ public String currentVariable() { return variables.getFirst(); } /** * Pop the last variable added from the variable stack. */ public void popVariable() { variables.pop(); } } }
3,412
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/waiters/AsyncWaiterClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.core.internal.waiters.WaiterAttribute; import software.amazon.awssdk.core.waiters.AsyncWaiter; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.utils.ThreadFactoryBuilder; public class AsyncWaiterClassSpec extends BaseWaiterClassSpec { private final PoetExtension poetExtensions; private final ClassName className; private final IntermediateModel model; private final String modelPackage; public AsyncWaiterClassSpec(IntermediateModel model) { super(model, ClassName.get(AsyncWaiter.class)); this.model = model; this.modelPackage = model.getMetadata().getFullModelPackageName(); this.poetExtensions = new PoetExtension(model); this.className = poetExtensions.getAsyncWaiterClass(); } @Override public ClassName className() { return className; } @Override protected ClassName clientClassName() { return poetExtensions.getClientClass(model.getMetadata().getAsyncInterface()); } @Override protected ParameterizedTypeName getWaiterResponseType(OperationModel opModel) { ClassName pojoResponse = ClassName.get(modelPackage, opModel.getReturnType().getReturnType()); ParameterizedTypeName waiterResponse = ParameterizedTypeName.get(ClassName.get(WaiterResponse.class), pojoResponse); return ParameterizedTypeName.get(ClassName.get(CompletableFuture.class), waiterResponse); } @Override protected ClassName interfaceClassName() { return poetExtensions.getAsyncWaiterInterface(); } @Override protected Optional<String> additionalWaiterConfig() { return Optional.of(".scheduledExecutorService(executorService)"); } @Override protected void additionalConstructorInitialization(MethodSpec.Builder method) { method.beginControlFlow("if (builder.executorService == null)") .addStatement("this.executorService = $T.newScheduledThreadPool(1, new $T().threadNamePrefix" + "($S).build())", Executors.class, ThreadFactoryBuilder.class, "waiters-ScheduledExecutor") .addStatement("attributeMapBuilder.put(SCHEDULED_EXECUTOR_SERVICE_ATTRIBUTE, this.executorService)") .endControlFlow(); method.beginControlFlow("else") .addStatement("this.executorService = builder.executorService") .endControlFlow(); } @Override protected void additionalTypeSpecModification(TypeSpec.Builder type) { type.addField(FieldSpec.builder(ParameterizedTypeName.get(WaiterAttribute.class, ScheduledExecutorService.class), "SCHEDULED_EXECUTOR_SERVICE_ATTRIBUTE", PRIVATE, STATIC, FINAL) .initializer("new $T<>($T.class)", WaiterAttribute.class, ScheduledExecutorService.class) .build()); type.addField(FieldSpec.builder(ScheduledExecutorService.class, "executorService") .addModifiers(PRIVATE, FINAL) .build()); } @Override protected void additionalBuilderTypeSpecModification(TypeSpec.Builder type) { type.addField(ClassName.get(ScheduledExecutorService.class), "executorService", PRIVATE); type.addMethod(MethodSpec.methodBuilder("scheduledExecutorService") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(ClassName.get(ScheduledExecutorService.class), "executorService") .addStatement("this.executorService = executorService") .addStatement("return this") .returns(interfaceClassName().nestedClass("Builder")) .build()); } }
3,413
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/waiters/BaseWaiterInterfaceSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.docs.WaiterDocs; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.service.WaiterDefinition; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Base class contains shared logic used in both sync waiter and async waiter interfaces. */ public abstract class BaseWaiterInterfaceSpec implements ClassSpec { private final IntermediateModel model; private final Map<String, WaiterDefinition> waiters; private final String modelPackage; public BaseWaiterInterfaceSpec(IntermediateModel model) { this.modelPackage = model.getMetadata().getFullModelPackageName(); this.model = model; this.waiters = model.getWaiters(); } @Override public TypeSpec poetSpec() { TypeSpec.Builder result = PoetUtils.createInterfaceBuilder(className()); result.addAnnotation(SdkPublicApi.class); result.addMethods(waiterOperations()); result.addSuperinterface(SdkAutoCloseable.class); result.addMethod(MethodSpec.methodBuilder("builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc(WaiterDocs.waiterBuilderMethodJavadoc(className())) .returns(className().nestedClass("Builder")) .addStatement("return $T.builder()", waiterImplName()) .build()); result.addMethod(MethodSpec.methodBuilder("create") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc(WaiterDocs.waiterCreateMethodJavadoc(className(), clientClassName())) .returns(className()) .addStatement("return $T.builder().build()", waiterImplName()) .build()); result.addJavadoc(WaiterDocs.waiterInterfaceJavadoc()); result.addType(builderInterface()); return result.build(); } protected abstract ClassName waiterImplName(); protected abstract ClassName clientClassName(); protected abstract ParameterizedTypeName getWaiterResponseType(OperationModel operationModel); protected void additionalBuilderTypeSpecModification(TypeSpec.Builder type) { // no-op } /** * @return List generated of traditional (request/response) methods for all operations. */ private List<MethodSpec> waiterOperations() { return waiters.entrySet() .stream() .flatMap(this::waiterOperations) .sorted(Comparator.comparing(m -> m.name)) .collect(Collectors.toList()); } private Stream<MethodSpec> waiterOperations(Map.Entry<String, WaiterDefinition> waiterDefinition) { List<MethodSpec> methods = new ArrayList<>(); methods.add(waiterOperation(waiterDefinition)); methods.add(waiterConsumerBuilderOperation(waiterDefinition)); methods.add(waiterOperationWithOverrideConfig(waiterDefinition)); methods.add(waiterConsumerBuilderOperationWithOverrideConfig(waiterDefinition)); return methods.stream(); } private MethodSpec waiterOperation(Map.Entry<String, WaiterDefinition> waiterDefinition) { String waiterMethodName = waiterDefinition.getKey(); OperationModel opModel = model.getOperation(waiterDefinition.getValue().getOperation()); ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType()); CodeBlock javadoc = WaiterDocs.waiterOperationJavadoc(clientClassName(), waiterDefinition, opModel); MethodSpec.Builder builder = methodSignatureWithReturnType(waiterMethodName, opModel) .addParameter(requestType, opModel.getInput().getVariableName()) .addJavadoc(javadoc); return unsupportedOperation(builder).build(); } private MethodSpec waiterOperationWithOverrideConfig(Map.Entry<String, WaiterDefinition> waiterDefinition) { String waiterMethodName = waiterDefinition.getKey(); OperationModel opModel = model.getOperation(waiterDefinition.getValue().getOperation()); ClassName requestClass = ClassName.get(modelPackage, opModel.getInput().getVariableType()); CodeBlock javadoc = WaiterDocs.waiterOperationWithOverrideConfig( clientClassName(), waiterDefinition, opModel); MethodSpec.Builder builder = methodSignatureWithReturnType(waiterMethodName, opModel) .addParameter(requestClass, opModel.getInput().getVariableName()) .addParameter(ClassName.get(WaiterOverrideConfiguration.class), "overrideConfig") .addJavadoc(javadoc); return unsupportedOperation(builder).build(); } private MethodSpec waiterConsumerBuilderOperationWithOverrideConfig(Map.Entry<String, WaiterDefinition> waiterDefinition) { String waiterMethodName = waiterDefinition.getKey(); OperationModel opModel = model.getOperation(waiterDefinition.getValue().getOperation()); ClassName requestClass = ClassName.get(modelPackage, opModel.getInput().getVariableType()); ParameterizedTypeName requestType = ParameterizedTypeName.get(ClassName.get(Consumer.class), requestClass.nestedClass("Builder")); ParameterizedTypeName overrideConfigType = ParameterizedTypeName.get(ClassName.get(Consumer.class), ClassName.get(WaiterOverrideConfiguration.class).nestedClass("Builder")); CodeBlock javadoc = WaiterDocs.waiterOperationWithOverrideConfigConsumerBuilder( clientClassName(), requestClass, waiterDefinition, opModel); String inputVariable = opModel.getInput().getVariableName(); MethodSpec.Builder builder = methodSignatureWithReturnType(waiterMethodName, opModel) .addParameter(requestType, inputVariable) .addParameter(overrideConfigType, "overrideConfig") .addJavadoc(javadoc); builder.addModifiers(Modifier.DEFAULT, Modifier.PUBLIC) .addStatement("return $L($T.builder().applyMutation($L).build()," + "$T.builder().applyMutation($L).build())", getWaiterMethodName(waiterMethodName), requestClass, inputVariable, ClassName.get(WaiterOverrideConfiguration.class), "overrideConfig"); return builder.build(); } private MethodSpec waiterConsumerBuilderOperation(Map.Entry<String, WaiterDefinition> waiterDefinition) { String waiterMethodName = waiterDefinition.getKey(); OperationModel opModel = model.getOperation(waiterDefinition.getValue().getOperation()); ClassName requestClass = ClassName.get(modelPackage, opModel.getInput().getVariableType()); ParameterizedTypeName requestType = ParameterizedTypeName.get(ClassName.get(Consumer.class), requestClass.nestedClass("Builder")); CodeBlock javadoc = WaiterDocs.waiterOperationConsumerBuilderJavadoc( clientClassName(), requestClass, waiterDefinition, opModel); String inputVariable = opModel.getInput().getVariableName(); MethodSpec.Builder builder = methodSignatureWithReturnType(waiterMethodName, opModel) .addParameter(requestType, inputVariable) .addJavadoc(javadoc); builder.addModifiers(Modifier.DEFAULT, Modifier.PUBLIC) .addStatement("return $L($T.builder().applyMutation($L).build())", getWaiterMethodName(waiterMethodName), requestClass, inputVariable); return builder.build(); } private MethodSpec.Builder methodSignatureWithReturnType(String waiterMethodName, OperationModel opModel) { return MethodSpec.methodBuilder(getWaiterMethodName(waiterMethodName)) .returns(getWaiterResponseType(opModel)); } private String getWaiterMethodName(String waiterMethodName) { return "waitUntil" + waiterMethodName; } private MethodSpec.Builder unsupportedOperation(MethodSpec.Builder builder) { return builder.addModifiers(Modifier.DEFAULT, Modifier.PUBLIC) .addStatement("throw new $T()", UnsupportedOperationException.class); } private TypeSpec builderInterface() { TypeSpec.Builder builder = TypeSpec.interfaceBuilder("Builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC); additionalBuilderTypeSpecModification(builder); builder.addMethods(builderMethods()); return builder.build(); } private List<MethodSpec> builderMethods() { List<MethodSpec> builderMethods = new ArrayList<>(); builderMethods.add(MethodSpec.methodBuilder("overrideConfiguration") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addParameter(ClassName.get(WaiterOverrideConfiguration.class), "overrideConfiguration") .addJavadoc(WaiterDocs.waiterBuilderPollingStrategy()) .returns(className().nestedClass("Builder")) .build()); ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(Consumer.class), ClassName.get(WaiterOverrideConfiguration.class).nestedClass("Builder")); builderMethods.add(MethodSpec.methodBuilder("overrideConfiguration") .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) .addParameter(parameterizedTypeName, "overrideConfiguration") .addJavadoc(WaiterDocs.waiterBuilderPollingStrategyConsumerBuilder()) .addStatement("$T.Builder builder = $T.builder()", WaiterOverrideConfiguration.class, WaiterOverrideConfiguration.class) .addStatement("overrideConfiguration.accept(builder)") .addStatement("return overrideConfiguration(builder.build())") .returns(className().nestedClass("Builder")) .build()); builderMethods.add(MethodSpec.methodBuilder("client") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addParameter(clientClassName(), "client") .addJavadoc(WaiterDocs.waiterBuilderClientJavadoc(clientClassName())) .returns(className().nestedClass("Builder")) .build()); builderMethods.add(MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addJavadoc(WaiterDocs.waiterBuilderBuildJavadoc(className())) .returns(className()) .build()); return builderMethods; } }
3,414
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/waiters/WaiterInterfaceSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.core.waiters.WaiterResponse; public final class WaiterInterfaceSpec extends BaseWaiterInterfaceSpec { private final IntermediateModel model; private final PoetExtension poetExtensions; private final ClassName className; private final String modelPackage; public WaiterInterfaceSpec(IntermediateModel model) { super(model); this.modelPackage = model.getMetadata().getFullModelPackageName(); this.model = model; this.poetExtensions = new PoetExtension(model); this.className = poetExtensions.getSyncWaiterInterface(); } @Override protected ClassName waiterImplName() { return poetExtensions.getSyncWaiterClass(); } @Override protected ClassName clientClassName() { return poetExtensions.getClientClass(model.getMetadata().getSyncInterface()); } @Override public ClassName className() { return className; } @Override protected ParameterizedTypeName getWaiterResponseType(OperationModel opModel) { ClassName pojoResponse = ClassName.get(modelPackage, opModel.getReturnType().getReturnType()); return ParameterizedTypeName.get(ClassName.get(WaiterResponse.class), pojoResponse); } }
3,415
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/waiters/WaiterClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.core.waiters.Waiter; import software.amazon.awssdk.core.waiters.WaiterResponse; public class WaiterClassSpec extends BaseWaiterClassSpec { private final PoetExtension poetExtensions; private final ClassName className; private final String modelPackage; private final ClassName clientClassName; public WaiterClassSpec(IntermediateModel model) { super(model, ClassName.get(Waiter.class)); this.modelPackage = model.getMetadata().getFullModelPackageName(); this.poetExtensions = new PoetExtension(model); this.className = poetExtensions.getSyncWaiterClass(); this.clientClassName = poetExtensions.getClientClass(model.getMetadata().getSyncInterface()); } @Override protected ClassName clientClassName() { return clientClassName; } @Override protected ParameterizedTypeName getWaiterResponseType(OperationModel opModel) { ClassName pojoResponse = ClassName.get(modelPackage, opModel.getReturnType().getReturnType()); return ParameterizedTypeName.get(ClassName.get(WaiterResponse.class), pojoResponse); } @Override protected ClassName interfaceClassName() { return poetExtensions.getSyncWaiterInterface(); } @Override public ClassName className() { return className; } }
3,416
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/waiters/BaseWaiterClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static software.amazon.awssdk.utils.internal.CodegenNamingUtils.lowercaseFirstChar; import com.fasterxml.jackson.jr.stree.JrsString; 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.TypeVariableName; import com.squareup.javapoet.WildcardTypeName; import java.time.Duration; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.codegen.emitters.tasks.WaitersRuntimeGeneratorTask; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.service.Acceptor; import software.amazon.awssdk.codegen.model.service.WaiterDefinition; 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.core.ApiName; import software.amazon.awssdk.core.internal.waiters.WaiterAttribute; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.core.waiters.WaiterAcceptor; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; import software.amazon.awssdk.core.waiters.WaiterState; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Base class containing common logic shared between the sync waiter class and the async waiter class */ public abstract class BaseWaiterClassSpec implements ClassSpec { private static final String WAITERS_USER_AGENT = "waiter"; private final IntermediateModel model; private final String modelPackage; private final Map<String, WaiterDefinition> waiters; private final ClassName waiterClassName; private final JmesPathAcceptorGenerator jmesPathAcceptorGenerator; private final PoetExtension poetExtensions; public BaseWaiterClassSpec(IntermediateModel model, ClassName waiterClassName) { this.model = model; this.modelPackage = model.getMetadata().getFullModelPackageName(); this.waiters = model.getWaiters(); this.waiterClassName = waiterClassName; this.jmesPathAcceptorGenerator = new JmesPathAcceptorGenerator(waitersRuntimeClass()); this.poetExtensions = new PoetExtension(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder typeSpecBuilder = PoetUtils.createClassBuilder(className()); typeSpecBuilder.addAnnotation(SdkInternalApi.class); typeSpecBuilder.addAnnotation(ThreadSafe.class); typeSpecBuilder.addModifiers(FINAL); typeSpecBuilder.addSuperinterface(interfaceClassName()); typeSpecBuilder.addMethod(constructor()); typeSpecBuilder.addField(FieldSpec.builder(ParameterizedTypeName.get(WaiterAttribute.class, SdkAutoCloseable.class), "CLIENT_ATTRIBUTE", PRIVATE, STATIC, FINAL) .initializer("new $T<>($T.class)", WaiterAttribute.class, SdkAutoCloseable.class) .build()); typeSpecBuilder.addField(clientClassName(), "client", PRIVATE, FINAL); typeSpecBuilder.addField(ClassName.get(AttributeMap.class), "managedResources", PRIVATE, FINAL); typeSpecBuilder.addMethod(staticErrorCodeMethod()); typeSpecBuilder.addMethods(waiterOperations()); typeSpecBuilder.addMethods(waiterAcceptorInitializers()); typeSpecBuilder.addMethods(waiterConfigInitializers()); typeSpecBuilder.addFields(waitersFields()); additionalTypeSpecModification(typeSpecBuilder); typeSpecBuilder.addMethod(closeMethod()); typeSpecBuilder.addMethod(MethodSpec.methodBuilder("builder") .addModifiers(Modifier.PUBLIC, STATIC) .returns(interfaceClassName().nestedClass("Builder")) .addStatement("return new DefaultBuilder()") .build()); typeSpecBuilder.addType(builder()); typeSpecBuilder.addMethod(applyWaitersUserAgentMethod(poetExtensions, model)); return typeSpecBuilder.build(); } private MethodSpec closeMethod() { return MethodSpec.methodBuilder("close") .addAnnotation(Override.class) .addModifiers(PUBLIC) .addStatement("managedResources.close()") .build(); } protected abstract ClassName clientClassName(); protected abstract TypeName getWaiterResponseType(OperationModel opModel); protected abstract ClassName interfaceClassName(); protected void additionalTypeSpecModification(TypeSpec.Builder type) { // no-op } protected void additionalConstructorInitialization(MethodSpec.Builder method) { // no-op } protected void additionalBuilderTypeSpecModification(TypeSpec.Builder builder) { // no-op } protected Optional<String> additionalWaiterConfig() { return Optional.empty(); } private MethodSpec constructor() { MethodSpec.Builder ctor = MethodSpec.constructorBuilder() .addModifiers(PRIVATE) .addParameter(className().nestedClass("DefaultBuilder"), "builder"); ctor.addStatement("$T attributeMapBuilder = $T.builder()", ClassName.get(AttributeMap.class).nestedClass("Builder"), AttributeMap.class); ctor.beginControlFlow("if (builder.client == null)") .addStatement("this.client = $T.builder().build()", clientClassName()) .addStatement("attributeMapBuilder.put(CLIENT_ATTRIBUTE, this.client)") .endControlFlow(); ctor.beginControlFlow("else") .addStatement("this.client = builder.client") .endControlFlow(); additionalConstructorInitialization(ctor); ctor.addStatement("managedResources = attributeMapBuilder.build()"); waiters.entrySet().stream() .map(this::waiterFieldInitialization) .forEach(ctor::addCode); return ctor.build(); } private List<MethodSpec> waiterConfigInitializers() { List<MethodSpec> initializers = new ArrayList<>(); waiters.forEach((k, v) -> initializers.add(waiterConfigInitializer(k, v))); return initializers; } private MethodSpec waiterConfigInitializer(String waiterKey, WaiterDefinition waiterDefinition) { ClassName overrideConfig = ClassName.get(WaiterOverrideConfiguration.class); MethodSpec.Builder configMethod = MethodSpec.methodBuilder(waiterFieldName(waiterKey) + "Config") .addModifiers(PRIVATE, STATIC) .addParameter(overrideConfig, "overrideConfig") .returns(overrideConfig); configMethod.addStatement("$T<$T> optionalOverrideConfig = Optional.ofNullable(overrideConfig)", Optional.class, WaiterOverrideConfiguration.class); configMethod.addStatement("int maxAttempts = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::maxAttempts)" + ".orElse($L)", waiterDefinition.getMaxAttempts()); configMethod.addStatement("$T backoffStrategy = optionalOverrideConfig." + "flatMap(WaiterOverrideConfiguration::backoffStrategy).orElse($T.create($T.ofSeconds($L)))", BackoffStrategy.class, FixedDelayBackoffStrategy.class, Duration.class, waiterDefinition.getDelay()); configMethod.addStatement("$T waitTimeout = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::waitTimeout)" + ".orElse(null)", Duration.class); configMethod.addStatement("return WaiterOverrideConfiguration.builder().maxAttempts(maxAttempts).backoffStrategy" + "(backoffStrategy).waitTimeout(waitTimeout).build()"); return configMethod.build(); } private CodeBlock waiterFieldInitialization(Map.Entry<String, WaiterDefinition> waiterDefinition) { String waiterKey = waiterDefinition.getKey(); WaiterDefinition waiter = waiterDefinition.getValue(); OperationModel opModel = operationModel(waiter); CodeBlock.Builder codeBlockBuilder = CodeBlock .builder(); String waiterFieldName = waiterFieldName(waiterKey); codeBlockBuilder.add("this.$L = $T.builder($T.class)" + ".acceptors($LAcceptors()).overrideConfiguration($LConfig(builder.overrideConfiguration))", waiterFieldName, waiterClassName, ClassName.get(modelPackage, opModel.getReturnType().getReturnType()), waiterFieldName, waiterFieldName); additionalWaiterConfig().ifPresent(codeBlockBuilder::add); codeBlockBuilder.addStatement(".build()"); return codeBlockBuilder.build(); } private List<FieldSpec> waitersFields() { return waiters.entrySet().stream() .map(this::waiterField) .collect(Collectors.toList()); } private FieldSpec waiterField(Map.Entry<String, WaiterDefinition> waiterDefinition) { OperationModel opModel = operationModel(waiterDefinition.getValue()); ClassName pojoResponse = ClassName.get(modelPackage, opModel.getReturnType().getReturnType()); String fieldName = waiterFieldName(waiterDefinition.getKey()); return FieldSpec.builder(ParameterizedTypeName.get(waiterClassName, pojoResponse), fieldName) .addModifiers(PRIVATE, FINAL) .build(); } private TypeSpec builder() { TypeSpec.Builder builder = TypeSpec.classBuilder("DefaultBuilder") .addModifiers(PUBLIC, STATIC, FINAL) .addSuperinterface(interfaceClassName().nestedClass("Builder")) .addField(clientClassName(), "client", PRIVATE) .addField(ClassName.get(WaiterOverrideConfiguration.class), "overrideConfiguration", PRIVATE); additionalBuilderTypeSpecModification(builder); builder.addMethods(builderMethods()); builder.addMethod(MethodSpec.constructorBuilder() .addModifiers(PRIVATE) .build()); return builder.build(); } private List<MethodSpec> builderMethods() { List<MethodSpec> methods = new ArrayList<>(); methods.add(MethodSpec.methodBuilder("overrideConfiguration") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(ClassName.get(WaiterOverrideConfiguration.class), "overrideConfiguration") .addStatement("this.overrideConfiguration = overrideConfiguration") .addStatement("return this") .returns(interfaceClassName().nestedClass("Builder")) .build()); methods.add(MethodSpec.methodBuilder("client") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(clientClassName(), "client") .addStatement("this.client = client") .addStatement("return this") .returns(interfaceClassName().nestedClass("Builder")) .build()); methods.add(MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .returns(interfaceClassName()) .addStatement("return new $T(this)", className()) .build()); return methods; } private List<MethodSpec> waiterOperations() { return waiters.entrySet() .stream() .flatMap(this::waiterOperations) .sorted(Comparator.comparing(m -> m.name)) .collect(Collectors.toList()); } private Stream<MethodSpec> waiterOperations(Map.Entry<String, WaiterDefinition> waiterDefinition) { List<MethodSpec> methods = new ArrayList<>(); methods.add(waiterOperation(waiterDefinition)); methods.add(waiterOperationWithOverrideConfig(waiterDefinition)); return methods.stream(); } private MethodSpec waiterOperationWithOverrideConfig(Map.Entry<String, WaiterDefinition> waiterDefinition) { String waiterMethodName = waiterDefinition.getKey(); OperationModel opModel = operationModel(waiterDefinition.getValue()); ClassName overrideConfig = ClassName.get(WaiterOverrideConfiguration.class); ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType()); String waiterFieldName = waiterFieldName(waiterDefinition.getKey()); MethodSpec.Builder builder = methodSignatureWithReturnType(waiterMethodName, opModel) .addParameter(requestType, opModel.getInput().getVariableName()) .addParameter(overrideConfig, "overrideConfig") .addModifiers(PUBLIC) .addAnnotation(Override.class) .addStatement("return $L.$L(() -> client.$N(applyWaitersUserAgent($N)), $LConfig(overrideConfig))", waiterFieldName, waiterClassName.simpleName().equals("Waiter") ? "run" : "runAsync", lowercaseFirstChar(waiterDefinition.getValue().getOperation()), opModel.getInput().getVariableName(), waiterFieldName); return builder.build(); } private MethodSpec waiterOperation(Map.Entry<String, WaiterDefinition> waiterDefinition) { String waiterMethodName = waiterDefinition.getKey(); OperationModel opModel = operationModel(waiterDefinition.getValue()); ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType()); MethodSpec.Builder builder = methodSignatureWithReturnType(waiterMethodName, opModel) .addParameter(requestType, opModel.getInput().getVariableName()) .addModifiers(PUBLIC) .addAnnotation(Override.class) .addStatement("return $L.$L(() -> client.$N(applyWaitersUserAgent($N)))", waiterFieldName(waiterMethodName), waiterClassName.simpleName().equals("Waiter") ? "run" : "runAsync", lowercaseFirstChar(waiterDefinition.getValue().getOperation()), opModel.getInput().getVariableName()); return builder.build(); } private List<MethodSpec> waiterAcceptorInitializers() { List<MethodSpec> initializers = new ArrayList<>(); waiters.forEach((k, v) -> initializers.add(acceptorInitializer(k, v))); return initializers; } private MethodSpec acceptorInitializer(String waiterKey, WaiterDefinition waiterDefinition) { MethodSpec.Builder acceptorsMethod = MethodSpec.methodBuilder(waiterFieldName(waiterKey) + "Acceptors") .addModifiers(PRIVATE, STATIC) .returns(waiterAcceptorTypeName(waiterDefinition)); acceptorsMethod.addStatement("$T result = new $T<>()", waiterAcceptorTypeName(waiterDefinition), ArrayList.class); for (Acceptor acceptor : waiterDefinition.getAcceptors()) { acceptorsMethod.addCode("result.add(") .addCode(acceptor(acceptor)) .addCode(");"); } acceptorsMethod.addStatement("result.addAll($T.DEFAULT_ACCEPTORS)", waitersRuntimeClass()); acceptorsMethod.addStatement("return result"); return acceptorsMethod.build(); } protected String waiterFieldName(String waiterKey) { return lowercaseFirstChar(waiterKey) + "Waiter"; } private OperationModel operationModel(WaiterDefinition waiterDefinition) { return model.getOperation(waiterDefinition.getOperation()); } private MethodSpec.Builder methodSignatureWithReturnType(String waiterMethodName, OperationModel opModel) { return MethodSpec.methodBuilder(getWaiterMethodName(waiterMethodName)) .returns(getWaiterResponseType(opModel)); } static MethodSpec applyWaitersUserAgentMethod(PoetExtension poetExtensions, IntermediateModel model) { TypeVariableName typeVariableName = TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName())); ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName .get(ClassName.get(Consumer.class), ClassName.get(AwsRequestOverrideConfiguration.Builder.class)); CodeBlock codeBlock = CodeBlock.builder() .addStatement("$T userAgentApplier = b -> b.addApiName($T.builder().version" + "($S).name($S).build())", parameterizedTypeName, ApiName.class, WAITERS_USER_AGENT, "hll") .addStatement("$T overrideConfiguration =\n" + " request.overrideConfiguration().map(c -> c.toBuilder()" + ".applyMutation" + "(userAgentApplier).build())\n" + " .orElse((AwsRequestOverrideConfiguration.builder()" + ".applyMutation" + "(userAgentApplier).build()))", AwsRequestOverrideConfiguration.class) .addStatement("return (T) request.toBuilder().overrideConfiguration" + "(overrideConfiguration).build()") .build(); return MethodSpec.methodBuilder("applyWaitersUserAgent") .addModifiers(Modifier.PRIVATE) .addParameter(typeVariableName, "request") .addTypeVariable(typeVariableName) .addCode(codeBlock) .returns(typeVariableName) .build(); } private String getWaiterMethodName(String waiterMethodName) { return "waitUntil" + waiterMethodName; } private TypeName waiterAcceptorTypeName(WaiterDefinition waiterDefinition) { WildcardTypeName wildcardTypeName = WildcardTypeName.supertypeOf(fullyQualifiedResponseType(waiterDefinition)); return ParameterizedTypeName.get(ClassName.get(List.class), ParameterizedTypeName.get(ClassName.get(WaiterAcceptor.class), wildcardTypeName)); } private TypeName fullyQualifiedResponseType(WaiterDefinition waiterDefinition) { String modelPackage = model.getMetadata().getFullModelPackageName(); String operationResponseType = model.getOperation(waiterDefinition.getOperation()).getReturnType().getReturnType(); return ClassName.get(modelPackage, operationResponseType); } private CodeBlock acceptor(Acceptor acceptor) { CodeBlock.Builder result = CodeBlock.builder(); switch (acceptor.getState()) { case "success": result.add("$T.success", WaiterAcceptor.class); break; case "failure": result.add("$T.error", WaiterAcceptor.class); break; case "retry": result.add("$T.retry", WaiterAcceptor.class); break; default: throw new IllegalArgumentException("Unsupported acceptor state: " + acceptor.getState()); } switch (acceptor.getMatcher()) { case "path": result.add("OnResponseAcceptor("); result.add(pathAcceptorBody(acceptor)); result.add(")"); break; case "pathAll": result.add("OnResponseAcceptor("); result.add(pathAllAcceptorBody(acceptor)); result.add(")"); break; case "pathAny": result.add("OnResponseAcceptor("); result.add(pathAnyAcceptorBody(acceptor)); result.add(")"); break; case "status": // Note: Ignores the result we've built so far because this uses a special acceptor implementation. int expected = Integer.parseInt(acceptor.getExpected().asText()); return CodeBlock.of("new $T($L, $T.$L)", waitersRuntimeClass().nestedClass("ResponseStatusAcceptor"), expected, WaiterState.class, waiterState(acceptor)); case "error": result.add("OnExceptionAcceptor("); result.add(errorAcceptorBody(acceptor)); result.add(")"); break; default: throw new IllegalArgumentException("Unsupported acceptor matcher: " + acceptor.getMatcher()); } return result.build(); } private String waiterState(Acceptor acceptor) { switch (acceptor.getState()) { case "success": return WaiterState.SUCCESS.name(); case "failure": return WaiterState.FAILURE.name(); case "retry": return WaiterState.RETRY.name(); default: throw new IllegalArgumentException("Unsupported acceptor state: " + acceptor.getState()); } } private CodeBlock pathAcceptorBody(Acceptor acceptor) { String expected = acceptor.getExpected().asText(); String expectedType = acceptor.getExpected() instanceof JrsString ? "$S" : "$L"; return CodeBlock.builder() .add("response -> {") .add("$1T input = new $1T(response);", waitersRuntimeClass().nestedClass("Value")) .add("return $T.equals(", Objects.class) .add(jmesPathAcceptorGenerator.interpret(acceptor.getArgument(), "input")) .add(".value(), " + expectedType + ");", expected) .add("}") .build(); } private CodeBlock pathAllAcceptorBody(Acceptor acceptor) { String expected = acceptor.getExpected().asText(); String expectedType = acceptor.getExpected() instanceof JrsString ? "$S" : "$L"; return CodeBlock.builder() .add("response -> {") .add("$1T input = new $1T(response);", waitersRuntimeClass().nestedClass("Value")) .add("$T<$T> resultValues = ", List.class, Object.class) .add(jmesPathAcceptorGenerator.interpret(acceptor.getArgument(), "input")) .add(".values();") .add("return !resultValues.isEmpty() && " + "resultValues.stream().allMatch(v -> $T.equals(v, " + expectedType + "));", Objects.class, expected) .add("}") .build(); } private CodeBlock pathAnyAcceptorBody(Acceptor acceptor) { String expected = acceptor.getExpected().asText(); String expectedType = acceptor.getExpected() instanceof JrsString ? "$S" : "$L"; return CodeBlock.builder() .add("response -> {") .add("$1T input = new $1T(response);", waitersRuntimeClass().nestedClass("Value")) .add("$T<$T> resultValues = ", List.class, Object.class) .add(jmesPathAcceptorGenerator.interpret(acceptor.getArgument(), "input")) .add(".values();") .add("return !resultValues.isEmpty() && " + "resultValues.stream().anyMatch(v -> $T.equals(v, " + expectedType + "));", Objects.class, expected) .add("}") .build(); } private CodeBlock errorAcceptorBody(Acceptor acceptor) { String expected = acceptor.getExpected().asText(); String expectedType = acceptor.getExpected() instanceof JrsString ? "$S" : "$L"; return CodeBlock.of("error -> $T.equals(errorCode(error), " + expectedType + ")", Objects.class, expected); } private MethodSpec staticErrorCodeMethod() { return MethodSpec.methodBuilder("errorCode") .addModifiers(PRIVATE, STATIC) .returns(String.class) .addParameter(Throwable.class, "error") .addCode("if (error instanceof $T) {", AwsServiceException.class) .addCode("return (($T) error).awsErrorDetails().errorCode();", AwsServiceException.class) .addCode("}") .addCode("return null;") .build(); } private ClassName waitersRuntimeClass() { return ClassName.get(model.getMetadata().getFullWaitersInternalPackageName(), WaitersRuntimeGeneratorTask.RUNTIME_CLASS_NAME); } }
3,417
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/waiters/AsyncWaiterInterfaceSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.docs.WaiterDocs; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.core.waiters.WaiterResponse; public final class AsyncWaiterInterfaceSpec extends BaseWaiterInterfaceSpec { private final IntermediateModel model; private final PoetExtension poetExtensions; private final ClassName className; private final String modelPackage; public AsyncWaiterInterfaceSpec(IntermediateModel model) { super(model); this.modelPackage = model.getMetadata().getFullModelPackageName(); this.model = model; this.poetExtensions = new PoetExtension(model); this.className = poetExtensions.getAsyncWaiterInterface(); } @Override protected ClassName waiterImplName() { return poetExtensions.getAsyncWaiterClass(); } @Override protected ClassName clientClassName() { return poetExtensions.getClientClass(model.getMetadata().getAsyncInterface()); } @Override public ClassName className() { return className; } @Override protected ParameterizedTypeName getWaiterResponseType(OperationModel opModel) { ClassName pojoResponse = ClassName.get(modelPackage, opModel.getReturnType().getReturnType()); ParameterizedTypeName waiterResponse = ParameterizedTypeName.get(ClassName.get(WaiterResponse.class), pojoResponse); return ParameterizedTypeName.get(ClassName.get(CompletableFuture.class), waiterResponse); } @Override protected void additionalBuilderTypeSpecModification(TypeSpec.Builder type) { type.addMethod(MethodSpec.methodBuilder("scheduledExecutorService") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addParameter(ClassName.get(ScheduledExecutorService.class), "executorService") .addJavadoc(WaiterDocs.waiterBuilderScheduledExecutorServiceJavadoc()) .returns(className().nestedClass("Builder")) .build()); } }
3,418
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/common/AbstractEnumClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.STATIC; import static software.amazon.awssdk.codegen.poet.PoetUtils.createEnumBuilder; import static software.amazon.awssdk.codegen.poet.PoetUtils.toStringBuilder; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeSpec.Builder; import java.util.EnumSet; import java.util.Map; import java.util.Set; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.utils.internal.EnumUtils; public abstract class AbstractEnumClass implements ClassSpec { private static final String VALUE = "value"; private static final String VALUE_MAP = "VALUE_MAP"; private static final String UNKNOWN_TO_SDK_VERSION = "UNKNOWN_TO_SDK_VERSION"; private final ShapeModel shape; public AbstractEnumClass(ShapeModel shape) { this.shape = shape; } @Override public final TypeSpec poetSpec() { Builder enumBuilder = createEnumBuilder(className()) .addField(valueMapField()) .addField(String.class, VALUE, Modifier.PRIVATE, Modifier.FINAL) .addMethod(toStringBuilder().addStatement("return $T.valueOf($N)", String.class, VALUE).build()) .addMethod(fromValueSpec()) .addMethod(knownValuesSpec()) .addMethod(createConstructor()); addDeprecated(enumBuilder); addJavadoc(enumBuilder); addEnumConstants(enumBuilder); enumBuilder.addEnumConstant(UNKNOWN_TO_SDK_VERSION, TypeSpec.anonymousClassBuilder("null").build()); return enumBuilder.build(); } protected final ShapeModel getShape() { return shape; } protected abstract void addDeprecated(Builder enumBuilder); protected abstract void addJavadoc(Builder enumBuilder); protected abstract void addEnumConstants(Builder enumBuilder); private FieldSpec valueMapField() { ParameterizedTypeName mapType = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), className()); return FieldSpec.builder(mapType, VALUE_MAP) .addModifiers(PRIVATE, STATIC, FINAL) .initializer("$1T.uniqueIndex($2T.class, $2T::toString)", EnumUtils.class, className()) .build(); } private MethodSpec createConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(String.class, VALUE) .addStatement("this.$1N = $1N", VALUE) .build(); } private MethodSpec fromValueSpec() { return MethodSpec.methodBuilder("fromValue") .returns(className()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc("Use this in place of valueOf to convert the raw string returned by the service into the " + "enum value.\n\n" + "@param $N real value\n" + "@return $T corresponding to the value\n", VALUE, className()) .addParameter(String.class, VALUE) .beginControlFlow("if ($N == null)", VALUE) .addStatement("return null") .endControlFlow() .addStatement("return $N.getOrDefault($N, $N)", VALUE_MAP, VALUE, UNKNOWN_TO_SDK_VERSION) .build(); } private MethodSpec knownValuesSpec() { return MethodSpec.methodBuilder("knownValues") .returns(ParameterizedTypeName.get(ClassName.get(Set.class), className())) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addJavadoc("Use this in place of {@link #values()} to return a {@link Set} of all values known to the " + "SDK.\n" + "This will return all known enum values except {@link #$N}.\n\n" + "@return a {@link $T} of known {@link $T}s", UNKNOWN_TO_SDK_VERSION, Set.class, className()) .addStatement("$1T<$2T> knownValues = $3T.allOf($2T.class)", Set.class, className(), EnumSet.class) .addStatement("knownValues.remove($N)", UNKNOWN_TO_SDK_VERSION) .addStatement("return knownValues") .build(); } }
3,419
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/common/UserAgentUtilsSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import java.util.function.Consumer; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; 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.core.ApiName; import software.amazon.awssdk.core.util.VersionInfo; public class UserAgentUtilsSpec implements ClassSpec { private static final String PAGINATOR_USER_AGENT = "PAGINATED"; protected final IntermediateModel model; protected final PoetExtension poetExtensions; public UserAgentUtilsSpec(IntermediateModel model) { this.model = model; this.poetExtensions = new PoetExtension(model); } @Override public TypeSpec poetSpec() { return TypeSpec.classBuilder(className()) .addModifiers(Modifier.PUBLIC) .addAnnotation(PoetUtils.generatedAnnotation()) .addAnnotation(SdkInternalApi.class) .addMethod(privateConstructor()) .addMethod(applyUserAgentInfoMethod()) .addMethod(applyPaginatorUserAgentMethod()) .build(); } @Override public ClassName className() { return poetExtensions.getUserAgentClass(); } protected MethodSpec privateConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build(); } private MethodSpec applyUserAgentInfoMethod() { TypeVariableName typeVariableName = TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName())); ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName .get(ClassName.get(Consumer.class), ClassName.get(AwsRequestOverrideConfiguration.Builder.class)); CodeBlock codeBlock = CodeBlock.builder() .addStatement("$T overrideConfiguration =\n" + " request.overrideConfiguration().map(c -> c.toBuilder()" + ".applyMutation" + "(userAgentApplier).build())\n" + " .orElse((AwsRequestOverrideConfiguration.builder()" + ".applyMutation" + "(userAgentApplier).build()))", AwsRequestOverrideConfiguration.class) .addStatement("return (T) request.toBuilder().overrideConfiguration" + "(overrideConfiguration).build()") .build(); return MethodSpec.methodBuilder("applyUserAgentInfo") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(typeVariableName, "request") .addParameter(parameterizedTypeName, "userAgentApplier") .addTypeVariable(typeVariableName) .addCode(codeBlock) .returns(typeVariableName) .build(); } private MethodSpec applyPaginatorUserAgentMethod() { TypeVariableName typeVariableName = TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName())); return MethodSpec.methodBuilder("applyPaginatorUserAgent") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(typeVariableName, "request") .addTypeVariable(typeVariableName) .addStatement("return applyUserAgentInfo(request, b -> b.addApiName($T.builder()" + ".version($T.SDK_VERSION)" + ".name($S)" + ".build()))", ApiName.class, VersionInfo.class, PAGINATOR_USER_AGENT) .returns(typeVariableName) .build(); } }
3,420
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/common/EnumClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeSpec.Builder; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.poet.PoetUtils; public final class EnumClass extends AbstractEnumClass { private final String enumPackageName; public EnumClass(String enumPackage, ShapeModel shape) { super(shape); this.enumPackageName = enumPackage; } @Override protected void addDeprecated(Builder enumBuilder) { PoetUtils.addDeprecated(enumBuilder::addAnnotation, getShape()); } @Override protected void addJavadoc(Builder enumBuilder) { PoetUtils.addJavadoc(enumBuilder::addJavadoc, getShape()); } @Override protected void addEnumConstants(Builder enumBuilder) { getShape().getEnums().forEach( e -> enumBuilder.addEnumConstant(e.getName(), TypeSpec.anonymousClassBuilder("$S", e.getValue()).build()) ); } @Override public ClassName className() { return ClassName.get(enumPackageName, getShape().getShapeName()); } }
3,421
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/model/MapSetters.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import java.util.ArrayList; import java.util.Collections; import java.util.List; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; class MapSetters extends AbstractMemberSetters { private final TypeProvider typeProvider; MapSetters(IntermediateModel intermediateModel, ShapeModel shapeModel, MemberModel memberModel, TypeProvider typeProvider) { super(intermediateModel, shapeModel, memberModel, typeProvider); this.typeProvider = typeProvider; } @Override public List<MethodSpec> fluentDeclarations(TypeName returnType) { List<MethodSpec> fluentDeclarations = new ArrayList<>(); fluentDeclarations.add(fluentAbstractSetterDeclaration(memberAsParameter(), returnType) .addJavadoc("$L", memberModel().getFluentSetterDocumentation()) .build()); if (Utils.isMapWithEnumShape(memberModel())) { fluentDeclarations.add(fluentAbstractSetterDeclaration(memberModel().getFluentEnumGetterMethodName(), mapWithEnumAsParameter(), returnType) .addJavadoc("$L", memberModel().getFluentSetterDocumentation()) .build()); } return fluentDeclarations; } @Override public List<MethodSpec> fluent(TypeName returnType) { List<MethodSpec> fluent = new ArrayList<>(); fluent.add(fluentSetterBuilder(returnType).addCode(copySetterBody() .toBuilder() .addStatement("return this") .build()) .build()); if (Utils.isMapWithEnumShape(memberModel())) { fluent.add(fluentSetterBuilder(memberModel().getFluentEnumGetterMethodName(), mapWithEnumAsParameter(), returnType) .addCode(copySetterBodyWithModeledEnumParameter()) .addStatement("return this") .build()); } return fluent; } @Override public List<MethodSpec> beanStyle() { MethodSpec.Builder builder = beanStyleSetterBuilder(); builder.addCode(beanCopySetterBody()); return Collections.singletonList(builder.build()); } private ParameterSpec mapWithEnumAsParameter() { return ParameterSpec.builder(typeProvider.parameterType(memberModel(), true), fieldName()) .build(); } }
3,422
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/model/EventModelBuilderSpecs.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Collections; import java.util.List; 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.poet.PoetExtension; public class EventModelBuilderSpecs { private final ClassName eventClassName; private final ShapeModelSpec shapeModelSpec; public EventModelBuilderSpecs(IntermediateModel intermediateModel, MemberModel eventModel, ClassName eventClassName, TypeProvider typeProvider) { this.eventClassName = eventClassName; this.shapeModelSpec = new ShapeModelSpec(eventModel.getShape(), typeProvider, new PoetExtension(intermediateModel), intermediateModel); } public ClassName builderInterfaceName() { return classToBuild().nestedClass("Builder"); } public ClassName builderImplName() { return classToBuild().nestedClass("BuilderImpl"); } public TypeSpec builderInterface() { TypeSpec.Builder builder = TypeSpec.interfaceBuilder(builderInterfaceName()) .addSuperinterfaces(superInterfaces()) .addModifiers(Modifier.PUBLIC); builder.addMethod(MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addAnnotation(Override.class) .returns(eventClassName) .build()); return builder.build(); } public TypeSpec beanStyleBuilder() { return TypeSpec.classBuilder(builderImplName()) .addSuperinterfaces(Collections.singletonList(builderInterfaceName())) .superclass(superClass()) .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .addMethod(noArgCConstructor()) .addMethod(fromEventConstructor()) .addMethod(buildMethod()) .build(); } private ClassName classToBuild() { return eventClassName; } private ClassName baseEventClassName() { return shapeModelSpec.className(); } private List<TypeName> superInterfaces() { return Collections.singletonList(baseEventClassName().nestedClass("Builder")); } private TypeName superClass() { return baseEventClassName().nestedClass("BuilderImpl"); } private MethodSpec buildMethod() { return MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addStatement("return new $T(this)", classToBuild()) .returns(classToBuild()) .build(); } private MethodSpec noArgCConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build(); } private MethodSpec fromEventConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(classToBuild(), "event") .addStatement("super(event)") .build(); } }
3,423
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/model/ResponseMetadataSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.awscore.AwsResponseMetadata; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; 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.utils.CollectionUtils; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.internal.CodegenNamingUtils; /** * Generate ResponseMetadata class */ public class ResponseMetadataSpec implements ClassSpec { private PoetExtension poetExtensions; private Map<String, String> headerMetadata = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); public ResponseMetadataSpec(IntermediateModel model) { if (!CollectionUtils.isNullOrEmpty(model.getCustomizationConfig().getCustomResponseMetadata())) { this.headerMetadata.putAll(model.getCustomizationConfig().getCustomResponseMetadata()); } this.poetExtensions = new PoetExtension(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder specBuilder = TypeSpec.classBuilder(className()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(PoetUtils.generatedAnnotation()) .addAnnotation(SdkPublicApi.class) .superclass(AwsResponseMetadata.class) .addMethod(constructor()) .addMethod(staticFactoryMethod()) .addMethods(metadataMethods()); List<FieldSpec> fields = headerMetadata.entrySet().stream().map(e -> FieldSpec.builder(String.class, e.getKey()) .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("$S", e.getValue()) .build() ).collect(Collectors.toList()); specBuilder.addFields(fields); return specBuilder.build(); } private MethodSpec constructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(AwsResponseMetadata.class, "responseMetadata") .addStatement("super(responseMetadata)") .build(); } private MethodSpec staticFactoryMethod() { return MethodSpec.methodBuilder("create") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(AwsResponseMetadata.class, "responseMetadata") .addStatement("return new $T(responseMetadata)", className()) .returns(className()) .build(); } private List<MethodSpec> metadataMethods() { return headerMetadata.keySet() .stream() .map(key -> { String methodName = convertMethodName(key); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName) .addModifiers(Modifier.PUBLIC) .addStatement("return getValue($L)", key) .returns(String.class); if (methodName.equals("requestId")) { methodBuilder.addAnnotation(Override.class); } return methodBuilder.build(); }).collect(Collectors.toList()); } /** * Convert key (UPPER_CASE) to method name. */ private String convertMethodName(String key) { String pascalCase = CodegenNamingUtils.pascalCase(key); return StringUtils.uncapitalize(pascalCase); } @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } }
3,424
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/model/NonCollectionSetters.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 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.TypeName; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.model.config.customization.ConvenienceTypeOverload; 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.poet.PoetUtils; import software.amazon.awssdk.utils.StringUtils; class NonCollectionSetters extends AbstractMemberSetters { NonCollectionSetters(IntermediateModel intermediateModel, ShapeModel shapeModel, MemberModel memberModel, TypeProvider typeProvider) { super(intermediateModel, shapeModel, memberModel, typeProvider); } @Override public List<MethodSpec> fluentDeclarations(TypeName returnType) { List<MethodSpec> fluentDeclarations = new ArrayList<>(); fluentDeclarations.add(fluentAbstractSetterDeclaration(memberAsParameter(), returnType) .addJavadoc("$L", memberModel().getFluentSetterDocumentation()) .build()); if (memberModel().getEnumType() != null) { fluentDeclarations.add(fluentAbstractSetterDeclaration(modeledParam(), returnType) .addJavadoc("$L", memberModel().getFluentSetterDocumentation()) .build()); } if (memberModel().getDeprecatedName() != null) { MethodSpec.Builder builder = fluentAbstractSetterDeclaration( memberModel().getDeprecatedFluentSetterMethodName(), memberAsParameter(), returnType); fluentDeclarations.add(builder .addJavadoc("$L", memberModel().getDeprecatedSetterDocumentation()) .addAnnotation(Deprecated.class) .build()); } if (memberModel().hasBuilder()) { fluentDeclarations.add(fluentConsumerFluentSetter(returnType)); } return fluentDeclarations; } @Override public List<MethodSpec> fluent(TypeName returnType) { List<MethodSpec> fluentSetters = new ArrayList<>(); fluentSetters.add(fluentAssignmentSetter(returnType)); if (memberModel().getEnumType() != null) { fluentSetters.add(fluentEnumToStringSetter(returnType)); } if (memberModel().getDeprecatedName() != null) { fluentSetters.add(fluentAssignmentSetter(memberModel().getDeprecatedFluentSetterMethodName(), returnType)); } return fluentSetters; } public MethodSpec convenienceDeclaration(TypeName returnType, ConvenienceTypeOverload overload) { return MethodSpec.methodBuilder(memberModel().getFluentSetterMethodName()) .addParameter(PoetUtils.classNameFromFqcn(overload.getConvenienceType()), memberAsParameter().name) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(returnType) .build(); } public MethodSpec fluentConvenience(TypeName returnType, ConvenienceTypeOverload overload) { return MethodSpec.methodBuilder(memberModel().getFluentSetterMethodName()) .addModifiers(Modifier.PUBLIC) .addParameter(PoetUtils.classNameFromFqcn(overload.getConvenienceType()), memberAsParameter().name) .addStatement("$L($T.instance().adapt($L))", memberModel().getFluentSetterMethodName(), PoetUtils.classNameFromFqcn(overload.getTypeAdapterFqcn()), memberAsParameter().name) .addStatement("return this") .returns(returnType) .build(); } @Override public List<MethodSpec> beanStyle() { List<MethodSpec> methods = new ArrayList<>(); methods.add(beanStyleSetterBuilder() .addCode(beanCopySetterBody()) .build()); if (StringUtils.isNotBlank(memberModel().getDeprecatedBeanStyleSetterMethodName())) { methods.add(deprecatedBeanStyleSetterBuilder() .addCode(beanCopySetterBody()) .addAnnotation(Deprecated.class) .addJavadoc("@deprecated Use {@link #" + memberModel().getBeanStyleSetterMethodName() + "} instead") .build()); } return methods; } private MethodSpec fluentAssignmentSetter(TypeName returnType) { return fluentSetterBuilder(returnType) .addCode(copySetterBody().toBuilder().addStatement("return this").build()) .build(); } private MethodSpec fluentAssignmentSetter(String methodName, TypeName returnType) { return fluentSetterBuilder(methodName, returnType) .addCode(copySetterBody().toBuilder().addStatement("return this").build()) .build(); } private MethodSpec fluentEnumToStringSetter(TypeName returnType) { return fluentSetterBuilder(modeledParam(), returnType) .addCode(enumToStringAssignmentBody().toBuilder().addStatement("return this").build()) .build(); } private MethodSpec fluentConsumerFluentSetter(TypeName returnType) { MemberModel memberModel = memberModel(); ClassName memberClass = poetExtensions.getModelClass(memberModel.getShape().getC2jName()); ClassName builderClass = memberClass.nestedClass("Builder"); return fluentDefaultSetterDeclaration(builderConsumerParam(builderClass), returnType) .addModifiers(Modifier.DEFAULT) .addStatement("return $N($T.builder().applyMutation($N).build())", memberModel.getFluentSetterMethodName(), memberClass, fieldName()) .addJavadoc("$L", memberModel.getDefaultConsumerFluentSetterDocumentation(memberModel.getVariable().getSimpleType())) .build(); } private CodeBlock enumToStringAssignmentBody() { return CodeBlock.builder() .addStatement("this.$N($N == null ? null : $N.toString())", memberModel().getFluentSetterMethodName(), fieldName(), fieldName()) .build(); } private ParameterSpec modeledParam() { return ParameterSpec.builder(poetExtensions.getModelClass(memberModel().getShape().getShapeName()), fieldName()).build(); } private ParameterSpec builderConsumerParam(ClassName builderClass) { return ParameterSpec.builder(ParameterizedTypeName.get(ClassName.get(Consumer.class), builderClass), fieldName()).build(); } }
3,425
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/model/EventModelSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.PUBLIC; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; 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.eventstream.EventStreamUtils; public final class EventModelSpec implements ClassSpec { private final MemberModel eventModel; private final ShapeModel eventStream; private final IntermediateModel intermediateModel; private final PoetExtension poetExtensions; private final ShapeModelSpec baseShapeModelSpec; private final TypeProvider typeProvider; private final EventStreamSpecHelper eventStreamSpecHelper; private final EventModelBuilderSpecs builderSpecs; public EventModelSpec(MemberModel eventModel, ShapeModel eventStream, IntermediateModel intermediateModel) { this.eventModel = eventModel; this.eventStream = eventStream; this.intermediateModel = intermediateModel; this.poetExtensions = new PoetExtension(intermediateModel); this.baseShapeModelSpec = new ShapeModelSpec(eventModel.getShape(), new TypeProvider(intermediateModel), poetExtensions, intermediateModel); this.typeProvider = new TypeProvider(intermediateModel); this.eventStreamSpecHelper = new EventStreamSpecHelper(eventStream, intermediateModel); this.builderSpecs = new EventModelBuilderSpecs(intermediateModel, eventModel, className(), typeProvider); } @Override public TypeSpec poetSpec() { return TypeSpec.classBuilder(className()) .superclass(baseShapeModelSpec.className()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(SdkInternalApi.class) .addAnnotation(PoetUtils.generatedAnnotation()) .addJavadoc(classJavadoc()) .addField(serialVersionUidField()) .addMethod(constructor()) .addMethod(toBuilderMethod()) .addMethod(builderMethod()) .addMethods(acceptMethods()) .addMethod(sdkEventTypeMethodSpec()) .addTypes(Arrays.asList(builderSpecs.builderInterface(), builderSpecs.beanStyleBuilder())) .build(); } private CodeBlock classJavadoc() { return CodeBlock.builder() .add("A specialization of {@code $L} that represents the {@code $L$$$L} event. Do not use this class " + "directly. Instead, use the static builder methods on {@link $L}.", baseShapeModelSpec.className(), eventStream.getC2jName(), eventModel.getC2jName(), poetExtensions.getModelClass(eventStream.getShapeName())) .build(); } private FieldSpec serialVersionUidField() { return FieldSpec.builder(long.class, "serialVersionUID", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("1L") .build(); } private MethodSpec constructor() { return MethodSpec.constructorBuilder() .addParameter(className().nestedClass("BuilderImpl"), "builderImpl") .addStatement("super($N)", "builderImpl") .build(); } private MethodSpec toBuilderMethod() { return MethodSpec.methodBuilder("toBuilder") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(builderSpecs.builderInterfaceName()) .addStatement("return new $T(this)", builderSpecs.builderImplName()) .build(); } private MethodSpec builderMethod() { return MethodSpec.methodBuilder("builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(builderSpecs.builderInterfaceName()) .addStatement("return new $T()", builderSpecs.builderImplName()) .build(); } private List<MethodSpec> acceptMethods() { return operationsUsingEventOnOutput().stream() .map(o -> { ClassName responseHandlerClass = poetExtensions.eventStreamResponseHandlerType(o); return acceptMethodSpec(responseHandlerClass); }) .collect(Collectors.toList()); } @Override public ClassName className() { return eventStreamSpecHelper.eventClassName(eventModel); } private List<OperationModel> operationsUsingEventOnOutput() { Collection<OperationModel> opModels = EventStreamUtils.findOperationsWithEventStream(intermediateModel, eventStream); return opModels.stream() .filter(opModel -> EventStreamUtils.doesShapeContainsEventStream(opModel.getOutputShape(), eventStream)) .collect(Collectors.toList()); } private MethodSpec acceptMethodSpec(ClassName responseHandlerClass) { String visitMethodName = eventStreamSpecHelper.visitMethodName(eventModel); return MethodSpec.methodBuilder("accept") .addModifiers(PUBLIC) .addAnnotation(Override.class) .addParameter(responseHandlerClass .nestedClass("Visitor"), "visitor") .addStatement("visitor.$N(this)", visitMethodName) .build(); } private MethodSpec sdkEventTypeMethodSpec() { ClassName eventTypeEnumClass = eventStreamSpecHelper.eventTypeEnumClassName(); String eventTypeValue = eventStreamSpecHelper.eventTypeEnumValue(eventModel); return MethodSpec.methodBuilder("sdkEventType") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(eventTypeEnumClass) .addStatement("return $T.$N", eventTypeEnumClass, eventTypeValue) .build(); } }
3,426
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/model/DeprecationUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.codegen.internal.Constant.LF; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.MethodSpec; import java.util.List; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.utils.StringUtils; public final class DeprecationUtils { private static final AnnotationSpec DEPRECATED = AnnotationSpec.builder(Deprecated.class).build(); private DeprecationUtils() { } /** * If a given member is modeled as deprecated, add the {@link Deprecated} annotation to the method and, if the method * already has existing Javadoc, append a section with the {@code @deprecated} tag. */ public static MethodSpec checkDeprecated(MemberModel member, MethodSpec method) { if (!member.isDeprecated() || method.annotations.contains(DEPRECATED)) { return method; } MethodSpec.Builder builder = method.toBuilder().addAnnotation(DEPRECATED); if (!method.javadoc.isEmpty()) { builder.addJavadoc(LF + "@deprecated"); if (StringUtils.isNotBlank(member.getDeprecatedMessage())) { builder.addJavadoc(" $L", member.getDeprecatedMessage()); } } return builder.build(); } /** * If a given operation is modeled as deprecated, add the {@link Deprecated} annotation to the method and, if the method * already has existing Javadoc, append a section with the {@code @deprecated} tag. */ public static MethodSpec checkDeprecated(OperationModel operation, MethodSpec method) { if (!operation.isDeprecated() || method.annotations.contains(DEPRECATED)) { return method; } MethodSpec.Builder builder = method.toBuilder().addAnnotation(DEPRECATED); if (!method.javadoc.isEmpty()) { builder.addJavadoc(LF + "@deprecated"); if (StringUtils.isNotBlank(operation.getDeprecatedMessage())) { builder.addJavadoc(" $L", operation.getDeprecatedMessage()); } } return builder.build(); } public static List<MethodSpec> checkDeprecated(MemberModel member, List<MethodSpec> methods) { return methods.stream().map(methodSpec -> checkDeprecated(member, methodSpec)).collect(toList()); } }
3,427
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/model/BeanGetterHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.model.TypeProvider.ShapeTransformation.USE_BUILDER; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.model.TypeProvider.TypeNameOptions; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.util.SdkAutoConstructList; import software.amazon.awssdk.core.util.SdkAutoConstructMap; public final class BeanGetterHelper { private final PoetExtension poetExtensions; private final ServiceModelCopiers copiers; private final TypeProvider typeProvider; public BeanGetterHelper(PoetExtension poetExtensions, ServiceModelCopiers copiers, TypeProvider typeProvider) { this.poetExtensions = poetExtensions; this.copiers = copiers; this.typeProvider = typeProvider; } public MethodSpec beanStyleGetter(MemberModel memberModel) { if (memberModel.hasBuilder()) { return builderGetter(memberModel); } if (memberModel.containsBuildable()) { return buildableContainerGetter(memberModel); } if (memberModel.isSdkBytesType()) { return byteBufferGetter(memberModel); } if (memberModel.isList() && memberModel.getListModel().getListMemberModel().isSdkBytesType()) { return listByteBufferGetter(memberModel); } if (memberModel.isMap() && memberModel.getMapModel().getValueModel().isSdkBytesType()) { return mapByteBufferGetter(memberModel); } return regularGetter(memberModel); } private MethodSpec buildableContainerGetter(MemberModel memberModel) { TypeName returnType = typeProvider.typeName(memberModel, new TypeNameOptions().shapeTransformation(USE_BUILDER) .useByteBufferTypes(true)); ClassName copierClass = copiers.copierClassFor(memberModel) .orElseThrow(() -> new IllegalStateException("Copier class not found for " + memberModel)); String variableName = memberModel.getVariable().getVariableName(); CodeBlock.Builder code = CodeBlock.builder(); code.add("$T result = $T.$N(this.$N);", returnType, copierClass, copiers.copyToBuilderMethodName(), variableName); if (memberModel.isList()) { code.add("if (result instanceof $T) {", SdkAutoConstructList.class) .add("return null;") .add("}"); } if (memberModel.isMap()) { code.add("if (result instanceof $T) {", SdkAutoConstructMap.class) .add("return null;") .add("}"); } code.add("return result;"); return MethodSpec.methodBuilder(memberModel.getBeanStyleGetterMethodName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(returnType) .addCode(code.build()) .build(); } private MethodSpec byteBufferGetter(MemberModel memberModel) { return basicGetter(memberModel, ClassName.get(ByteBuffer.class), CodeBlock.of("return $1N == null ? null : $1N.asByteBuffer();", memberModel.getVariable().getVariableName())); } private MethodSpec listByteBufferGetter(MemberModel memberModel) { return basicGetter(memberModel, ParameterizedTypeName.get(List.class, ByteBuffer.class), CodeBlock.of("return $1N == null ? null : $1N.stream().map($2T::asByteBuffer).collect($3T.toList());", memberModel.getVariable().getVariableName(), SdkBytes.class, Collectors.class)); } private MethodSpec mapByteBufferGetter(MemberModel memberModel) { String body = "return $1N == null ? null : " + "$1N.entrySet().stream().collect($2T.toMap(e -> e.getKey(), e -> e.getValue().asByteBuffer()));"; String keyType = memberModel.getMapModel().getKeyModel().getVariable().getVariableType(); return basicGetter(memberModel, PoetUtils.createParameterizedTypeName(Map.class, keyType, ByteBuffer.class.getSimpleName()), CodeBlock.of(body, memberModel.getVariable().getVariableName(), Collectors.class)); } private MethodSpec regularGetter(MemberModel memberModel) { return basicGetter(memberModel, typeProvider.parameterType(memberModel), CodeBlock.of("return $N;", memberModel.getVariable().getVariableName())); } private MethodSpec builderGetter(MemberModel memberModel) { return basicGetter(memberModel, poetExtensions.getModelClass(memberModel.getC2jShape()).nestedClass("Builder"), CodeBlock.of("return $1N != null ? $1N.toBuilder() : null;", memberModel.getVariable().getVariableName())); } private MethodSpec basicGetter(MemberModel memberModel, TypeName returnType, CodeBlock body) { CodeBlock.Builder getterBody = CodeBlock.builder(); memberModel.getAutoConstructClassIfExists().ifPresent(autoConstructClass -> { getterBody.add("if ($N instanceof $T) {", memberModel.getVariable().getVariableName(), autoConstructClass) .add("return null;") .add("}"); }); getterBody.add(body); return MethodSpec.methodBuilder(memberModel.getBeanStyleGetterMethodName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(returnType) .addCode(getterBody.build()) .build(); } }
3,428
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/model/MemberCopierSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.model.TypeProvider.ShapeTransformation.NONE; import static software.amazon.awssdk.codegen.poet.model.TypeProvider.ShapeTransformation.USE_BUILDER; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.intermediate.MapModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; 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.StaticImport; import software.amazon.awssdk.codegen.poet.model.TypeProvider.TypeNameOptions; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructList; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructMap; import software.amazon.awssdk.core.util.SdkAutoConstructList; import software.amazon.awssdk.core.util.SdkAutoConstructMap; class MemberCopierSpec implements ClassSpec { private final MemberModel memberModel; private final ServiceModelCopiers serviceModelCopiers; private final TypeProvider typeProvider; private final PoetExtension poetExtensions; private enum EnumTransform { /** Copy enums as strings */ STRING_TO_ENUM, /** Copy strings as enums */ ENUM_TO_STRING, /** Copy without a transformation */ NONE } private enum BuilderTransform { BUILDER_TO_BUILDABLE, BUILDABLE_TO_BUILDER, NONE } MemberCopierSpec(MemberModel memberModel, ServiceModelCopiers serviceModelCopiers, TypeProvider typeProvider, PoetExtension poetExtensions) { this.memberModel = memberModel; this.serviceModelCopiers = serviceModelCopiers; this.typeProvider = typeProvider; this.poetExtensions = poetExtensions; } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = TypeSpec.classBuilder(className()) .addModifiers(Modifier.FINAL) .addAnnotation(PoetUtils.generatedAnnotation()) .addMethod(copyMethod()); if (memberModel.containsBuildable()) { builder.addMethod(copyFromBuilderMethod()); builder.addMethod(copyToBuilderMethod()); } // If this is a collection, and it contains enums, or recursively // contains enums, add extra methods for copying the elements from an // enum to string and vice versa if (isEnumCopyAvailable(memberModel)) { builder.addMethod(enumToStringCopyMethod()); builder.addMethod(stringToEnumCopyMethod()); } return builder.build(); } @Override public ClassName className() { return serviceModelCopiers.copierClassFor(memberModel).get(); } @Override public Iterable<StaticImport> staticImports() { if (memberModel.isList()) { return Collections.singletonList(StaticImport.staticMethodImport(Collectors.class, "toList")); } if (memberModel.isMap()) { return Collections.singletonList(StaticImport.staticMethodImport(Collectors.class, "toMap")); } return Collections.emptyList(); } public static boolean isEnumCopyAvailable(MemberModel memberModel) { if (!(memberModel.isMap() || memberModel.isList())) { return false; } if (memberModel.isMap()) { MapModel mapModel = memberModel.getMapModel(); MemberModel keyModel = mapModel.getKeyModel(); MemberModel valueModel = mapModel.getValueModel(); if (keyModel.getEnumType() != null || valueModel.getEnumType() != null) { return true; } if (valueModel.isList() || valueModel.isMap()) { return isEnumCopyAvailable(valueModel); } // Keys are always simple, don't need to check } else { MemberModel element = memberModel.getListModel().getListMemberModel(); if (element.getEnumType() != null) { return true; } if (element.isList() || element.isMap()) { return isEnumCopyAvailable(element); } } return false; } private MethodSpec copyMethod() { return MethodSpec.methodBuilder(serviceModelCopiers.copyMethodName()) .addModifiers(Modifier.STATIC) .addParameter(typeName(memberModel, true, true, BuilderTransform.NONE, EnumTransform.NONE), memberParamName()) .returns(typeName(memberModel, false, false, BuilderTransform.NONE, EnumTransform.NONE)) .addCode(copyMethodBody(BuilderTransform.NONE, EnumTransform.NONE)) .build(); } private MethodSpec enumToStringCopyMethod() { return MethodSpec.methodBuilder(serviceModelCopiers.enumToStringCopyMethodName()) .addModifiers(Modifier.STATIC) .addParameter(typeName(memberModel, true, true, BuilderTransform.NONE, EnumTransform.ENUM_TO_STRING), memberParamName()) .returns(typeName(memberModel, false, false, BuilderTransform.NONE, EnumTransform.ENUM_TO_STRING)) .addCode(copyMethodBody(BuilderTransform.NONE, EnumTransform.ENUM_TO_STRING)) .build(); } private MethodSpec stringToEnumCopyMethod() { return MethodSpec.methodBuilder(serviceModelCopiers.stringToEnumCopyMethodName()) .addModifiers(Modifier.STATIC) .addParameter(typeName(memberModel, true, true, BuilderTransform.NONE, EnumTransform.STRING_TO_ENUM), memberParamName()) .returns(typeName(memberModel, false, false, BuilderTransform.NONE, EnumTransform.STRING_TO_ENUM)) .addCode(copyMethodBody(BuilderTransform.NONE, EnumTransform.STRING_TO_ENUM)) .build(); } private MethodSpec copyFromBuilderMethod() { return MethodSpec.methodBuilder(serviceModelCopiers.copyFromBuilderMethodName()) .addModifiers(Modifier.STATIC) .returns(typeName(memberModel, false, false, BuilderTransform.BUILDER_TO_BUILDABLE, EnumTransform.NONE)) .addParameter(typeName(memberModel, true, true, BuilderTransform.BUILDER_TO_BUILDABLE, EnumTransform.NONE), memberParamName()) .addCode(copyMethodBody(BuilderTransform.BUILDER_TO_BUILDABLE, EnumTransform.NONE)) .build(); } private MethodSpec copyToBuilderMethod() { return MethodSpec.methodBuilder(serviceModelCopiers.copyToBuilderMethodName()) .addModifiers(Modifier.STATIC) .returns(typeName(memberModel, false, false, BuilderTransform.BUILDABLE_TO_BUILDER, EnumTransform.NONE)) .addParameter(typeName(memberModel, true, true, BuilderTransform.BUILDABLE_TO_BUILDER, EnumTransform.NONE), memberParamName()) .addCode(copyMethodBody(BuilderTransform.BUILDABLE_TO_BUILDER, EnumTransform.NONE)) .build(); } private CodeBlock copyMethodBody(BuilderTransform builderTransform, EnumTransform enumTransform) { CodeBlock.Builder code = CodeBlock.builder(); if (!memberModel.getAutoConstructClassIfExists().isPresent()) { code.add("if ($N == null) {", memberParamName()) .add("return null;") .add("}"); } String outputVariable = copyMethodBody(code, builderTransform, new UniqueVariableSource(), enumTransform, memberParamName(), memberModel); code.add("return $N;", outputVariable); return code.build(); } private String copyMethodBody(CodeBlock.Builder code, BuilderTransform builderTransform, UniqueVariableSource variableSource, EnumTransform enumTransform, String inputVariableName, MemberModel inputMember) { if (inputMember.getEnumType() != null) { String outputVariableName = variableSource.getNew("result"); ClassName enumType = poetExtensions.getModelClass(inputMember.getEnumType()); switch (enumTransform) { case NONE: return inputVariableName; case ENUM_TO_STRING: code.add("$T $N = $N.toString();", String.class, outputVariableName, inputVariableName); return outputVariableName; case STRING_TO_ENUM: code.add("$1T $2N = $1T.fromValue($3N);", enumType, outputVariableName, inputVariableName); return outputVariableName; default: throw new IllegalStateException(); } } if (inputMember.isSimple()) { return inputVariableName; } if (inputMember.hasBuilder()) { switch (builderTransform) { case NONE: return inputVariableName; case BUILDER_TO_BUILDABLE: String buildableOutput = variableSource.getNew("member"); TypeName buildableOutputType = typeName(inputMember, false, false, builderTransform, enumTransform); code.add("$T $N = $N == null ? null : $N.build();", buildableOutputType, buildableOutput, inputVariableName, inputVariableName); return buildableOutput; case BUILDABLE_TO_BUILDER: String builderOutput = variableSource.getNew("member"); TypeName builderOutputType = typeName(inputMember, false, false, builderTransform, enumTransform); code.add("$T $N = $N == null ? null : $N.toBuilder();", builderOutputType, builderOutput, inputVariableName, inputVariableName); return builderOutput; default: throw new IllegalStateException(); } } if (inputMember.isList()) { String outputVariableName = variableSource.getNew("list"); String modifiableVariableName = variableSource.getNew("modifiableList"); MemberModel listEntryModel = inputMember.getListModel().getListMemberModel(); TypeName listType = typeName(inputMember, false, false, builderTransform, enumTransform); code.add("$T $N;", listType, outputVariableName) .add("if ($1N == null || $1N instanceof $2T) {", inputVariableName, SdkAutoConstructList.class) .add("$N = $T.getInstance();", outputVariableName, DefaultSdkAutoConstructList.class) .add("} else {") .add("$T $N = new $T<>();", listType, modifiableVariableName, ArrayList.class); String entryInputVariable = variableSource.getNew("entry"); code.add("$N.forEach($N -> {", inputVariableName, entryInputVariable); String entryOutputVariable = copyMethodBody(code, builderTransform, variableSource, enumTransform, entryInputVariable, listEntryModel); code.add("$N.add($N);", modifiableVariableName, entryOutputVariable) .add("});") .add("$N = $T.unmodifiableList($N);", outputVariableName, Collections.class, modifiableVariableName) .add("}"); return outputVariableName; } if (inputMember.isMap()) { String outputVariableName = variableSource.getNew("map"); String modifiableVariableName = variableSource.getNew("modifiableMap"); MemberModel keyModel = inputMember.getMapModel().getKeyModel(); MemberModel valueModel = inputMember.getMapModel().getValueModel(); TypeName keyType = typeName(keyModel, false, false, builderTransform, enumTransform); TypeName outputMapType = typeName(inputMember, false, false, builderTransform, enumTransform); code.add("$T $N;", outputMapType, outputVariableName) .add("if ($1N == null || $1N instanceof $2T) {", inputVariableName, SdkAutoConstructMap.class) .add("$N = $T.getInstance();", outputVariableName, DefaultSdkAutoConstructMap.class) .add("} else {") .add("$T $N = new $T<>();", outputMapType, modifiableVariableName, LinkedHashMap.class); String keyInputVariable = variableSource.getNew("key"); String valueInputVariable = variableSource.getNew("value"); code.add("$N.forEach(($N, $N) -> {", inputVariableName, keyInputVariable, valueInputVariable); String keyOutputVariable = copyMethodBody(code, builderTransform, variableSource, enumTransform, keyInputVariable, keyModel); String valueOutputVariable = copyMethodBody(code, builderTransform, variableSource, enumTransform, valueInputVariable, valueModel); if (keyModel.getEnumType() != null && !keyType.toString().equals("java.lang.String")) { // When enums are used as keys, drop any entries with unknown keys code.add("if ($N != $T.UNKNOWN_TO_SDK_VERSION) {", keyOutputVariable, keyType) .add("$N.put($N, $N);", modifiableVariableName, keyOutputVariable, valueOutputVariable) .add("}"); } else { code.add("$N.put($N, $N);", modifiableVariableName, keyOutputVariable, valueOutputVariable); } code.add("});") .add("$N = $T.unmodifiableMap($N);", outputVariableName, Collections.class, modifiableVariableName) .add("}"); return outputVariableName; } throw new UnsupportedOperationException("Unable to generate copier for member '" + inputMember + "'"); } private TypeName typeName(MemberModel model, boolean isInputType, boolean useCollectionForList, BuilderTransform builderTransform, EnumTransform enumTransform) { boolean useEnumTypes = (isInputType && enumTransform == EnumTransform.ENUM_TO_STRING) || (!isInputType && enumTransform == EnumTransform.STRING_TO_ENUM); boolean useBuilderTypes = (isInputType && builderTransform == BuilderTransform.BUILDER_TO_BUILDABLE) || (!isInputType && builderTransform == BuilderTransform.BUILDABLE_TO_BUILDER); return typeProvider.typeName(model, new TypeNameOptions().useEnumTypes(useEnumTypes) .shapeTransformation(useBuilderTypes ? USE_BUILDER : NONE) .useSubtypeWildcardsForCollections(isInputType) .useSubtypeWildcardsForBuilders(isInputType) .useCollectionForList(useCollectionForList)); } private String memberParamName() { if (memberModel.isSimple()) { return Utils.unCapitalize(memberModel.getVariable().getSimpleType()) + "Param"; } return Utils.unCapitalize(memberModel.getC2jShape()) + "Param"; } private static final class UniqueVariableSource { private final Map<String, Integer> suffixes = new HashMap<>(); private String getNew(String prefix) { return prefix + suffix(prefix); } private String suffix(String prefix) { Integer suffixNumber = suffixes.compute(prefix, (k, v) -> v == null ? 0 : v + 1); return suffixNumber == 0 ? "" : suffixNumber.toString(); } } }
3,429
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/model/ServiceClientConfigurationBuilderClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.model.ServiceClientConfigurationUtils.Field; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; public class ServiceClientConfigurationBuilderClass implements ClassSpec { private final ServiceClientConfigurationUtils utils; public ServiceClientConfigurationBuilderClass(IntermediateModel model) { this.utils = new ServiceClientConfigurationUtils(model); } @Override public ClassName className() { return utils.serviceClientConfigurationBuilderClassName(); } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = PoetUtils.createClassBuilder(className()) .addSuperinterface(utils.serviceClientConfigurationClassName().nestedClass("Builder")) .addModifiers(PUBLIC) .addAnnotation(SdkInternalApi.class); builder.addField(SdkClientConfiguration.Builder.class, "config", PRIVATE, FINAL); builder.addMethod(MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addStatement("this($T.builder())", SdkClientConfiguration.class) .build()); builder.addMethod(MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addParameter(SdkClientConfiguration.Builder.class, "config") .addStatement("this.config = config", SdkClientConfiguration.Builder.class) .build()); for (Field field : utils.serviceClientConfigurationFields()) { builder.addMethod(setterForField(field)); builder.addMethod(getterForField(field)); } builder.addMethod(MethodSpec.methodBuilder("build") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(utils.serviceClientConfigurationClassName()) .addStatement("return new $T(this)", utils.serviceClientConfigurationClassName()) .build()); return builder.build(); } private MethodSpec setterForField(Field field) { return field.configSetter() .toBuilder() .addAnnotation(Override.class) .build(); } private MethodSpec getterForField(Field field) { return field.configGetter() .toBuilder() .addAnnotation(Override.class) .build(); } }
3,430
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/model/MemberSetters.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import java.util.List; /** * Creates the methods for fluent and bean style member setters for a * {@link software.amazon.awssdk.codegen.model.intermediate.MemberModel}. */ interface MemberSetters { List<MethodSpec> fluentDeclarations(TypeName returnType); List<MethodSpec> fluent(TypeName returnType); List<MethodSpec> beanStyle(); }
3,431
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/model/ServiceModelCopiers.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import java.util.Collection; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetExtension; public class ServiceModelCopiers { private final IntermediateModel intermediateModel; private final PoetExtension poetExtensions; private final TypeProvider typeProvider; public ServiceModelCopiers(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; this.poetExtensions = new PoetExtension(intermediateModel); this.typeProvider = new TypeProvider(intermediateModel); } public Collection<ClassSpec> copierSpecs() { Map<ClassName, ClassSpec> memberSpecs = new HashMap<>(); allShapeMembers().values().stream() .filter(m -> !canCopyReference(m)) .map(m -> new MemberCopierSpec(m, this, typeProvider, poetExtensions)) .forEach(spec -> memberSpecs.put(spec.className(), spec)); return memberSpecs.values(); } public Optional<ClassName> copierClassFor(MemberModel memberModel) { if (canCopyReference(memberModel)) { return Optional.empty(); } // FIXME: Some services (Health) have shapes with names // that differ only in the casing of the first letter, and generating // classes for them breaks on case insensitive filesystems... String shapeName = memberModel.getC2jShape(); if (shapeName.substring(0, 1).toLowerCase(Locale.ENGLISH).equals(shapeName.substring(0, 1))) { shapeName = "_" + shapeName; } return Optional.of(poetExtensions.getModelClass(shapeName + "Copier")); } public String copyMethodName() { return "copy"; } public String enumToStringCopyMethodName() { return "copyEnumToString"; } public String stringToEnumCopyMethodName() { return "copyStringToEnum"; } public String copyFromBuilderMethodName() { return "copyFromBuilder"; } public String copyToBuilderMethodName() { return "copyToBuilder"; } private Map<String, MemberModel> allShapeMembers() { Map<String, MemberModel> shapeMembers = new HashMap<>(); intermediateModel.getShapes().values().stream() .flatMap(s -> s.getMembersAsMap().values().stream()) .forEach(m -> shapeMembers.put(m.getC2jShape(), m)); return shapeMembers; } private boolean canCopyReference(MemberModel m) { return !m.isList() && !m.isMap(); } }
3,432
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/model/EventStreamSpecHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.PUBLIC; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeSpec; import java.util.List; import java.util.Locale; import java.util.Map; 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.intermediate.ShapeModel; import software.amazon.awssdk.codegen.naming.NamingStrategy; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.eventstream.EventTypeEnumSpec; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.internal.CodegenNamingUtils; public final class EventStreamSpecHelper { private final ShapeModel eventStream; private final IntermediateModel intermediateModel; private final PoetExtension poetExtensions; public EventStreamSpecHelper(ShapeModel eventStream, IntermediateModel intermediateModel) { this.eventStream = eventStream; this.intermediateModel = intermediateModel; this.poetExtensions = new PoetExtension(intermediateModel); } public String visitMethodName(MemberModel event) { if (useLegacyGenerationScheme(event)) { return "visit"; } return "visit" + CodegenNamingUtils.pascalCase(event.getName()); } public String eventPackageName() { return intermediateModel.getMetadata().getFullModelPackageName() + "." + eventStream.getShapeName().toLowerCase(Locale.ENGLISH); } public boolean useLegacyGenerationScheme(MemberModel event) { Map<String, List<String>> useLegacyEventGenerationScheme = intermediateModel.getCustomizationConfig() .getUseLegacyEventGenerationScheme(); List<String> targetEvents = useLegacyEventGenerationScheme.get(eventStream.getC2jName()); if (targetEvents == null) { return false; } return targetEvents.stream().anyMatch(e -> e.equals(event.getC2jName())); } public ClassName eventClassName(MemberModel eventModel) { if (useLegacyGenerationScheme(eventModel)) { return poetExtensions.getModelClass(eventModel.getShape().getShapeName()); } String simpleName = "Default" + intermediateModel.getNamingStrategy().getShapeClassName(eventModel.getName()); return ClassName.get(eventPackageName(), simpleName); } public ClassName eventTypeEnumClassName() { return poetExtensions.getModelClass(eventStream.getShapeName()).nestedClass("EventType"); } public TypeSpec eventTypeEnumSpec() { return new EventTypeEnumSpec("", intermediateModel, eventStream) .poetSpec() .toBuilder() .addModifiers(PUBLIC, Modifier.STATIC) .build(); } public String eventTypeEnumValue(MemberModel eventModel) { NamingStrategy namingStrategy = intermediateModel.getNamingStrategy(); return namingStrategy.getEnumValueName(eventModel.getName()); } public String eventBuilderMethodName(MemberModel eventModel) { return String.format("%sBuilder", StringUtils.uncapitalize(eventModel.getName())); } public String eventConsumerName(MemberModel eventModel) { if (useLegacyGenerationScheme(eventModel)) { return "on" + eventModel.getShape().getShapeName(); } return "on" + eventModel.getName(); } }
3,433
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/model/ModelMethodOverrides.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import java.util.List; import java.util.Objects; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.poet.PoetCollectors; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.utils.ToString; /** * Creates the method specs for common method overrides for service models. */ public class ModelMethodOverrides { private final ClassName className; private final PoetExtension poetExtensions; public ModelMethodOverrides(ClassName className, PoetExtension poetExtensions) { this.className = className; this.poetExtensions = poetExtensions; } public MethodSpec equalsBySdkFieldsMethod(ShapeModel shapeModel) { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("equalsBySdkFields") .returns(boolean.class) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(Object.class, "obj") .beginControlFlow("if (this == obj)") .addStatement("return true") .endControlFlow() .beginControlFlow("if (obj == null)") .addStatement("return false") .endControlFlow() .beginControlFlow("if (!(obj instanceof $T))", className) .addStatement("return false") .endControlFlow(); if (!shapeModel.getNonStreamingMembers().isEmpty()) { methodBuilder.addStatement("$T other = ($T) obj", className, className); } List<MemberModel> memberModels = shapeModel.getNonStreamingMembers(); CodeBlock.Builder memberEqualsStmt = CodeBlock.builder(); if (memberModels.isEmpty()) { memberEqualsStmt.addStatement("return true"); } else { memberEqualsStmt.add("return "); memberEqualsStmt.add(memberModels.stream().map(m -> { String getterName = m.getFluentGetterMethodName(); CodeBlock.Builder result = CodeBlock.builder(); if (m.getAutoConstructClassIfExists().isPresent()) { String existenceCheckMethodName = m.getExistenceCheckMethodName(); result.add("$1N() == other.$1N() && ", existenceCheckMethodName); } return result.add("$T.equals($N(), other.$N())", Objects.class, getterName, getterName) .build(); }).collect(PoetCollectors.toDelimitedCodeBlock("&&"))); memberEqualsStmt.add(";"); } return methodBuilder.addCode(memberEqualsStmt.build()).build(); } public MethodSpec equalsMethod(ShapeModel shapeModel) { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("equals") .returns(boolean.class) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(Object.class, "obj"); CodeBlock.Builder memberEqualsStmt = CodeBlock.builder(); memberEqualsStmt.add("return "); if (poetExtensions.isRequest(shapeModel) || poetExtensions.isResponse(shapeModel)) { memberEqualsStmt.add("super.equals(obj) && "); } memberEqualsStmt.add("equalsBySdkFields(obj);"); return methodBuilder.addCode(memberEqualsStmt.build()).build(); } public MethodSpec toStringMethod(ShapeModel shapeModel) { String javadoc = "Returns a string representation of this object. This is useful for testing and " + "debugging. Sensitive data will be redacted from this string using a placeholder " + "value. "; MethodSpec.Builder toStringMethod = MethodSpec.methodBuilder("toString") .returns(String.class) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addJavadoc(javadoc); toStringMethod.addCode("return $T.builder($S)", ToString.class, shapeModel.getShapeName()); shapeModel.getNonStreamingMembers() .forEach(m -> toStringMethod.addCode(".add($S, ", m.getName()) .addCode(toStringValue(m)) .addCode(")")); toStringMethod.addCode(".build();"); return toStringMethod.build(); } public CodeBlock toStringValue(MemberModel member) { if (member.isSensitive()) { return CodeBlock.of("$L() == null ? null : $S", member.getFluentGetterMethodName(), "*** Sensitive Data Redacted ***"); } if (member.getAutoConstructClassIfExists().isPresent()) { return CodeBlock.of("$N() ? $N() : null", member.getExistenceCheckMethodName(), member.getFluentGetterMethodName()); } return CodeBlock.of("$L()", member.getFluentGetterMethodName()); } public MethodSpec hashCodeMethod(ShapeModel shapeModel) { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("hashCode") .returns(int.class) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addStatement("int hashCode = 1"); if (poetExtensions.isRequest(shapeModel) || poetExtensions.isResponse(shapeModel)) { methodBuilder.addStatement("hashCode = 31 * hashCode + super.hashCode()"); } shapeModel.getNonStreamingMembers() .forEach(m -> methodBuilder.addCode("hashCode = 31 * hashCode + $T.hashCode(", Objects.class) .addCode(hashCodeValue(m)) .addCode(");\n")); methodBuilder.addStatement("return hashCode"); return methodBuilder.build(); } public CodeBlock hashCodeValue(MemberModel member) { if (member.getAutoConstructClassIfExists().isPresent()) { return CodeBlock.of("$N() ? $N() : null", member.getExistenceCheckMethodName(), member.getFluentGetterMethodName()); } return CodeBlock.of("$N()", member.getFluentGetterMethodName()); } }
3,434
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/model/ShapeModelSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.WildcardTypeName; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.lang.model.element.Modifier; 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.Protocol; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.service.XmlNamespace; import software.amazon.awssdk.codegen.naming.NamingStrategy; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.DefaultValueTrait; import software.amazon.awssdk.core.traits.JsonValueTrait; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.traits.LocationTrait; import software.amazon.awssdk.core.traits.MapTrait; import software.amazon.awssdk.core.traits.PayloadTrait; import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.awssdk.core.traits.TimestampFormatTrait; import software.amazon.awssdk.core.traits.XmlAttributeTrait; import software.amazon.awssdk.core.traits.XmlAttributesTrait; import software.amazon.awssdk.core.traits.XmlAttributesTrait.AttributeAccessors; import software.amazon.awssdk.utils.Pair; /** * Provides Poet specs related to shape models. */ class ShapeModelSpec { private final ShapeModel shapeModel; private final TypeProvider typeProvider; private final PoetExtension poetExtensions; private final NamingStrategy namingStrategy; private final CustomizationConfig customizationConfig; private final IntermediateModel model; ShapeModelSpec(ShapeModel shapeModel, TypeProvider typeProvider, PoetExtension poetExtensions, IntermediateModel model) { this.shapeModel = shapeModel; this.typeProvider = typeProvider; this.poetExtensions = poetExtensions; this.namingStrategy = model.getNamingStrategy(); this.customizationConfig = model.getCustomizationConfig(); this.model = model; } ClassName className() { return poetExtensions.getModelClass(shapeModel.getShapeName()); } public List<FieldSpec> fields() { return fields(Modifier.PRIVATE, Modifier.FINAL); } public List<FieldSpec> fields(Modifier... modifiers) { return shapeModel.getNonStreamingMembers().stream() // Exceptions can be members of event stream shapes, need to filter those out of the models .filter(m -> m.getShape() == null || m.getShape().getShapeType() != ShapeType.Exception) .map(m -> typeProvider.asField(m, modifiers)) .collect(Collectors.toList()); } public Iterable<FieldSpec> staticFields(Modifier... modifiers) { List<FieldSpec> fields = new ArrayList<>(); shapeModel.getNonStreamingMembers().stream() // Exceptions can be members of event stream shapes, need to filter those out of the models .filter(m -> m.getShape() == null || m.getShape().getShapeType() != ShapeType.Exception) .filter(m -> !m.isSynthetic()) .forEach(m -> { FieldSpec field = typeProvider.asField(m, modifiers); ClassName sdkFieldType = ClassName.get(SdkField.class); fields.add(FieldSpec.builder(ParameterizedTypeName.get(sdkFieldType, field.type), namingStrategy.getSdkFieldFieldName(m), Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer(sdkFieldInitializer(m)) .build()); }); ParameterizedTypeName sdkFieldType = ParameterizedTypeName.get(ClassName.get(SdkField.class), WildcardTypeName.subtypeOf(ClassName.get(Object.class))); fields.add(FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(List.class), sdkFieldType), "SDK_FIELDS", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("$T.unmodifiableList($T.asList($L))", ClassName.get(Collections.class), ClassName.get(Arrays.class), fields.stream() .map(f -> f.name) .collect(Collectors.joining(","))) .build()); return fields; } private CodeBlock sdkFieldInitializer(MemberModel m) { ClassName sdkFieldType = ClassName.get(SdkField.class); return CodeBlock.builder() .add("$T.<$T>builder($T.$L)\n", sdkFieldType, typeProvider.fieldType(m), ClassName.get(MarshallingType.class), m.getMarshallingType()) .add(".memberName($S)\n", m.getC2jName()) .add(".getter(getter($T::$L))\n", className(), m.getFluentGetterMethodName()) .add(".setter(setter($T::$L))\n", className().nestedClass("Builder"), m.getFluentSetterMethodName()) .add(constructor(m)) .add(traits(m)) .add(".build()") .build(); } private CodeBlock containerSdkFieldInitializer(MemberModel m) { ClassName sdkFieldType = ClassName.get(SdkField.class); return CodeBlock.builder() .add("$T.<$T>builder($T.$L)\n", sdkFieldType, typeProvider.fieldType(m), ClassName.get(MarshallingType.class), m.getMarshallingType()) .add(constructor(m)) .add(traits(m)) .add(".build()") .build(); } private CodeBlock traits(MemberModel m) { List<CodeBlock> traits = new ArrayList<>(); traits.add(createLocationTrait(m)); if (m.isList()) { traits.add(createListTrait(m)); } else if (m.isMap()) { traits.add(createMapTrait(m)); } if (m.getHttp().getIsPayload() || m.isEventPayload() || attachPayloadTraitToMember(m)) { traits.add(createPayloadTrait()); } if (m.isJsonValue()) { traits.add(createJsonValueTrait()); } if (m.isIdempotencyToken()) { traits.add(createIdempotencyTrait()); } String customDefaultValueSupplier = customizationConfig.getModelMarshallerDefaultValueSupplier().get(m.getC2jName()); if (customDefaultValueSupplier != null) { traits.add(createDefaultValueTrait(customDefaultValueSupplier)); } if (m.getTimestampFormat() != null) { traits.add(createTimestampFormatTrait(m)); } if (m.getShape() != null && m.getShape().getXmlNamespace() != null) { traits.add(createXmlAttributesTrait(m)); } if (m.isXmlAttribute()) { traits.add(createXmlAttributeTrait()); } if (customizationConfig.isRequiredTraitValidationEnabled() && m.isRequired()) { traits.add(createRequiredTrait()); } if (!traits.isEmpty()) { return CodeBlock.builder() .add(".traits(" + traits.stream().map(t -> "$L").collect(Collectors.joining(", ")) + ")", traits.toArray()) .build(); } else { return CodeBlock.builder().build(); } } private boolean attachPayloadTraitToMember(MemberModel m) { return customizationConfig.getAttachPayloadTraitToMember() .getOrDefault(shapeModel.getC2jName(), "") .equals(m.getC2jName()); } private CodeBlock createTimestampFormatTrait(MemberModel m) { TimestampFormatTrait.Format format = TimestampFormatTrait.Format.fromString(m.getTimestampFormat()); ClassName traitClass = ClassName.get(TimestampFormatTrait.class); ClassName formatClass = ClassName.get(TimestampFormatTrait.Format.class); return CodeBlock.builder() .add("$T.create($T.$L)", traitClass, formatClass, format.name()) .build(); } private CodeBlock createLocationTrait(MemberModel m) { MarshallLocation marshallLocation = marshallLocation(m); String unmarshallLocation = unmarshallLocation(m); return CodeBlock.builder() // TODO will marshall and unmarshall location name ever differ? .add("$T.builder()\n" + ".location($T.$L)\n" + ".locationName($S)\n" + unmarshallLocation + ".build()", ClassName.get(LocationTrait.class), ClassName.get(MarshallLocation.class), marshallLocation, m.getHttp().getMarshallLocationName()) .build(); } private MarshallLocation marshallLocation(MemberModel m) { // Handle events explicitly if (m.isEventHeader()) { return MarshallLocation.HEADER; } if (m.isEventPayload()) { return MarshallLocation.PAYLOAD; } return m.getHttp().getMarshallLocation(); } // Rest xml uses unmarshall locationName to properly unmarshall flattened lists private String unmarshallLocation(MemberModel m) { return model.getMetadata().getProtocol() == Protocol.EC2 || model.getMetadata().getProtocol() == Protocol.REST_XML ? String.format(".unmarshallLocationName(\"%s\")%n", m.getHttp().getUnmarshallLocationName()) : ""; } private CodeBlock createIdempotencyTrait() { return CodeBlock.builder() .add("$T.idempotencyToken()", ClassName.get(DefaultValueTrait.class)) .build(); } private CodeBlock createDefaultValueTrait(String customDefaultValueSupplier) { return CodeBlock.builder() .add("$T.create($T.getInstance())", ClassName.get(DefaultValueTrait.class), ClassName.bestGuess(customDefaultValueSupplier)) .build(); } private CodeBlock createJsonValueTrait() { return CodeBlock.builder() .add("$T.create()", ClassName.get(JsonValueTrait.class)) .build(); } private CodeBlock createPayloadTrait() { return CodeBlock.builder() .add("$T.create()", ClassName.get(PayloadTrait.class)) .build(); } private CodeBlock createRequiredTrait() { return CodeBlock.builder() .add("$T.create()", ClassName.get(RequiredTrait.class)) .build(); } private CodeBlock createMapTrait(MemberModel m) { return CodeBlock.builder() .add("$T.builder()\n" + ".keyLocationName($S)\n" + ".valueLocationName($S)\n" + ".valueFieldInfo($L)\n" + isFlattened(m) + ".build()", ClassName.get(MapTrait.class), m.getMapModel().getKeyLocationName(), m.getMapModel().getValueLocationName(), containerSdkFieldInitializer(m.getMapModel().getValueModel())) .build(); } private CodeBlock createListTrait(MemberModel m) { return CodeBlock.builder() .add("$T.builder()\n" + ".memberLocationName($S)\n" + ".memberFieldInfo($L)\n" + isFlattened(m) + ".build()", ClassName.get(ListTrait.class), m.getListModel().getMemberLocationName(), containerSdkFieldInitializer(m.getListModel().getListMemberModel())) .build(); } private CodeBlock createXmlAttributeTrait() { return CodeBlock.builder() .add("$T.create()", ClassName.get(XmlAttributeTrait.class)) .build(); } private CodeBlock createXmlAttributesTrait(MemberModel model) { ShapeModel shape = model.getShape(); XmlNamespace xmlNamespace = shape.getXmlNamespace(); String uri = xmlNamespace.getUri(); String prefix = xmlNamespace.getPrefix(); CodeBlock.Builder codeBlockBuilder = CodeBlock.builder() .add("$T.create(", ClassName.get(XmlAttributesTrait.class)); String namespacePrefix = "xmlns:" + prefix; codeBlockBuilder.add("$T.of($S, $T.builder().attributeGetter((ignore) -> $S).build())", Pair.class, namespacePrefix, AttributeAccessors.class, uri); Optional<MemberModel> memberWithXmlAttribute = findMemberWithXmlAttribute(shape); memberWithXmlAttribute.ifPresent(m -> { String attributeLocation = m.getHttp().getMarshallLocationName(); codeBlockBuilder .add(", $T.of($S, ", Pair.class, attributeLocation) .add("$T.builder()", AttributeAccessors.class) .add(".attributeGetter(t -> (($T)t).$L())\n", typeProvider.fieldType(model), m.getFluentGetterMethodName()) .add(".build())"); }); codeBlockBuilder.add(")"); return codeBlockBuilder.build(); } private static Optional<MemberModel> findMemberWithXmlAttribute(ShapeModel shapeModel) { return shapeModel.getMembers().stream().filter(MemberModel::isXmlAttribute).findAny(); } private String isFlattened(MemberModel m) { return m.getHttp().isFlattened() ? ".isFlattened(true)\n" : ""; } private CodeBlock constructor(MemberModel m) { if (!m.isSimple() && !m.isList() && !m.isMap()) { return CodeBlock.builder() .add(".constructor($T::builder)\n", typeProvider.fieldType(m)) .build(); } else { return CodeBlock.builder().build(); } } }
3,435
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/model/TypeProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.WildcardTypeName; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; 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.MapModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.document.Document; /** * Helper class for resolving Poet {@link TypeName}s for use in model classes. */ public class TypeProvider { private final IntermediateModel intermediateModel; private final PoetExtension poetExtensions; public TypeProvider(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; this.poetExtensions = new PoetExtension(this.intermediateModel); } public ClassName listImplClassName() { return ClassName.get(ArrayList.class); } public TypeName enumReturnType(MemberModel memberModel) { return typeName(memberModel, new TypeNameOptions().useEnumTypes(true)); } public TypeName returnType(MemberModel memberModel) { return typeName(memberModel, new TypeNameOptions().useEnumTypes(false)); } public TypeName fieldType(MemberModel memberModel) { return typeName(memberModel, new TypeNameOptions().useEnumTypes(false)); } public TypeName parameterType(MemberModel memberModel) { return parameterType(memberModel, false); } public TypeName parameterType(MemberModel memberModel, boolean preserveEnum) { return typeName(memberModel, new TypeNameOptions().useCollectionForList(true) .useSubtypeWildcardsForCollections(true) .useEnumTypes(preserveEnum)); } public TypeName mapEntryWithConcreteTypes(MapModel mapModel) { TypeName keyType = fieldType(mapModel.getKeyModel()); TypeName valueType = fieldType(mapModel.getValueModel()); return ParameterizedTypeName.get(ClassName.get(Map.Entry.class), keyType, valueType); } public TypeName getTypeNameForSimpleType(String simpleType) { return Stream.of(String.class, Boolean.class, Integer.class, Long.class, Short.class, Byte.class, BigInteger.class, Double.class, Float.class, BigDecimal.class, SdkBytes.class, InputStream.class, Instant.class, Document.class) .filter(cls -> cls.getName().equals(simpleType) || cls.getSimpleName().equals(simpleType)) .map(ClassName::get) .findFirst() .orElseThrow(() -> new RuntimeException("Unsupported simple fieldType " + simpleType)); } public FieldSpec asField(MemberModel memberModel, Modifier... modifiers) { FieldSpec.Builder builder = FieldSpec.builder(fieldType(memberModel), memberModel.getVariable().getVariableName()); if (modifiers != null) { builder.addModifiers(modifiers); } return builder.build(); } private static boolean isContainerType(MemberModel m) { return m.isList() || m.isMap(); } public TypeName typeName(MemberModel model) { return typeName(model, new TypeNameOptions()); } public TypeName typeName(MemberModel model, TypeNameOptions options) { if (model.isSdkBytesType() && options.useByteBufferTypes) { return ClassName.get(ByteBuffer.class); } if (model.getEnumType() != null && options.useEnumTypes) { return poetExtensions.getModelClass(model.getEnumType()); } if (model.isSimple()) { return getTypeNameForSimpleType(model.getVariable().getVariableType()); } if (model.isList()) { MemberModel entryModel = model.getListModel().getListMemberModel(); TypeName entryType = typeName(entryModel, options); if (options.useSubtypeWildcardsForCollections && isContainerType(entryModel) || options.useSubtypeWildcardsForBuilders && entryModel.hasBuilder()) { entryType = WildcardTypeName.subtypeOf(entryType); } Class<?> collectionType = options.useCollectionForList ? Collection.class : List.class; return ParameterizedTypeName.get(ClassName.get(collectionType), entryType); } if (model.isMap()) { MemberModel keyModel = model.getMapModel().getKeyModel(); MemberModel valueModel = model.getMapModel().getValueModel(); TypeName keyType = typeName(keyModel, options); TypeName valueType = typeName(valueModel, options); if (options.useSubtypeWildcardsForCollections && isContainerType(keyModel) || options.useSubtypeWildcardsForBuilders && keyModel.hasBuilder()) { keyType = WildcardTypeName.subtypeOf(keyType); } if (options.useSubtypeWildcardsForCollections && isContainerType(valueModel) || options.useSubtypeWildcardsForBuilders && valueModel.hasBuilder()) { valueType = WildcardTypeName.subtypeOf(valueType); } return ParameterizedTypeName.get(ClassName.get(Map.class), keyType, valueType); } if (model.hasBuilder()) { ClassName shapeClass = poetExtensions.getModelClass(model.getC2jShape()); switch (options.shapeTransformation) { case NONE: return shapeClass; case USE_BUILDER: return shapeClass.nestedClass("Builder"); case USE_BUILDER_IMPL: return shapeClass.nestedClass("BuilderImpl"); default: throw new IllegalStateException(); } } throw new IllegalArgumentException("Unsupported member model: " + model); } public enum ShapeTransformation { USE_BUILDER, USE_BUILDER_IMPL, NONE } public static final class TypeNameOptions { private ShapeTransformation shapeTransformation = ShapeTransformation.NONE; private boolean useCollectionForList = false; private boolean useSubtypeWildcardsForCollections = false; private boolean useByteBufferTypes = false; private boolean useEnumTypes = false; private boolean useSubtypeWildcardsForBuilders = false; public TypeNameOptions shapeTransformation(ShapeTransformation shapeTransformation) { this.shapeTransformation = shapeTransformation; return this; } public TypeNameOptions useCollectionForList(boolean useCollectionForList) { this.useCollectionForList = useCollectionForList; return this; } public TypeNameOptions useSubtypeWildcardsForCollections(boolean useSubtypeWildcardsForCollections) { this.useSubtypeWildcardsForCollections = useSubtypeWildcardsForCollections; return this; } public TypeNameOptions useSubtypeWildcardsForBuilders(boolean useSubtypeWildcardsForBuilders) { this.useSubtypeWildcardsForBuilders = useSubtypeWildcardsForBuilders; return this; } public TypeNameOptions useEnumTypes(boolean useEnumTypes) { this.useEnumTypes = useEnumTypes; return this; } public TypeNameOptions useByteBufferTypes(boolean useByteBufferTypes) { this.useByteBufferTypes = useByteBufferTypes; return this; } } }
3,436
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/model/AwsServiceBaseResponseSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import javax.lang.model.element.Modifier; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.AwsResponseMetadata; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; public class AwsServiceBaseResponseSpec implements ClassSpec { private final IntermediateModel intermediateModel; private final PoetExtension poetExtensions; private final ClassName responseMetadata; public AwsServiceBaseResponseSpec(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; this.poetExtensions = new PoetExtension(this.intermediateModel); this.responseMetadata = poetExtensions.getResponseMetadataClass(); } @Override public TypeSpec poetSpec() { MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PROTECTED) .addParameter(className().nestedClass("Builder"), "builder") .addStatement("super(builder)"); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className()) .addAnnotation(PoetUtils.generatedAnnotation()) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .superclass(ClassName.get(AwsResponse.class)) .addType(builderInterfaceSpec()) .addType(builderImplSpec()); addResponseMetadata(classBuilder, constructorBuilder); classBuilder.addMethod(constructorBuilder.build()); return classBuilder.build(); } @Override public ClassName className() { return poetExtensions.getModelClass(intermediateModel.getSdkResponseBaseClassName()); } private TypeSpec builderInterfaceSpec() { TypeSpec.Builder builder = TypeSpec.interfaceBuilder("Builder") .addModifiers(Modifier.PUBLIC) .addSuperinterface(ClassName.get(AwsResponse.class).nestedClass("Builder")) .addMethod(MethodSpec.methodBuilder("build") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(className()) .build()); addResponseMetadataToInterface(builder); return builder.build(); } private ClassName builderInterfaceName() { return className().nestedClass("Builder"); } private TypeSpec builderImplSpec() { MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PROTECTED) .addParameter(className(), "response") .addStatement("super(response)") .addStatement("this.responseMetadata = response.responseMetadata()"); TypeSpec.Builder classBuilder = TypeSpec.classBuilder("BuilderImpl") .addModifiers(Modifier.PROTECTED, Modifier.STATIC, Modifier.ABSTRACT) .addSuperinterface(className().nestedClass("Builder")) .superclass(ClassName.get(AwsResponse.class).nestedClass("BuilderImpl")) .addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PROTECTED) .build()) .addMethod(constructorBuilder.build()); addResponseMetadataToImpl(classBuilder); return classBuilder.build(); } private void addResponseMetadata(TypeSpec.Builder classBuilder, MethodSpec.Builder constructorBuilder) { constructorBuilder.addStatement("this.responseMetadata = builder.responseMetadata()"); classBuilder.addField(FieldSpec.builder(responseMetadata, "responseMetadata", Modifier.PRIVATE, Modifier.FINAL) .build()); classBuilder.addMethod(MethodSpec.methodBuilder("responseMetadata") .returns(responseMetadata) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addCode("return responseMetadata;") .build()); } private void addResponseMetadataToInterface(TypeSpec.Builder builder) { builder.addMethod(MethodSpec.methodBuilder("responseMetadata") .returns(responseMetadata) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .build()); builder.addMethod(MethodSpec.methodBuilder("responseMetadata") .addParameter(AwsResponseMetadata.class, "metadata") .returns(builderInterfaceName()) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .build()); } private void addResponseMetadataToImpl(TypeSpec.Builder classBuilder) { classBuilder.addField(FieldSpec.builder(responseMetadata, "responseMetadata", Modifier.PRIVATE).build()); classBuilder.addMethod(MethodSpec.methodBuilder("responseMetadata") .returns(responseMetadata) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addStatement("return responseMetadata") .build()); classBuilder.addMethod(MethodSpec.methodBuilder("responseMetadata") .addParameter(AwsResponseMetadata.class, "responseMetadata") .returns(builderInterfaceName()) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addCode(CodeBlock.builder() .add("this.responseMetadata = $T.create(responseMetadata);\n", responseMetadata) .add("return this;") .build()) .build()); } }
3,437
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/model/BaseExceptionClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import javax.lang.model.element.Modifier; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; public class BaseExceptionClass implements ClassSpec { private final ClassName baseExceptionClassName; public BaseExceptionClass(IntermediateModel model) { String basePackage = model.getMetadata().getFullModelPackageName(); this.baseExceptionClassName = ClassName.get(basePackage, model.getSdkModeledExceptionBaseClassName()); } @Override public TypeSpec poetSpec() { return PoetUtils.createClassBuilder(baseExceptionClassName) .superclass(AwsServiceException.class) .addMethod(constructor()) .addMethod(builderMethod()) .addMethod(toBuilderMethod()) .addMethod(serializableBuilderClass()) .addModifiers(Modifier.PUBLIC) .addType(builderInterface()) .addType(builderImplClass()) .build(); } public MethodSpec constructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PROTECTED) .addParameter(baseExceptionClassName.nestedClass("Builder"), "builder") .addStatement("super(builder)") .build(); } public TypeSpec builderInterface() { TypeSpec.Builder builder = TypeSpec.interfaceBuilder(baseExceptionClassName.nestedClass("Builder")) .addSuperinterface(ClassName.get(AwsServiceException.class).nestedClass("Builder")) .addModifiers(Modifier.PUBLIC) .addMethods(ExceptionProperties.builderInterfaceMethods(className().nestedClass("Builder"))); return builder.build(); } public TypeSpec builderImplClass() { return TypeSpec.classBuilder(baseExceptionClassName.nestedClass("BuilderImpl")) .addSuperinterface(className().nestedClass("Builder")) .superclass(ClassName.get(AwsServiceException.class).nestedClass("BuilderImpl")) .addModifiers(Modifier.STATIC, Modifier.PROTECTED) .addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PROTECTED).build()) .addMethod(copyModelConstructor()) .addMethods(ExceptionProperties.builderImplMethods(className().nestedClass("BuilderImpl"))) .addMethod(MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addStatement("return new $T(this)", className()) .returns(className()) .build()) .build(); } private MethodSpec copyModelConstructor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PROTECTED) .addParameter(className(), "ex") .addStatement("super(ex)") .build(); } private MethodSpec builderMethod() { return MethodSpec.methodBuilder("builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(className().nestedClass("Builder")) .addStatement("return new $T()", className().nestedClass("BuilderImpl")) .build(); } private MethodSpec toBuilderMethod() { return MethodSpec.methodBuilder("toBuilder") .addModifiers(Modifier.PUBLIC) .returns(className().nestedClass("Builder")) .addStatement("return new $T(this)", className().nestedClass("BuilderImpl")) .build(); } private MethodSpec serializableBuilderClass() { return MethodSpec.methodBuilder("serializableBuilderClass") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(className().nestedClass("Builder")))) .addStatement("return $T.class", className().nestedClass("BuilderImpl")) .build(); } @Override public ClassName className() { return baseExceptionClassName; } }
3,438
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/model/ServiceClientConfigurationClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.ABSTRACT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.awscore.AwsServiceClientConfiguration; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.model.ServiceClientConfigurationUtils.Field; public class ServiceClientConfigurationClass implements ClassSpec { private final ClassName defaultClientMetadataClassName; private final ServiceClientConfigurationUtils utils; public ServiceClientConfigurationClass(IntermediateModel model) { String basePackage = model.getMetadata().getFullClientPackageName(); String serviceId = model.getMetadata().getServiceName(); this.defaultClientMetadataClassName = ClassName.get(basePackage, serviceId + "ServiceClientConfiguration"); this.utils = new ServiceClientConfigurationUtils(model); } @Override public ClassName className() { return utils.serviceClientConfigurationClassName(); } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = PoetUtils.createClassBuilder(defaultClientMetadataClassName) .addModifiers(PUBLIC, FINAL) .addAnnotation(SdkPublicApi.class) .superclass(AwsServiceClientConfiguration.class) .addJavadoc("Class to expose the service client settings to the user. " + "Implementation of {@link $T}", AwsServiceClientConfiguration.class); builder.addMethod(constructor()) .addMethod(builderMethod()); for (Field field : utils.serviceClientConfigurationFields()) { if (!field.isInherited()) { builder.addField(field.type(), field.name(), PRIVATE, FINAL); builder.addMethod(field.localGetter()); } } return builder.addType(builderInterfaceSpec()) .build(); } private MethodSpec constructor() { MethodSpec.Builder builder = MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addParameter(className().nestedClass("Builder"), "builder"); builder.addStatement("super(builder)"); for (Field field : utils.serviceClientConfigurationFields()) { if (!field.isInherited()) { builder.addStatement("this.$L = builder.$L()", field.name(), field.name()); } } return builder.build(); } private MethodSpec builderMethod() { return MethodSpec.methodBuilder("builder") .addModifiers(PUBLIC, STATIC) .addStatement("return new $T()", utils.serviceClientConfigurationBuilderClassName()) .returns(className().nestedClass("Builder")) .build(); } private TypeSpec builderInterfaceSpec() { TypeSpec.Builder builder = TypeSpec.interfaceBuilder("Builder") .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(AwsServiceClientConfiguration.class) .nestedClass("Builder")) .addJavadoc("A builder for creating a {@link $T}", className()); for (Field field : utils.serviceClientConfigurationFields()) { MethodSpec.Builder setterMethod = field.setterSpec().toBuilder().addModifiers(ABSTRACT); MethodSpec.Builder getterMethod = field.getterSpec().toBuilder().addModifiers(ABSTRACT); if (field.isInherited()) { setterMethod.addAnnotation(Override.class); getterMethod.addAnnotation(Override.class); } builder.addMethod(setterMethod.build()); builder.addMethod(getterMethod.build()); } builder.addMethod(MethodSpec.methodBuilder("build") .addAnnotation(Override.class) .addModifiers(PUBLIC, ABSTRACT) .returns(className()) .build()); return builder.build(); } }
3,439
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/model/ExceptionProperties.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import java.util.Arrays; import java.util.List; import javax.lang.model.element.Modifier; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; public class ExceptionProperties { private ExceptionProperties() { } public static List<MethodSpec> builderInterfaceMethods(ClassName className) { return Arrays.asList( builderMethod(className, "awsErrorDetails", AwsErrorDetails.class), builderMethod(className, "message", String.class), builderMethod(className, "requestId", String.class), builderMethod(className, "statusCode", int.class), builderMethod(className, "cause", Throwable.class), builderMethod(className, "writableStackTrace", Boolean.class)); } public static List<MethodSpec> builderImplMethods(ClassName className) { return Arrays.asList( builderImplMethods(className, "awsErrorDetails", AwsErrorDetails.class), builderImplMethods(className, "message", String.class), builderImplMethods(className, "requestId", String.class), builderImplMethods(className, "statusCode", int.class), builderImplMethods(className, "cause", Throwable.class), builderImplMethods(className, "writableStackTrace", Boolean.class)); } private static MethodSpec builderMethod(ClassName className, String name, Class clazz) { return MethodSpec.methodBuilder(name) .addAnnotation(Override.class) .returns(className) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addParameter(clazz, name) .build(); } private static MethodSpec builderImplMethods(ClassName className, String name, Class clazz) { return MethodSpec.methodBuilder(name) .addAnnotation(Override.class) .returns(className) .addModifiers(Modifier.PUBLIC) .addParameter(clazz, name) .addStatement("this." + name + " = " + name) .addStatement("return this") .build(); } }
3,440
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/model/AwsServiceModel.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.Collections.emptyList; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static software.amazon.awssdk.codegen.internal.Utils.capitalize; import static software.amazon.awssdk.codegen.poet.model.DeprecationUtils.checkDeprecated; 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.TypeVariableName; import com.squareup.javapoet.WildcardTypeName; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.BiConsumer; 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 software.amazon.awssdk.annotations.SdkPublicApi; 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.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.intermediate.VariableModel; import software.amazon.awssdk.codegen.naming.NamingStrategy; 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.eventstream.EventStreamUtils; import software.amazon.awssdk.codegen.poet.model.TypeProvider.TypeNameOptions; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Provides the Poet specs for AWS Service models. */ public class AwsServiceModel implements ClassSpec { private final IntermediateModel intermediateModel; private final ShapeModel shapeModel; private final PoetExtension poetExtensions; private final TypeProvider typeProvider; private final ShapeModelSpec shapeModelSpec; private final ModelBuilderSpecs modelBuilderSpecs; private final ServiceModelCopiers serviceModelCopiers; private final ModelMethodOverrides modelMethodOverrides; public AwsServiceModel(IntermediateModel intermediateModel, ShapeModel shapeModel) { this.intermediateModel = intermediateModel; this.shapeModel = shapeModel; this.poetExtensions = new PoetExtension(intermediateModel); this.typeProvider = new TypeProvider(intermediateModel); this.shapeModelSpec = new ShapeModelSpec(this.shapeModel, typeProvider, poetExtensions, intermediateModel); this.modelBuilderSpecs = resolveBuilderSpecs(); this.serviceModelCopiers = new ServiceModelCopiers(this.intermediateModel); this.modelMethodOverrides = new ModelMethodOverrides(className(), this.poetExtensions); } @Override public TypeSpec poetSpec() { if (shapeModel.isEventStream()) { return eventStreamInterfaceSpec(); } List<FieldSpec> fields = shapeModelSpec.fields(); TypeSpec.Builder specBuilder = TypeSpec.classBuilder(className()) .addModifiers(PUBLIC) .addAnnotation(PoetUtils.generatedAnnotation()) .addSuperinterfaces(modelSuperInterfaces()) .superclass(modelSuperClass()) .addMethods(modelClassMethods()) .addFields(fields) .addFields(shapeModelSpec.staticFields()) .addMethod(addModifier(sdkFieldsMethod(), FINAL)) .addTypes(nestedModelClassTypes()); if (shapeModel.isUnion()) { specBuilder.addField(unionTypeField()); } if (!isEvent()) { specBuilder.addModifiers(Modifier.FINAL); } // Add serializable version UID for model and exceptions. if (shapeModel.getShapeType() == ShapeType.Model || shapeModel.getShapeType() == ShapeType.Exception) { specBuilder.addField(FieldSpec.builder(long.class, "serialVersionUID", Modifier.PRIVATE, STATIC, Modifier.FINAL) .initializer("1L") .build()); } if (!fields.isEmpty()) { specBuilder .addMethod(getterCreator()) .addMethod(setterCreator()); } if (this.shapeModel.isEvent()) { addEventSupport(specBuilder); } if (this.shapeModel.getDocumentation() != null) { specBuilder.addJavadoc("$L", this.shapeModel.getDocumentation()); } return specBuilder.build(); } private ModelBuilderSpecs resolveBuilderSpecs() { return new ModelBuilderSpecs(intermediateModel, shapeModel, typeProvider); } private TypeSpec eventStreamInterfaceSpec() { Collection<OperationModel> opModels = EventStreamUtils.findOperationsWithEventStream(intermediateModel, shapeModel); Collection<OperationModel> outputOperations = findOutputEventStreamOperations(opModels, shapeModel); EventStreamSpecHelper helper = new EventStreamSpecHelper(shapeModel, intermediateModel); ClassName modelClass = poetExtensions.getModelClassFromShape(shapeModel); TypeSpec.Builder builder = PoetUtils.createInterfaceBuilder(modelClass) .addAnnotation(SdkPublicApi.class) .addMethods(eventStreamInterfaceEventBuilderMethods()) .addType(helper.eventTypeEnumSpec()); ClassName eventTypeEnum = helper.eventTypeEnumClassName(); builder.addMethod(MethodSpec.methodBuilder("sdkEventType") .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) .returns(eventTypeEnum) .addJavadoc("The type of this event. Corresponds to the {@code :event-type} header on the Message.") .addStatement("return $T.UNKNOWN_TO_SDK_VERSION", eventTypeEnum) .build()); if (!outputOperations.isEmpty()) { CodeBlock unknownInitializer = buildUnknownEventStreamInitializer(outputOperations, modelClass); builder.addSuperinterface(ClassName.get(SdkPojo.class)) .addJavadoc("Base interface for all event types in $L.", shapeModel.getShapeName()) .addField(FieldSpec.builder(modelClass, "UNKNOWN") .addModifiers(PUBLIC, STATIC, Modifier.FINAL) .initializer(unknownInitializer) .addJavadoc("Special type of {@link $T} for unknown types of events that this " + "version of the SDK does not know about", modelClass) .build()); for (OperationModel opModel : outputOperations) { ClassName responseHandlerClass = poetExtensions.eventStreamResponseHandlerType(opModel); builder.addMethod(acceptMethodSpec(modelClass, responseHandlerClass) .addModifiers(Modifier.ABSTRACT) .build()); } return builder.build(); } else if (hasInputStreamOperations(opModels, shapeModel)) { return builder.addJavadoc("Base interface for all event types in $L.", shapeModel.getShapeName()) .build(); } throw new IllegalArgumentException(shapeModel.getShapeName() + " event stream shape is not found " + "in any request or response shape"); } private void addEventSupport(TypeSpec.Builder specBuilder) { EventStreamUtils.getBaseEventStreamShapes(intermediateModel, shapeModel) .forEach(eventStream -> addEventSupport(specBuilder, eventStream)); } private void addEventSupport(TypeSpec.Builder specBuilder, ShapeModel eventStream) { ClassName eventStreamClassName = poetExtensions.getModelClassFromShape(eventStream); Collection<OperationModel> opModels = EventStreamUtils.findOperationsWithEventStream(intermediateModel, eventStream); Collection<OperationModel> outputOperations = findOutputEventStreamOperations(opModels, eventStream); boolean onOutput = !outputOperations.isEmpty(); boolean onInput = hasInputStreamOperations(opModels, eventStream); if (!onOutput && !onInput) { throw new IllegalArgumentException(shapeModel.getC2jName() + " event shape is not a member in any " + "request or response event shape"); } EventStreamSpecHelper helper = new EventStreamSpecHelper(eventStream, intermediateModel); specBuilder.addSuperinterface(eventStreamClassName); boolean usesLegacyScheme = useLegacyEventGenerationScheme(eventStream); Optional<MemberModel> legacyEvent = findLegacyGenerationEventWithShape(eventStream); if (usesLegacyScheme && legacyEvent.isPresent()) { NamingStrategy namingStrategy = intermediateModel.getNamingStrategy(); ClassName eventTypeEnum = helper.eventTypeEnumClassName(); specBuilder.addMethod(MethodSpec.methodBuilder("sdkEventType") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(eventTypeEnum) .addStatement("return $T.$N", eventTypeEnum, namingStrategy.getEnumValueName(legacyEvent.get().getName())) .build()); } if (onOutput) { ClassName modelClass = poetExtensions.getModelClass(shapeModel.getShapeName()); for (OperationModel opModel : outputOperations) { ClassName responseHandlerClass = poetExtensions.eventStreamResponseHandlerType(opModel); MethodSpec.Builder acceptMethodSpec = acceptMethodSpec(modelClass, responseHandlerClass) .addAnnotation(Override.class); if (usesLegacyScheme) { acceptMethodSpec.addStatement("visitor.visit(this)"); } else { // The class that represents the event type will be // responsible for implementing this acceptMethodSpec.addStatement("throw new $T()", UnsupportedOperationException.class); } specBuilder.addMethod(acceptMethodSpec.build()); } } } private boolean hasInputStreamOperations(Collection<OperationModel> opModels, ShapeModel eventStream) { return opModels.stream() .anyMatch(op -> EventStreamUtils.doesShapeContainsEventStream(op.getInputShape(), eventStream)); } private List<OperationModel> findOutputEventStreamOperations(Collection<OperationModel> opModels, ShapeModel eventStream) { return opModels .stream() .filter(opModel -> EventStreamUtils.doesShapeContainsEventStream(opModel.getOutputShape(), eventStream)) .collect(Collectors.toList()); } private CodeBlock buildUnknownEventStreamInitializer(Collection<OperationModel> outputOperations, ClassName eventStreamModelClass) { CodeBlock.Builder builder = CodeBlock.builder() .add("new $T() {\n" + " @Override\n" + " public $T<$T<?>> sdkFields() {\n" + " return $T.emptyList();\n" + " }\n", eventStreamModelClass, List.class, SdkField.class, Collections.class ); for (OperationModel opModel : outputOperations) { ClassName responseHandlerClass = poetExtensions.eventStreamResponseHandlerType(opModel); builder.add(" @Override\n" + " public void accept($T.Visitor visitor) {" + " \nvisitor.visitDefault(this);\n" + " }\n", responseHandlerClass); } builder.add(" }\n"); return builder.build(); } private MethodSpec sdkFieldsMethod() { ParameterizedTypeName sdkFieldType = ParameterizedTypeName.get(ClassName.get(SdkField.class), WildcardTypeName.subtypeOf(ClassName.get(Object.class))); return MethodSpec.methodBuilder("sdkFields") .addModifiers(PUBLIC) .addAnnotation(Override.class) .returns(ParameterizedTypeName.get(ClassName.get(List.class), sdkFieldType)) .addCode("return SDK_FIELDS;") .build(); } private MethodSpec getterCreator() { TypeVariableName t = TypeVariableName.get("T"); return MethodSpec.methodBuilder("getter") .addTypeVariable(t) .addModifiers(Modifier.PRIVATE, STATIC) .addParameter(ParameterizedTypeName.get(ClassName.get(Function.class), className(), t), "g") .returns(ParameterizedTypeName.get(ClassName.get(Function.class), ClassName.get(Object.class), t)) .addStatement("return obj -> g.apply(($T) obj)", className()) .build(); } private MethodSpec setterCreator() { TypeVariableName t = TypeVariableName.get("T"); return MethodSpec.methodBuilder("setter") .addTypeVariable(t) .addModifiers(Modifier.PRIVATE, STATIC) .addParameter(ParameterizedTypeName.get(ClassName.get(BiConsumer.class), builderClassName(), t), "s") .returns(ParameterizedTypeName.get(ClassName.get(BiConsumer.class), ClassName.get(Object.class), t)) .addStatement("return (obj, val) -> s.accept(($T) obj, val)", builderClassName()) .build(); } private MethodSpec.Builder acceptMethodSpec(ClassName modelClass, ClassName responseHandlerClass) { return MethodSpec.methodBuilder("accept") .addModifiers(PUBLIC) .addJavadoc(new DocumentationBuilder() .description("Calls the appropriate visit method depending on " + "the subtype of {@link $T}.") .param("visitor", "Visitor to invoke.") .build(), modelClass) .addParameter(responseHandlerClass .nestedClass("Visitor"), "visitor"); } @Override public ClassName className() { return shapeModelSpec.className(); } private ClassName builderClassName() { return className().nestedClass("Builder"); } private ClassName unionTypeClassName() { return className().nestedClass("Type"); } private List<TypeName> modelSuperInterfaces() { List<TypeName> interfaces = new ArrayList<>(); switch (shapeModel.getShapeType()) { case Model: interfaces.add(ClassName.get(SdkPojo.class)); interfaces.add(ClassName.get(Serializable.class)); interfaces.add(toCopyableBuilderInterface()); break; case Exception: case Request: case Response: interfaces.add(toCopyableBuilderInterface()); break; default: break; } return interfaces; } private TypeName modelSuperClass() { switch (shapeModel.getShapeType()) { case Request: return requestBaseClass(); case Response: return responseBaseClass(); case Exception: return exceptionBaseClass(); default: return ClassName.OBJECT; } } private TypeName requestBaseClass() { return new AwsServiceBaseRequestSpec(intermediateModel).className(); } private TypeName responseBaseClass() { return new AwsServiceBaseResponseSpec(intermediateModel).className(); } private ClassName exceptionBaseClass() { String customExceptionBase = intermediateModel.getCustomizationConfig() .getSdkModeledExceptionBaseClassName(); if (customExceptionBase != null) { return poetExtensions.getModelClass(customExceptionBase); } return poetExtensions.getModelClass(intermediateModel.getSdkModeledExceptionBaseClassName()); } private TypeName toCopyableBuilderInterface() { return ParameterizedTypeName.get(ClassName.get(ToCopyableBuilder.class), className().nestedClass("Builder"), className()); } private List<MethodSpec> modelClassMethods() { List<MethodSpec> methodSpecs = new ArrayList<>(); switch (shapeModel.getShapeType()) { case Exception: methodSpecs.add(exceptionConstructor()); methodSpecs.add(toBuilderMethod()); methodSpecs.add(builderMethod()); methodSpecs.add(serializableBuilderClass()); methodSpecs.addAll(memberGetters()); break; default: methodSpecs.addAll(addModifier(memberGetters(), FINAL)); methodSpecs.add(constructor()); methodSpecs.add(toBuilderMethod()); methodSpecs.add(builderMethod()); methodSpecs.add(serializableBuilderClass()); methodSpecs.add(addModifier(modelMethodOverrides.hashCodeMethod(shapeModel), FINAL)); methodSpecs.add(addModifier(modelMethodOverrides.equalsMethod(shapeModel), FINAL)); methodSpecs.add(addModifier(modelMethodOverrides.equalsBySdkFieldsMethod(shapeModel), FINAL)); methodSpecs.add(addModifier(modelMethodOverrides.toStringMethod(shapeModel), FINAL)); methodSpecs.add(getValueForField()); methodSpecs.addAll(unionMembers()); break; } if (isEvent()) { methodSpecs.add(copyMethod()); } return methodSpecs; } private MethodSpec getValueForField() { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("getValueForField") .addModifiers(PUBLIC, FINAL) .addTypeVariable(TypeVariableName.get("T")) .returns(ParameterizedTypeName.get(ClassName.get(Optional.class), TypeVariableName.get("T"))) .addParameter(String.class, "fieldName") .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class), TypeVariableName.get("T")), "clazz"); if (shapeModel.getNonStreamingMembers().isEmpty()) { methodBuilder.addStatement("return $T.empty()", Optional.class); return methodBuilder.build(); } methodBuilder.beginControlFlow("switch ($L)", "fieldName"); shapeModel.getNonStreamingMembers().forEach(m -> addCasesForMember(methodBuilder, m)); methodBuilder.addCode("default:"); methodBuilder.addStatement("return $T.empty()", Optional.class); methodBuilder.endControlFlow(); return methodBuilder.build(); } private FieldSpec unionTypeField() { return FieldSpec.builder(unionTypeClassName(), "type", PRIVATE, FINAL).build(); } private Collection<MethodSpec> unionMembers() { if (!shapeModel.isUnion()) { return emptyList(); } Validate.isFalse(shapeModel.isEvent(), "Event shape %s must not be a union", shapeModel.getShapeName()); Validate.isFalse(shapeModel.isEventStream(), "Event stream shape %s must not be a union", shapeModel.getShapeName()); Validate.isFalse(shapeModel.isDocument(), "Document shape %s must not be a union", shapeModel.getShapeName()); Validate.isFalse(isRequest() && isResponse(), "Input or output shape %s must not be a union", shapeModel.getShapeName()); List<MethodSpec> unionMembers = new ArrayList<>(); unionMembers.addAll(unionConstructors()); unionMembers.add(unionTypeMethod()); unionMembers.addAll(unionAcceptMethods()); return unionMembers; } private Collection<MethodSpec> unionConstructors() { return shapeModel.getMembers().stream() .flatMap(this::unionConstructors) .collect(Collectors.toList()); } private Stream<MethodSpec> unionConstructors(MemberModel member) { List<MethodSpec> unionConstructors = new ArrayList<>(); String memberName = member.getFluentSetterMethodName(); String methodName = "from" + capitalize(memberName); unionConstructors.add(MethodSpec.methodBuilder(methodName) .addJavadoc("$L", member.getUnionConstructorDocumentation()) .addModifiers(PUBLIC, STATIC) .returns(className()) .addParameter(typeProvider.typeName(member, new TypeNameOptions().useEnumTypes(false)), memberName) .addCode(CodeBlock.of("return builder()." + memberName + "(" + memberName + ").build();")) .build()); if (member.getFluentEnumSetterMethodName() != null) { unionConstructors.add(MethodSpec.methodBuilder("from" + capitalize(member.getFluentEnumSetterMethodName())) .addJavadoc("$L", member.getUnionConstructorDocumentation()) .addModifiers(PUBLIC, STATIC) .returns(className()) .addParameter(typeProvider.typeName(member, new TypeNameOptions().useEnumTypes(true)), memberName) .addCode(CodeBlock.of("return builder()." + member.getFluentEnumSetterMethodName() + "(" + memberName + ").build();")) .build()); } // Include a consumer-builder if the inner types are structures if (!member.isSimple() && !member.isList() && !member.isMap()) { TypeName memberType = typeProvider.typeName(member); ClassName memberClass = Validate.isInstanceOf(ClassName.class, memberType, "Non-simple TypeName was not represented as a ClassName: %s", memberType); ClassName memberClassBuilder = memberClass.nestedClass("Builder"); unionConstructors.add(MethodSpec.methodBuilder(methodName) .addJavadoc("$L", member.getUnionConstructorDocumentation()) .addModifiers(PUBLIC, STATIC) .returns(className()) .addParameter(ParameterizedTypeName.get(ClassName.get(Consumer.class), memberClassBuilder), memberName) .addCode(CodeBlock.builder() .add("$T builder = $T.builder();", memberClassBuilder, memberClass) .add("$L.accept(builder);", memberName) .add("return $L(builder.build());", methodName) .build()) .build()); } return unionConstructors.stream(); } private MethodSpec unionTypeMethod() { return MethodSpec.methodBuilder("type") .addJavadoc("$L", shapeModel.getUnionTypeGetterDocumentation()) .addModifiers(PUBLIC) .returns(unionTypeClassName()) .addCode("return type;") .build(); } private Collection<MethodSpec> unionAcceptMethods() { return emptyList(); } private void addCasesForMember(MethodSpec.Builder methodBuilder, MemberModel member) { methodBuilder.addCode("case $S:", member.getC2jName()) .addStatement("return $T.ofNullable(clazz.cast($L()))", Optional.class, member.getFluentGetterMethodName()); if (shouldGenerateDeprecatedNameGetter(member)) { methodBuilder.addCode("case $S:", member.getDeprecatedName()) .addStatement("return $T.ofNullable(clazz.cast($L()))", Optional.class, member.getFluentGetterMethodName()); } } private List<MethodSpec> memberGetters() { return shapeModel.getNonStreamingMembers().stream() .filter(m -> !m.getHttp().getIsStreaming()) .flatMap(this::memberGetters) .collect(Collectors.toList()); } private Stream<MethodSpec> memberGetters(MemberModel member) { List<MethodSpec> result = new ArrayList<>(); if (shouldGenerateEnumGetter(member)) { result.add(enumMemberGetter(member)); } member.getAutoConstructClassIfExists() .ifPresent(autoConstructClass -> result.add(existenceCheckGetter(member, autoConstructClass))); if (shouldGenerateDeprecatedNameGetter(member)) { result.add(deprecatedMemberGetter(member)); } result.add(memberGetter(member)); return checkDeprecated(member, result).stream(); } private boolean shouldGenerateDeprecatedNameGetter(MemberModel member) { return StringUtils.isNotBlank(member.getDeprecatedName()); } private boolean shouldGenerateEnumGetter(MemberModel member) { return member.getEnumType() != null || MemberCopierSpec.isEnumCopyAvailable(member); } private MethodSpec enumMemberGetter(MemberModel member) { return MethodSpec.methodBuilder(member.getFluentEnumGetterMethodName()) .addJavadoc("$L", member.getGetterDocumentation()) .addModifiers(PUBLIC) .returns(typeProvider.enumReturnType(member)) .addCode(enumGetterStatement(member)) .build(); } private MethodSpec memberGetter(MemberModel member) { return MethodSpec.methodBuilder(member.getFluentGetterMethodName()) .addJavadoc("$L", member.getGetterDocumentation()) .addModifiers(PUBLIC) .returns(typeProvider.returnType(member)) .addCode(getterStatement(member)) .build(); } private MethodSpec existenceCheckGetter(MemberModel member, ClassName autoConstructClass) { return MethodSpec.methodBuilder(member.getExistenceCheckMethodName()) .addJavadoc("$L", member.getExistenceCheckDocumentation()) .addModifiers(PUBLIC) .returns(TypeName.BOOLEAN) .addCode(existenceCheckStatement(member, autoConstructClass)) .build(); } private CodeBlock existenceCheckStatement(MemberModel member, ClassName autoConstructClass) { String variableName = member.getVariable().getVariableName(); return CodeBlock.of("return $N != null && !($N instanceof $T);", variableName, variableName, autoConstructClass); } private MethodSpec deprecatedMemberGetter(MemberModel member) { return MethodSpec.methodBuilder(member.getDeprecatedFluentGetterMethodName()) .addJavadoc("$L", member.getDeprecatedGetterDocumentation()) .addModifiers(PUBLIC) .addAnnotation(Deprecated.class) .returns(typeProvider.returnType(member)) .addCode(getterStatement(member)) .build(); } private CodeBlock enumGetterStatement(MemberModel member) { String fieldName = member.getVariable().getVariableName(); if (member.isList() || member.isMap()) { Optional<ClassName> copier = serviceModelCopiers.copierClassFor(member); if (!copier.isPresent()) { throw new IllegalStateException("Don't know how to copy " + fieldName + " with enum elements!"); } return CodeBlock.of("return $T.$N($N);", copier.get(), serviceModelCopiers.stringToEnumCopyMethodName(), fieldName); } else { ClassName enumClass = poetExtensions.getModelClass(member.getEnumType()); return CodeBlock.of("return $T.fromValue($N);", enumClass, fieldName); } } private CodeBlock getterStatement(MemberModel model) { VariableModel modelVariable = model.getVariable(); return CodeBlock.of("return $N;", modelVariable.getVariableName()); } private List<TypeSpec> nestedModelClassTypes() { List<TypeSpec> nestedClasses = new ArrayList<>(); switch (shapeModel.getShapeType()) { case Model: case Request: case Response: case Exception: nestedClasses.add(modelBuilderSpecs.builderInterface()); nestedClasses.add(modelBuilderSpecs.beanStyleBuilder()); break; default: break; } if (shapeModel.isUnion()) { nestedClasses.add(modelBuilderSpecs.unionTypeClass()); } return nestedClasses; } private MethodSpec constructor() { MethodSpec.Builder ctorBuilder = MethodSpec.constructorBuilder() .addParameter(modelBuilderSpecs.builderImplName(), "builder"); if (shapeModel.isEvent()) { ctorBuilder.addModifiers(Modifier.PROTECTED); } else { ctorBuilder.addModifiers(PRIVATE); } if (isRequest() || isResponse()) { ctorBuilder.addStatement("super(builder)"); } shapeModelSpec.fields().forEach(f -> ctorBuilder.addStatement("this.$N = builder.$N", f, f)); if (shapeModel.isUnion()) { ctorBuilder.addStatement("this.type = builder.type"); } return ctorBuilder.build(); } private MethodSpec exceptionConstructor() { MethodSpec.Builder ctorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(modelBuilderSpecs.builderImplName(), "builder"); ctorBuilder.addStatement("super(builder)"); shapeModelSpec.fields().forEach(f -> ctorBuilder.addStatement("this.$N = builder.$N", f, f)); return ctorBuilder.build(); } private MethodSpec builderMethod() { return MethodSpec.methodBuilder("builder") .addModifiers(PUBLIC, STATIC) .returns(modelBuilderSpecs.builderInterfaceName()) .addStatement("return new $T()", modelBuilderSpecs.builderImplName()) .build(); } private MethodSpec toBuilderMethod() { return MethodSpec.methodBuilder("toBuilder") .addModifiers(PUBLIC) .addAnnotation(Override.class) .returns(modelBuilderSpecs.builderInterfaceName()) .addStatement("return new $T(this)", modelBuilderSpecs.builderImplName()) .build(); } private MethodSpec serializableBuilderClass() { return MethodSpec.methodBuilder("serializableBuilderClass") .addModifiers(PUBLIC, STATIC) .returns(ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(modelBuilderSpecs.builderInterfaceName()))) .addStatement("return $T.class", modelBuilderSpecs.builderImplName()) .build(); } private MethodSpec copyMethod() { ParameterizedTypeName consumerParam = ParameterizedTypeName.get(ClassName.get(Consumer.class), WildcardTypeName.supertypeOf(modelBuilderSpecs.builderInterfaceName())); return MethodSpec.methodBuilder("copy") .addModifiers(PUBLIC, FINAL) .addAnnotation(Override.class) .addParameter(consumerParam, "modifier") .addStatement("return $T.super.copy(modifier)", ToCopyableBuilder.class) .returns(className()) .build(); } private boolean isResponse() { return shapeModel.getShapeType() == ShapeType.Response; } private boolean isRequest() { return shapeModel.getShapeType() == ShapeType.Request; } private boolean isEvent() { return shapeModel.isEvent(); } private List<MethodSpec> eventStreamInterfaceEventBuilderMethods() { return shapeModel.getMembers().stream() .filter(m -> m.getShape().isEvent()) .map(this::eventBuilderMethod) .collect(Collectors.toList()); } private MethodSpec eventBuilderMethod(MemberModel event) { EventStreamSpecHelper specHelper = new EventStreamSpecHelper(shapeModel, intermediateModel); ClassName eventClassName = specHelper.eventClassName(event); ClassName returnType; if (specHelper.useLegacyGenerationScheme(event)) { returnType = eventClassName.nestedClass("Builder"); } else { ClassName baseClass = poetExtensions.getModelClass(event.getShape().getShapeName()); returnType = baseClass.nestedClass("Builder"); } String methodName = specHelper.eventBuilderMethodName(event); return MethodSpec.methodBuilder(methodName) .addModifiers(PUBLIC, STATIC) .returns(returnType) .addJavadoc("Create a builder for the {@code $L} event type for this stream.", event.getC2jName()) .addStatement("return $T.builder()", eventClassName) .build(); } private List<MethodSpec> addModifier(List<MethodSpec> specs, Modifier modifier) { return specs.stream() .map(spec -> addModifier(spec, modifier)) .collect(Collectors.toList()); } private MethodSpec addModifier(MethodSpec spec, Modifier modifier) { return spec.toBuilder().addModifiers(modifier).build(); } private boolean useLegacyEventGenerationScheme(ShapeModel eventStream) { EventStreamSpecHelper helper = new EventStreamSpecHelper(eventStream, intermediateModel); // This is hacky, but there's no better solution without // extensive refactoring. We basically need to know if any of // the *event types* within this even stream have this // customization enabled, which requires knowing the // MemberModel that has this given shape. for (MemberModel member : eventStream.getMembers()) { if (member.getShape().equals(shapeModel) && helper.useLegacyGenerationScheme(member)) { return true; } } return false; } private Optional<MemberModel> findLegacyGenerationEventWithShape(ShapeModel eventStream) { EventStreamSpecHelper helper = new EventStreamSpecHelper(eventStream, intermediateModel); for (MemberModel member : eventStream.getMembers()) { if (member.getShape().equals(shapeModel) && helper.useLegacyGenerationScheme(member)) { return Optional.ofNullable(member); } } return Optional.empty(); } }
3,441
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/model/AccessorsFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; 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.poet.PoetExtension; class AccessorsFactory { private final ShapeModel shapeModel; private final TypeProvider typeProvider; private final IntermediateModel intermediateModel; private final BeanGetterHelper getterHelper; AccessorsFactory(ShapeModel shapeModel, IntermediateModel intermediateModel, TypeProvider typeProvider, PoetExtension poetExtensions) { this.shapeModel = shapeModel; this.typeProvider = typeProvider; this.intermediateModel = intermediateModel; this.getterHelper = new BeanGetterHelper(poetExtensions, new ServiceModelCopiers(intermediateModel), typeProvider); } public MethodSpec beanStyleGetter(MemberModel memberModel) { return getterHelper.beanStyleGetter(memberModel); } public List<MethodSpec> fluentSetterDeclarations(MemberModel memberModel, TypeName returnType) { if (memberModel.isList()) { return new ListSetters(intermediateModel, shapeModel, memberModel, typeProvider).fluentDeclarations(returnType); } if (memberModel.isMap()) { return new MapSetters(intermediateModel, shapeModel, memberModel, typeProvider).fluentDeclarations(returnType); } return new NonCollectionSetters(intermediateModel, shapeModel, memberModel, typeProvider).fluentDeclarations(returnType); } public List<MethodSpec> convenienceSetterDeclarations(MemberModel memberModel, TypeName returnType) { return intermediateModel.getCustomizationConfig().getConvenienceTypeOverloads().stream() .filter(c -> c.accepts(shapeModel, memberModel)) .map(s -> new NonCollectionSetters(intermediateModel, shapeModel, memberModel, typeProvider).convenienceDeclaration(returnType, s)) .collect(Collectors.toList()); } public List<MethodSpec> fluentSetters(MemberModel memberModel, TypeName returnType) { if (memberModel.isList()) { return new ListSetters(intermediateModel, shapeModel, memberModel, typeProvider).fluent(returnType); } if (memberModel.isMap()) { return new MapSetters(intermediateModel, shapeModel, memberModel, typeProvider).fluent(returnType); } return new NonCollectionSetters(intermediateModel, shapeModel, memberModel, typeProvider).fluent(returnType); } public List<MethodSpec> beanStyleSetters(MemberModel memberModel) { if (memberModel.isList()) { return new ListSetters(intermediateModel, shapeModel, memberModel, typeProvider).beanStyle(); } if (memberModel.isMap()) { return new MapSetters(intermediateModel, shapeModel, memberModel, typeProvider).beanStyle(); } return new NonCollectionSetters(intermediateModel, shapeModel, memberModel, typeProvider).beanStyle(); } public List<MethodSpec> convenienceSetters(MemberModel memberModel, TypeName returnType) { List<MethodSpec> convenienceSetters = new ArrayList<>(); intermediateModel.getCustomizationConfig().getConvenienceTypeOverloads().stream() .filter(c -> c.accepts(shapeModel, memberModel)) .forEach(s -> convenienceSetters.add( new NonCollectionSetters(intermediateModel, shapeModel, memberModel, typeProvider) .fluentConvenience(returnType, s))); return convenienceSetters; } }
3,442
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/model/ServiceClientConfigurationUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.WildcardTypeName; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.lang.model.element.Modifier; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeSpecUtils; import software.amazon.awssdk.core.client.config.ClientOption; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeProvider; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.Validate; public class ServiceClientConfigurationUtils { private final AuthSchemeSpecUtils authSchemeSpecUtils; private final ClassName configurationClassName; private final ClassName configurationBuilderClassName; private final List<Field> fields; public ServiceClientConfigurationUtils(IntermediateModel model) { String basePackage = model.getMetadata().getFullClientPackageName(); String serviceId = model.getMetadata().getServiceName(); configurationClassName = ClassName.get(basePackage, serviceId + "ServiceClientConfiguration"); configurationBuilderClassName = ClassName.get(model.getMetadata().getFullClientInternalPackageName(), serviceId + "ServiceClientConfigurationBuilder"); authSchemeSpecUtils = new AuthSchemeSpecUtils(model); fields = fields(); } /** * Returns the {@link ClassName} of the service client configuration class. */ public ClassName serviceClientConfigurationClassName() { return configurationClassName; } /** * Returns the {@link ClassName} of the builder for the service client configuration class. */ public ClassName serviceClientConfigurationBuilderClassName() { return configurationBuilderClassName; } /** * Returns the list of fields present in the service client configuration class with its corresponding {@link ClientOption} * mapping to the {@link SdkClientConfiguration} class. */ public List<Field> serviceClientConfigurationFields() { return Collections.unmodifiableList(fields); } private List<Field> fields() { return Arrays.asList( overrideConfigurationField(), endpointOverrideField(), endpointProviderField(), regionField(), credentialsProviderField(), authSchemesField(), authSchemeProviderField() ); } private Field overrideConfigurationField() { return fieldBuilder("overrideConfiguration", ClientOverrideConfiguration.class) .doc("client override configuration") .localSetter(basicLocalSetterCode("overrideConfiguration")) .localGetter(basicLocalGetterCode("overrideConfiguration")) .configSetter(overrideConfigurationConfigSetter()) .configGetter(overrideConfigurationConfigGetter()) .build(); } private CodeBlock overrideConfigurationConfigSetter() { return CodeBlock.builder() .addStatement("config.putAll(overrideConfiguration)", SdkClientConfiguration.class) .addStatement("return this") .build(); } private CodeBlock overrideConfigurationConfigGetter() { return CodeBlock.of("return config.asOverrideConfigurationBuilder().build();"); } private Field endpointOverrideField() { return fieldBuilder("endpointOverride", URI.class) .doc("endpoint override") .localSetter(basicLocalSetterCode("endpointOverride")) .localGetter(basicLocalGetterCode("endpointOverride")) .configSetter(endpointOverrideConfigSetter()) .configGetter(endpointOverrideConfigGetter()) .build(); } private CodeBlock endpointOverrideConfigSetter() { return CodeBlock.builder() .beginControlFlow("if (endpointOverride != null)") .addStatement("config.option($T.ENDPOINT, endpointOverride)", SdkClientOption.class) .addStatement("config.option($T.ENDPOINT_OVERRIDDEN, true)", SdkClientOption.class) .nextControlFlow("else") .addStatement("config.option($T.ENDPOINT, null)", SdkClientOption.class) .addStatement("config.option($T.ENDPOINT_OVERRIDDEN, false)", SdkClientOption.class) .endControlFlow() .addStatement("return this") .build(); } private CodeBlock endpointOverrideConfigGetter() { return CodeBlock.builder() .beginControlFlow("if (Boolean.TRUE.equals(config.option($T.ENDPOINT_OVERRIDDEN)))", SdkClientOption.class) .addStatement("return config.option($T.ENDPOINT)", SdkClientOption.class) .endControlFlow() .addStatement("return null") .build(); } private Field endpointProviderField() { return fieldBuilder("endpointProvider", EndpointProvider.class) .doc("endpoint provider") .localSetter(basicLocalSetterCode("endpointProvider")) .localGetter(basicLocalGetterCode("endpointProvider")) .configSetter(basicConfigSetterCode(SdkClientOption.ENDPOINT_PROVIDER, "endpointProvider")) .configGetter(basicConfigGetterCode(SdkClientOption.ENDPOINT_PROVIDER)) .build(); } private Field regionField() { return fieldBuilder("region", Region.class) .doc("AWS region") .localSetter(basicLocalSetterCode("region")) .localGetter(basicLocalGetterCode("region")) .configSetter(basicConfigSetterCode(AwsClientOption.AWS_REGION, "region")) .configGetter(basicConfigGetterCode(AwsClientOption.AWS_REGION)) .build(); } private Field credentialsProviderField() { TypeName awsIdentityProviderType = ParameterizedTypeName.get(ClassName.get(IdentityProvider.class), WildcardTypeName.subtypeOf(AwsCredentialsIdentity.class)); return fieldBuilder("credentialsProvider", awsIdentityProviderType) .doc("credentials provider") .localSetter(basicLocalSetterCode("credentialsProvider")) .localGetter(basicLocalGetterCode("credentialsProvider")) .configSetter(basicConfigSetterCode(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER, "credentialsProvider")) .configGetter(basicConfigGetterCode(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER)) .build(); } private Field authSchemesField() { TypeName authSchemeGenericType = ParameterizedTypeName.get(ClassName.get(AuthScheme.class), WildcardTypeName.subtypeOf(Object.class)); TypeName authSchemesType = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), authSchemeGenericType); return fieldBuilder("authSchemes", authSchemesType) .doc("auth schemes") .setterSpec(authSchemesSetterSpec()) .localSetter(authSchemesLocalSetter()) .localGetter(authSchemesLocalGetter()) .configSetter(authSchemesConfigSetter()) .configGetter(authSchemeConfigGetter()) .build(); } private MethodSpec authSchemesSetterSpec() { TypeName authScheme = ParameterizedTypeName.get(ClassName.get(AuthScheme.class), WildcardTypeName.subtypeOf(Object.class)); return MethodSpec.methodBuilder("putAuthScheme") .addModifiers(Modifier.PUBLIC) .addParameter(authScheme, "authScheme") .returns(configurationClassName.nestedClass("Builder")) .build(); } private CodeBlock authSchemesLocalSetter() { return CodeBlock.builder() .beginControlFlow("if (this.authSchemes == null)") .addStatement("this.authSchemes = new HashMap<>()") .endControlFlow() .addStatement("this.authSchemes.put(authScheme.schemeId(), authScheme)") .addStatement("return this") .build(); } private CodeBlock authSchemesLocalGetter() { return CodeBlock.builder() .addStatement("return $1T.unmodifiableMap(authSchemes == null ? $1T.emptyMap() : authSchemes)", Collections.class) .build(); } private CodeBlock authSchemesConfigSetter() { return CodeBlock.builder() .addStatement("config.computeOptionIfAbsent($T.AUTH_SCHEMES, $T::new)" + ".put(authScheme.schemeId(), authScheme)", SdkClientOption.class, HashMap.class) .addStatement("return this") .build(); } private CodeBlock authSchemeConfigGetter() { return CodeBlock.builder() .addStatement("$T<$T, $T<?>> authSchemes = config.option($T.AUTH_SCHEMES)", Map.class, String.class, AuthScheme.class, SdkClientOption.class) .addStatement("return $1T.unmodifiableMap(authSchemes == null ? $1T.emptyMap() : authSchemes)", Collections.class) .build(); } private Field authSchemeProviderField() { return fieldBuilder("authSchemeProvider", authSchemeSpecUtils.providerInterfaceName()) .doc("auth scheme provider") .isInherited(false) .localSetter(basicLocalSetterCode("authSchemeProvider")) .localGetter(basicLocalGetterCode("authSchemeProvider")) .configSetter(basicConfigSetterCode(SdkClientOption.AUTH_SCHEME_PROVIDER, "authSchemeProvider")) .configGetter(authSchemeProviderConfigGetter()) .build(); } private CodeBlock authSchemeProviderConfigGetter() { return CodeBlock.builder() .addStatement("$T result = config.option($T.AUTH_SCHEME_PROVIDER)", AuthSchemeProvider.class, SdkClientOption.class) .beginControlFlow("if (result == null)") .addStatement("return null") .endControlFlow() .addStatement("return $1T.isInstanceOf($2T.class, result, \"Expected an instance of \" + $2T.class" + ".getSimpleName())", Validate.class, authSchemeSpecUtils.providerInterfaceName()) .build(); } private CodeBlock basicLocalSetterCode(String fieldName) { return CodeBlock.builder() .addStatement("this.$1N = $1N", fieldName) .addStatement("return this") .build(); } private CodeBlock basicLocalGetterCode(String fieldName) { return CodeBlock.of("return $N;", fieldName); } private CodeBlock basicConfigSetterCode(ClientOption<?> option, String parameterName) { return CodeBlock.builder() .addStatement("config.option($T.$N, $N)", option.getClass(), fieldName(option), parameterName) .addStatement("return this") .build(); } private CodeBlock basicConfigGetterCode(ClientOption<?> option) { return CodeBlock.of("return config.option($T.$N);", option.getClass(), fieldName(option)); } public class Field { private final String name; private final TypeName type; private final String doc; private final boolean isInherited; private final MethodSpec setterSpec; private final MethodSpec getterSpec; private final MethodSpec localSetter; private final MethodSpec localGetter; private final MethodSpec configSetter; private final MethodSpec configGetter; Field(FieldBuilder builder) { this.name = Validate.paramNotNull(builder.name, "name"); this.type = Validate.paramNotNull(builder.type, "type"); this.doc = Validate.paramNotNull(builder.doc, "doc"); this.isInherited = Validate.paramNotNull(builder.isInherited, "isInherited"); Validate.paramNotNull(builder.localSetter, "localSetter"); Validate.paramNotNull(builder.localGetter, "localGetter"); Validate.paramNotNull(builder.configSetter, "configSetter"); Validate.paramNotNull(builder.configGetter, "configGetter"); this.setterSpec = setterSpec(builder.setterSpec); this.getterSpec = getterSpec(builder.getterSpec); this.localSetter = setterSpec.toBuilder().addCode(builder.localSetter).build(); this.localGetter = getterSpec.toBuilder().addCode(builder.localGetter).build(); this.configSetter = setterSpec.toBuilder().addCode(builder.configSetter).build(); this.configGetter = getterSpec.toBuilder().addCode(builder.configGetter).build(); } private MethodSpec setterSpec(MethodSpec setterSpec) { if (setterSpec != null) { return setterSpec; } return MethodSpec.methodBuilder(name) .addJavadoc("Sets the value for " + doc) .addModifiers(Modifier.PUBLIC) .returns(configurationClassName.nestedClass("Builder")) .addParameter(type, name) .build(); } private MethodSpec getterSpec(MethodSpec getterSpec) { if (getterSpec != null) { return getterSpec; } return MethodSpec.methodBuilder(name) .addJavadoc("Gets the value for " + doc) .addModifiers(Modifier.PUBLIC) .returns(type) .build(); } public String name() { return name; } public TypeName type() { return type; } public String doc() { return doc; } public boolean isInherited() { return isInherited; } public MethodSpec setterSpec() { return setterSpec; } public MethodSpec getterSpec() { return getterSpec; } public MethodSpec localSetter() { return localSetter; } public MethodSpec localGetter() { return localGetter; } public MethodSpec configSetter() { return configSetter; } public MethodSpec configGetter() { return configGetter; } } public FieldBuilder fieldBuilder(String name, TypeName type) { return new FieldBuilder().name(name).type(type); } public FieldBuilder fieldBuilder(String name, Class<?> type) { return new FieldBuilder().name(name).type(type); } private class FieldBuilder { private String name; private TypeName type; private String doc; private Boolean isInherited = true; private MethodSpec setterSpec; private MethodSpec getterSpec; private CodeBlock localSetter; private CodeBlock localGetter; private CodeBlock configSetter; private CodeBlock configGetter; public FieldBuilder name(String name) { this.name = name; return this; } public FieldBuilder type(Class<?> type) { this.type = ClassName.get(type); return this; } public FieldBuilder type(TypeName type) { this.type = type; return this; } public FieldBuilder doc(String doc) { this.doc = doc; return this; } public FieldBuilder isInherited(Boolean inherited) { isInherited = inherited; return this; } public FieldBuilder setterSpec(MethodSpec setterSpec) { this.setterSpec = setterSpec; return this; } public FieldBuilder getterSpec(MethodSpec getterSpec) { this.getterSpec = getterSpec; return this; } public FieldBuilder localSetter(CodeBlock localSetter) { this.localSetter = localSetter; return this; } public FieldBuilder localGetter(CodeBlock localGetter) { this.localGetter = localGetter; return this; } public FieldBuilder configSetter(CodeBlock configSetter) { this.configSetter = configSetter; return this; } public FieldBuilder configGetter(CodeBlock configGetter) { this.configGetter = configGetter; return this; } public Field build() { return new Field(this); } } /** * This method resolves an static reference to its name, for instance, when called with * <pre> * fieldName(AwsClientOption.AWS_REGION, AwsClientOption.class) * </pre> * it will return the string "AWS_REGION" that we can use for codegen. Using the value directly avoid typo bugs and allows the * compiler and the IDE to know about this relationship. * <p> * This method uses the fully qualified names in the reflection package to avoid polluting this class imports. Adapted from * https://stackoverflow.com/a/35416606 */ private static String fieldName(Object fieldObject) { java.lang.reflect.Field[] allFields = fieldObject.getClass().getFields(); for (java.lang.reflect.Field field : allFields) { int modifiers = field.getModifiers(); if (!java.lang.reflect.Modifier.isStatic(modifiers)) { continue; } Object currentFieldObject; try { // For static fields you can pass a null to get back its value. currentFieldObject = field.get(null); } catch (Exception e) { throw new IllegalArgumentException(e); } boolean isWantedField = fieldObject.equals(currentFieldObject); if (isWantedField) { return field.getName(); } } throw new java.util.NoSuchElementException(String.format("cannot find constant %s in class %s", fieldObject, fieldObject.getClass().getName())); } }
3,443
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/model/ModelBuilderSpecs.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static software.amazon.awssdk.codegen.poet.model.DeprecationUtils.checkDeprecated; 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.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.function.Consumer; import javax.lang.model.element.Modifier; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; 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.ShapeType; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructList; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructMap; import software.amazon.awssdk.core.util.SdkAutoConstructList; import software.amazon.awssdk.core.util.SdkAutoConstructMap; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; /** * Provides the Poet specs for model class builders. */ class ModelBuilderSpecs { private final IntermediateModel intermediateModel; private final ShapeModel shapeModel; private final TypeProvider typeProvider; private final PoetExtension poetExtensions; private final AccessorsFactory accessorsFactory; private final ShapeModelSpec shapeModelSpec; ModelBuilderSpecs(IntermediateModel intermediateModel, ShapeModel shapeModel, TypeProvider typeProvider) { this.intermediateModel = intermediateModel; this.shapeModel = shapeModel; this.typeProvider = typeProvider; this.poetExtensions = new PoetExtension(this.intermediateModel); this.accessorsFactory = new AccessorsFactory(this.shapeModel, this.intermediateModel, this.typeProvider, poetExtensions); this.shapeModelSpec = new ShapeModelSpec(shapeModel, typeProvider, poetExtensions, intermediateModel); } public ClassName builderInterfaceName() { return classToBuild().nestedClass("Builder"); } public ClassName builderImplName() { return classToBuild().nestedClass("BuilderImpl"); } public TypeSpec builderInterface() { TypeSpec.Builder builder = TypeSpec.interfaceBuilder(builderInterfaceName()) .addSuperinterfaces(builderSuperInterfaces()) .addModifiers(PUBLIC); shapeModel.getNonStreamingMembers() .forEach(m -> { builder.addMethods( checkDeprecated(m, accessorsFactory.fluentSetterDeclarations(m, builderInterfaceName()))); builder.addMethods( checkDeprecated(m, accessorsFactory.convenienceSetterDeclarations(m, builderInterfaceName()))); }); if (isException()) { builder.addSuperinterface(parentExceptionBuilder().nestedClass("Builder")); builder.addMethods(ExceptionProperties.builderInterfaceMethods(builderInterfaceName())); } if (isRequest()) { builder.addMethod(MethodSpec.methodBuilder("overrideConfiguration") .returns(builderInterfaceName()) .addAnnotation(Override.class) .addParameter(AwsRequestOverrideConfiguration.class, "overrideConfiguration") .addModifiers(PUBLIC, Modifier.ABSTRACT) .build()); builder.addMethod(MethodSpec.methodBuilder("overrideConfiguration") .addAnnotation(Override.class) .returns(builderInterfaceName()) .addParameter(ParameterizedTypeName.get(Consumer.class, AwsRequestOverrideConfiguration.Builder.class), "builderConsumer") .addModifiers(PUBLIC, Modifier.ABSTRACT) .build()); } return builder.build(); } public TypeSpec beanStyleBuilder() { TypeSpec.Builder builderClassBuilder = TypeSpec.classBuilder(builderImplName()) .addSuperinterface(builderInterfaceName()) // TODO: Uncomment this once property shadowing is fixed //.addSuperinterface(copyableBuilderSuperInterface()) .superclass(builderImplSuperClass()) .addModifiers(Modifier.STATIC); if (!isEvent()) { builderClassBuilder.addModifiers(Modifier.FINAL); } else { builderClassBuilder.addModifiers(Modifier.PROTECTED); } if (isException()) { builderClassBuilder.superclass(parentExceptionBuilder().nestedClass("BuilderImpl")); } builderClassBuilder.addFields(fields()); builderClassBuilder.addMethod(noargConstructor()); builderClassBuilder.addMethod(modelCopyConstructor()); builderClassBuilder.addMethods(accessors()); builderClassBuilder.addMethod(buildMethod()); builderClassBuilder.addMethod(sdkFieldsMethod()); if (shapeModel.isUnion()) { builderClassBuilder.addMethod(handleUnionValueChangeMethod()); } return builderClassBuilder.build(); } private ClassName parentExceptionBuilder() { String customExceptionBase = intermediateModel.getCustomizationConfig() .getSdkModeledExceptionBaseClassName(); if (customExceptionBase != null) { return poetExtensions.getModelClass(customExceptionBase); } return poetExtensions.getModelClass(intermediateModel.getSdkModeledExceptionBaseClassName()); } private MethodSpec sdkFieldsMethod() { ParameterizedTypeName sdkFieldType = ParameterizedTypeName.get(ClassName.get(SdkField.class), WildcardTypeName.subtypeOf(ClassName.get(Object.class))); return MethodSpec.methodBuilder("sdkFields") .addModifiers(PUBLIC) .addAnnotation(Override.class) .returns(ParameterizedTypeName.get(ClassName.get(List.class), sdkFieldType)) .addCode("return SDK_FIELDS;") .build(); } private TypeName builderImplSuperClass() { if (isRequest()) { return new AwsServiceBaseRequestSpec(intermediateModel).className().nestedClass("BuilderImpl"); } if (isResponse()) { return new AwsServiceBaseResponseSpec(intermediateModel).className().nestedClass("BuilderImpl"); } return ClassName.OBJECT; } private List<FieldSpec> fields() { List<FieldSpec> fields = new ArrayList<>(); for (MemberModel member : shapeModel.getNonStreamingMembers()) { FieldSpec fieldSpec = typeProvider.asField(member, Modifier.PRIVATE); if (member.isList()) { fieldSpec = fieldSpec.toBuilder() .initializer("$T.getInstance()", DefaultSdkAutoConstructList.class) .build(); } else if (member.isMap()) { fieldSpec = fieldSpec.toBuilder() .initializer("$T.getInstance()", DefaultSdkAutoConstructMap.class) .build(); } fields.add(fieldSpec); } if (shapeModel.isUnion()) { ClassName unionType = shapeModelSpec.className().nestedClass("Type"); fields.add(FieldSpec.builder(unionType, "type", PRIVATE) .initializer("$T.UNKNOWN_TO_SDK_VERSION", unionType) .build()); fields.add(FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(Set.class), unionType), "setTypes", PRIVATE) .initializer("$T.noneOf($T.class)", EnumSet.class, unionType) .build()); } return fields; } private MethodSpec noargConstructor() { Modifier modifier = isEvent() ? Modifier.PROTECTED : Modifier.PRIVATE; MethodSpec.Builder ctorBuilder = MethodSpec.constructorBuilder() .addModifiers(modifier); return ctorBuilder.build(); } private MethodSpec modelCopyConstructor() { Modifier modifier = isEvent() ? Modifier.PROTECTED : Modifier.PRIVATE; MethodSpec.Builder copyBuilderCtor = MethodSpec.constructorBuilder() .addModifiers(modifier) .addParameter(classToBuild(), "model"); if (isRequest() || isResponse() || isException()) { copyBuilderCtor.addCode("super(model);"); } shapeModel.getNonStreamingMembers().forEach(m -> { String name = m.getVariable().getVariableName(); copyBuilderCtor.addStatement("$N(model.$N)", m.getFluentSetterMethodName(), name); }); return copyBuilderCtor.build(); } private List<MethodSpec> accessors() { List<MethodSpec> accessors = new ArrayList<>(); shapeModel.getNonStreamingMembers() .forEach(m -> { accessors.add(checkDeprecated(m, accessorsFactory.beanStyleGetter(m))); accessors.addAll(checkDeprecated(m, accessorsFactory.beanStyleSetters(m))); accessors.addAll(checkDeprecated(m, accessorsFactory.fluentSetters(m, builderInterfaceName()))); accessors.addAll(checkDeprecated(m, accessorsFactory.convenienceSetters(m, builderInterfaceName()))); }); if (isException()) { accessors.addAll(ExceptionProperties.builderImplMethods(builderImplName())); } if (isRequest()) { accessors.add(MethodSpec.methodBuilder("overrideConfiguration") .addAnnotation(Override.class) .returns(builderInterfaceName()) .addParameter(AwsRequestOverrideConfiguration.class, "overrideConfiguration") .addModifiers(PUBLIC) .addStatement("super.overrideConfiguration(overrideConfiguration)") .addStatement("return this") .build()); accessors.add(MethodSpec.methodBuilder("overrideConfiguration") .addAnnotation(Override.class) .returns(builderInterfaceName()) .addParameter(ParameterizedTypeName.get(Consumer.class, AwsRequestOverrideConfiguration.Builder.class), "builderConsumer") .addModifiers(PUBLIC) .addStatement("super.overrideConfiguration(builderConsumer)") .addStatement("return this") .build()); } return accessors; } private MethodSpec buildMethod() { return MethodSpec.methodBuilder("build") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(classToBuild()) .addStatement("return new $T(this)", classToBuild()) .build(); } private ClassName classToBuild() { return shapeModelSpec.className(); } private boolean isException() { return shapeModel.getShapeType() == ShapeType.Exception; } private boolean isRequest() { return shapeModel.getShapeType() == ShapeType.Request; } private boolean isResponse() { return shapeModel.getShapeType() == ShapeType.Response; } private boolean isEvent() { return shapeModel.isEvent(); } private List<TypeName> builderSuperInterfaces() { List<TypeName> superInterfaces = new ArrayList<>(); if (isRequest()) { superInterfaces.add(new AwsServiceBaseRequestSpec(intermediateModel).className().nestedClass("Builder")); } if (isResponse()) { superInterfaces.add(new AwsServiceBaseResponseSpec(intermediateModel).className().nestedClass("Builder")); } superInterfaces.add(ClassName.get(SdkPojo.class)); superInterfaces.add(ParameterizedTypeName.get(ClassName.get(CopyableBuilder.class), classToBuild().nestedClass("Builder"), classToBuild())); return superInterfaces; } public TypeSpec unionTypeClass() { Validate.isTrue(shapeModel.isUnion(), "%s was not a union.", shapeModel.getShapeName()); TypeSpec.Builder type = TypeSpec.enumBuilder("Type") .addJavadoc("@see $L#type()", shapeModel.getShapeName()) .addModifiers(PUBLIC); for (MemberModel member : shapeModel.getMembers()) { type.addEnumConstant(member.getUnionEnumTypeName()); } type.addEnumConstant("UNKNOWN_TO_SDK_VERSION"); return type.build(); } private MethodSpec handleUnionValueChangeMethod() { CodeBlock body = CodeBlock.builder() .beginControlFlow("if (this.type == type || oldValue == newValue)") .addStatement("return") .endControlFlow() .beginControlFlow("if (newValue == null || newValue instanceof $T || newValue instanceof $T)", SdkAutoConstructList.class, SdkAutoConstructMap.class) .addStatement("setTypes.remove(type)") .nextControlFlow("else if (oldValue == null || oldValue instanceof $T || oldValue instanceof $T)", SdkAutoConstructList.class, SdkAutoConstructMap.class) .addStatement("setTypes.add(type)") .endControlFlow() .beginControlFlow("if (setTypes.size() == 1)") .addStatement("this.type = setTypes.iterator().next()") .nextControlFlow("else if (setTypes.isEmpty())") .addStatement("this.type = Type.UNKNOWN_TO_SDK_VERSION") .nextControlFlow("else") .addStatement("this.type = null") .endControlFlow() .build(); return MethodSpec.methodBuilder("handleUnionValueChange") .addModifiers(PRIVATE, FINAL) .returns(void.class) .addParameter(shapeModelSpec.className().nestedClass("Type"), "type") .addParameter(Object.class, "oldValue") .addParameter(Object.class, "newValue") .addCode(body) .build(); } }
3,444
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/model/ListSetters.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ArrayTypeName; 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.TypeName; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Consumer; 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.ShapeModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.utils.Validate; class ListSetters extends AbstractMemberSetters { private final TypeProvider typeProvider; private final PoetExtension poetExtensions; ListSetters(IntermediateModel intermediateModel, ShapeModel shapeModel, MemberModel memberModel, TypeProvider typeProvider) { super(intermediateModel, shapeModel, memberModel, typeProvider); this.typeProvider = typeProvider; this.poetExtensions = new PoetExtension(intermediateModel); } @Override public List<MethodSpec> fluentDeclarations(TypeName returnType) { List<MethodSpec> fluentDeclarations = new ArrayList<>(); String setterDocumentation = memberModel().getFluentSetterDocumentation(); fluentDeclarations.add(fluentAbstractSetterDeclaration(memberAsParameter(), returnType) .addJavadoc("$L", setterDocumentation) .build()); fluentDeclarations.add(fluentAbstractSetterDeclaration(ParameterSpec.builder(asArray(), fieldName()).build(), returnType) .addJavadoc("$L", setterDocumentation) .varargs(true) .build()); TypeName elementType = listElementType(); if (elementModel().hasBuilder()) { fluentDeclarations.add(fluentAbstractSetterDeclaration(ParameterSpec.builder(asConsumerBuilderArray(), fieldName()) .build(), returnType) .varargs(true) .addJavadoc("$L", memberModel().getDefaultConsumerFluentSetterDocumentation( elementType.toString())) .build()); } if (enumTypeInListMemberModel() != null) { // Generate setter with modeled Collections parameter fluentDeclarations.add(fluentAbstractSetterDeclaration(memberModel().getFluentEnumSetterMethodName(), collectionOfModeledEnumAsParameter(), returnType) .addJavadoc("$L", setterDocumentation) .build()); // Generate setter with modeled var args parameter fluentDeclarations.add(fluentAbstractSetterDeclaration(memberModel().getFluentEnumSetterMethodName(), arrayOfModeledEnumAsParameter(), returnType) .varargs(true) .addJavadoc("$L", setterDocumentation) .build()); } return fluentDeclarations; } @Override public List<MethodSpec> fluent(TypeName returnType) { List<MethodSpec> fluent = new ArrayList<>(); fluent.add(fluentCopySetter(returnType)); fluent.add(fluentVarargToListSetter(returnType)); if (elementModel().hasBuilder()) { fluent.add(fluentVarargConsumerBuilderSetter(returnType)); } if (enumTypeInListMemberModel() != null) { // Generate setter with modeled Collections parameter in BuilderImpl fluent.add(fluentEnumCollectionsSetter(memberModel().getFluentEnumSetterMethodName(), collectionOfModeledEnumAsParameter(), returnType)); // Generate setter with modeled var args parameter in BuilderImpl fluent.add(fluentEnumVarargToListSetter(memberModel().getFluentEnumSetterMethodName(), arrayOfModeledEnumAsParameter(), returnType)); } return fluent; } @Override public List<MethodSpec> beanStyle() { MethodSpec.Builder builder = beanStyleSetterBuilder(); builder.addCode(beanCopySetterBody()); return Collections.singletonList(builder.build()); } private MethodSpec fluentCopySetter(TypeName returnType) { return fluentSetterBuilder(returnType) .addCode(copySetterBody() .toBuilder() .addStatement("return this").build()) .build(); } private MethodSpec fluentVarargToListSetter(TypeName returnType) { return fluentSetterBuilder(ParameterSpec.builder(asArray(), fieldName()).build(), returnType) .varargs(true) .addAnnotation(SafeVarargs.class) .addCode(varargToListSetterBody()) .addStatement("return this") .build(); } private MethodSpec fluentVarargConsumerBuilderSetter(TypeName returnType) { return fluentSetterBuilder(ParameterSpec.builder(asConsumerBuilderArray(), fieldName()).build(), returnType) .varargs(true) .addAnnotation(SafeVarargs.class) .addCode(consumerBuilderVarargSetterBody()) .addStatement("return this") .build(); } /** * {@link MethodSpec} to generate fluent setter method implementation that takes a collection of modeled enums as parameter */ private MethodSpec fluentEnumCollectionsSetter(String methodName, ParameterSpec parameter, TypeName returnType) { return fluentSetterBuilder(methodName, parameter, returnType) .addCode(fluentSetterWithEnumCollectionsParameterMethodBody()) .addStatement("return this") .build(); } /** * {@link MethodSpec} to generate fluent setter method implementation that takes var args of modeled enums as parameter */ private MethodSpec fluentEnumVarargToListSetter(String methodName, ParameterSpec parameter, TypeName returnType) { return fluentSetterBuilder(methodName, parameter, returnType) .varargs(true) .addAnnotation(SafeVarargs.class) .addCode(enumVarargToListSetterBody()) .addStatement("return this") .build(); } private CodeBlock varargToListSetterBody() { return CodeBlock.of("$1L($2T.asList($3L));", memberModel().getFluentSetterMethodName(), Arrays.class, fieldName()); } private CodeBlock consumerBuilderVarargSetterBody() { return CodeBlock.of("$1L($3T.of($2L).map(c -> $4T.builder().applyMutation(c).build()).collect($5T.toList()));", memberModel().getFluentSetterMethodName(), fieldName(), Stream.class, listElementType(), Collectors.class); } private CodeBlock enumVarargToListSetterBody() { return CodeBlock.of("$1L($3T.asList($2L));", memberModel().getFluentEnumSetterMethodName(), fieldName(), Arrays.class); } private MemberModel elementModel() { return memberModel().getListModel().getListMemberModel(); } private TypeName modeledEnumElement() { return poetExtensions.getModelClass(enumTypeInListMemberModel()); } private String enumTypeInListMemberModel() { return memberModel().getListModel().getListMemberModel().getEnumType(); } private TypeName listElementType() { return typeProvider.parameterType(elementModel()); } private TypeName listElementConsumerBuilderType() { TypeName listElementType = listElementType(); ClassName classType = Validate.isInstanceOf(ClassName.class, listElementType, "List element type must be of type class, but was %s", listElementType); return classType.nestedClass("Builder"); } private TypeName asConsumerBuilderArray() { ParameterizedTypeName consumerBuilder = ParameterizedTypeName.get(ClassName.get(Consumer.class), listElementConsumerBuilderType()); return ArrayTypeName.of(consumerBuilder); } private ArrayTypeName asArray() { return ArrayTypeName.of(listElementType()); } private ArrayTypeName asArrayOfModeledEnum() { return ArrayTypeName.of(modeledEnumElement()); } private ParameterSpec arrayOfModeledEnumAsParameter() { return ParameterSpec.builder(asArrayOfModeledEnum(), fieldName()).build(); } private ParameterSpec collectionOfModeledEnumAsParameter() { return ParameterSpec.builder(typeProvider.parameterType(memberModel(), true), fieldName()) .build(); } }
3,445
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/model/AwsServiceBaseRequestSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import javax.lang.model.element.Modifier; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; public class AwsServiceBaseRequestSpec implements ClassSpec { private final IntermediateModel intermediateModel; private final PoetExtension poetExtensions; public AwsServiceBaseRequestSpec(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; this.poetExtensions = new PoetExtension(intermediateModel); } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = TypeSpec.classBuilder(className()) .addAnnotation(PoetUtils.generatedAnnotation()) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .superclass(ClassName.get(AwsRequest.class)) .addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PROTECTED) .addParameter(className().nestedClass("Builder"), "builder") .addStatement("super(builder)") .build()) .addMethod(MethodSpec.methodBuilder("toBuilder") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(className().nestedClass("Builder")) .build()) .addType(builderInterfaceSpec()) .addType(builderImplSpec()); return builder.build(); } @Override public ClassName className() { return poetExtensions.getModelClass(intermediateModel.getSdkRequestBaseClassName()); } private TypeSpec builderInterfaceSpec() { return TypeSpec.interfaceBuilder("Builder") .addModifiers(Modifier.PUBLIC) .addSuperinterface(ClassName.get(AwsRequest.class).nestedClass("Builder")) .addMethod(MethodSpec.methodBuilder("build") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(className()) .build()) .build(); } private TypeSpec builderImplSpec() { return TypeSpec.classBuilder("BuilderImpl") .addModifiers(Modifier.PROTECTED, Modifier.STATIC, Modifier.ABSTRACT) .addSuperinterface(className().nestedClass("Builder")) .superclass(ClassName.get(AwsRequest.class).nestedClass("BuilderImpl")) .addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PROTECTED) .build()) .addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PROTECTED) .addParameter(className(), "request") .addStatement("super(request)") .build()) .build(); } }
3,446
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/model/AbstractMemberSetters.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.Collections.emptyList; import static java.util.Collections.singleton; import static software.amazon.awssdk.codegen.poet.model.TypeProvider.ShapeTransformation.USE_BUILDER_IMPL; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; // CHECKSTYLE:OFF java.beans is required for services that use names starting with 'set' to fix bean-based marshalling. import java.beans.Transient; // CHECKSTYLE:ON import java.util.Optional; import java.util.stream.Collectors; 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.intermediate.ShapeModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.model.TypeProvider.TypeNameOptions; import software.amazon.awssdk.core.SdkBytes; /** * Abstract implementation of {@link MemberSetters} to share common functionality. */ abstract class AbstractMemberSetters implements MemberSetters { protected final PoetExtension poetExtensions; private final ShapeModel shapeModel; private final MemberModel memberModel; private final TypeProvider typeProvider; private final ServiceModelCopiers serviceModelCopiers; AbstractMemberSetters(IntermediateModel intermediateModel, ShapeModel shapeModel, MemberModel memberModel, TypeProvider typeProvider) { this.shapeModel = shapeModel; this.memberModel = memberModel; this.typeProvider = typeProvider; this.serviceModelCopiers = new ServiceModelCopiers(intermediateModel); this.poetExtensions = new PoetExtension(intermediateModel); } protected MethodSpec.Builder fluentAbstractSetterDeclaration(ParameterSpec parameter, TypeName returnType) { return fluentSetterDeclaration(parameter, returnType).addModifiers(Modifier.ABSTRACT); } protected MethodSpec.Builder fluentAbstractSetterDeclaration(String methodName, ParameterSpec parameter, TypeName returnType) { return setterDeclaration(methodName, parameter, returnType).addModifiers(Modifier.ABSTRACT); } protected MethodSpec.Builder fluentDefaultSetterDeclaration(ParameterSpec parameter, TypeName returnType) { return fluentSetterDeclaration(parameter, returnType).addModifiers(Modifier.DEFAULT); } protected MethodSpec.Builder fluentSetterBuilder(TypeName returnType) { return fluentSetterBuilder(memberAsParameter(), returnType); } protected MethodSpec.Builder fluentSetterBuilder(String methodName, TypeName returnType) { return fluentSetterBuilder(methodName, memberAsParameter(), returnType); } protected MethodSpec.Builder fluentSetterBuilder(ParameterSpec setterParam, TypeName returnType) { return fluentSetterBuilder(memberModel().getFluentSetterMethodName(), setterParam, returnType); } protected MethodSpec.Builder fluentSetterBuilder(String methodName, ParameterSpec setterParam, TypeName returnType) { return MethodSpec.methodBuilder(methodName) .addParameter(setterParam) .addAnnotation(Override.class) .addAnnotations(maybeTransient(methodName)) .returns(returnType) .addModifiers(Modifier.PUBLIC, Modifier.FINAL); } private Iterable<AnnotationSpec> maybeTransient(String methodName) { if (methodName.startsWith("set")) { return singleton(AnnotationSpec.builder(Transient.class).build()); } return emptyList(); } protected MethodSpec.Builder beanStyleSetterBuilder() { return beanStyleSetterBuilder(memberAsBeanStyleParameter(), memberModel().getBeanStyleSetterMethodName()); } protected MethodSpec.Builder deprecatedBeanStyleSetterBuilder() { return beanStyleSetterBuilder(memberAsBeanStyleParameter(), memberModel().getDeprecatedBeanStyleSetterMethodName()); } protected MethodSpec.Builder beanStyleSetterBuilder(ParameterSpec setterParam, String methodName) { return MethodSpec.methodBuilder(methodName) .addParameter(setterParam) .addModifiers(Modifier.PUBLIC, Modifier.FINAL); } protected CodeBlock copySetterBody() { return copySetterBody("this.$1N = $2T.$3N($1N)", "this.$1N = $1N", serviceModelCopiers.copyMethodName()); } protected CodeBlock fluentSetterWithEnumCollectionsParameterMethodBody() { return copySetterBody("this.$1N = $2T.$3N($1N)", "this.$1N = $1N", serviceModelCopiers.enumToStringCopyMethodName()); } protected CodeBlock copySetterBodyWithModeledEnumParameter() { return copySetterBody("this.$1N = $2T.$3N($1N)", "this.$1N = $1N", serviceModelCopiers.enumToStringCopyMethodName()); } protected CodeBlock copySetterBuilderBody() { if (memberModel.hasBuilder()) { return copySetterBody("this.$1N = $1N != null ? $2T.$3N($1N.build()) : null", "this.$1N = $1N != null ? $1N.build() : null", serviceModelCopiers.copyMethodName()); } if (memberModel.containsBuildable()) { return copySetterBody("this.$1N = $2T.$3N($1N)", null, serviceModelCopiers.copyFromBuilderMethodName()); } return copySetterBody(); } protected CodeBlock beanCopySetterBody() { if (memberModel.isSdkBytesType()) { return sdkBytesSetter(); } if (memberModel.isList() && memberModel.getListModel().getListMemberModel().isSdkBytesType()) { return sdkBytesListSetter(); } if (memberModel.isMap() && memberModel.getMapModel().getValueModel().isSdkBytesType()) { return sdkBytesMapValueSetter(); } return copySetterBuilderBody(); } private CodeBlock sdkBytesSetter() { return CodeBlock.of("$1N($2N == null ? null : $3T.fromByteBuffer($2N));", memberModel.getFluentSetterMethodName(), fieldName(), SdkBytes.class); } private CodeBlock sdkBytesListSetter() { return CodeBlock.of("$1N($2N == null ? null : $2N.stream().map($3T::fromByteBuffer).collect($4T.toList()));", memberModel.getFluentSetterMethodName(), fieldName(), SdkBytes.class, Collectors.class); } private CodeBlock sdkBytesMapValueSetter() { return CodeBlock.of("$1N($2N == null ? null : " + "$2N.entrySet().stream()" + ".collect($4T.toMap(e -> e.getKey(), e -> $3T.fromByteBuffer(e.getValue()))));", memberModel.getFluentSetterMethodName(), fieldName(), SdkBytes.class, Collectors.class); } protected ParameterSpec memberAsParameter() { return ParameterSpec.builder(typeProvider.parameterType(memberModel), fieldName()).build(); } protected ParameterSpec memberAsBeanStyleParameter() { TypeName type = typeProvider.typeName(memberModel, new TypeNameOptions().shapeTransformation(USE_BUILDER_IMPL) .useSubtypeWildcardsForCollections(true) .useCollectionForList(true) .useByteBufferTypes(true)); return ParameterSpec.builder(type, fieldName()).build(); } protected ShapeModel shapeModel() { return shapeModel; } protected MemberModel memberModel() { return memberModel; } protected String fieldName() { return memberModel.getVariable().getVariableName(); } private MethodSpec.Builder fluentSetterDeclaration(ParameterSpec parameter, TypeName returnType) { return setterDeclaration(memberModel().getFluentSetterMethodName(), parameter, returnType); } private MethodSpec.Builder setterDeclaration(String methodName, ParameterSpec parameter, TypeName returnType) { return MethodSpec.methodBuilder(methodName) .addModifiers(Modifier.PUBLIC) .addParameter(parameter) .returns(returnType); } private CodeBlock copySetterBody(String copyAssignment, String regularAssignment, String copyMethodName) { CodeBlock.Builder body = CodeBlock.builder(); if (shapeModel.isUnion()) { body.addStatement("Object oldValue = this.$N", fieldName()); } Optional<ClassName> copierClass = serviceModelCopiers.copierClassFor(memberModel); if (copierClass.isPresent()) { body.addStatement(copyAssignment, fieldName(), copierClass.get(), copyMethodName); } else { body.addStatement(regularAssignment, fieldName()); } if (shapeModel.isUnion()) { body.addStatement("handleUnionValueChange(Type.$N, oldValue, this.$N)", memberModel.getUnionEnumTypeName(), fieldName()); } return body.build(); } }
3,447
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/rules/EndpointRulesClientTestSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.codegen.poet.rules.TestGeneratorUtils.getHostPrefixTemplate; import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.jr.stree.JrsArray; import com.fasterxml.jackson.jr.stree.JrsObject; import com.fasterxml.jackson.jr.stree.JrsValue; import com.squareup.javapoet.AnnotationSpec; 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.TypeSpec; import java.net.URI; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import javax.lang.model.element.Modifier; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; 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.ParameterHttpMapping; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.rules.endpoints.EndpointTestModel; import software.amazon.awssdk.codegen.model.rules.endpoints.EndpointTestSuiteModel; import software.amazon.awssdk.codegen.model.rules.endpoints.OperationInput; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterModel; import software.amazon.awssdk.codegen.model.service.ClientContextParam; import software.amazon.awssdk.codegen.model.service.Location; 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.utils.AuthUtils; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.rules.testing.AsyncTestCase; import software.amazon.awssdk.core.rules.testing.BaseRuleSetClientTest; import software.amazon.awssdk.core.rules.testing.SyncTestCase; import software.amazon.awssdk.core.rules.testing.util.EmptyPublisher; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.Validate; public class EndpointRulesClientTestSpec implements ClassSpec { /** * Many of the services, (especially the services whose rules are completely auto generated), share a same set of tests * that fail for the SDK (with a valid reason). */ private static final Map<String, String> GLOBAL_SKIP_ENDPOINT_TESTS; static { Map<String, String> tests = new HashMap<>(); tests.put("For region us-iso-west-1 with FIPS enabled and DualStack enabled", "Client builder does the validation"); tests.put("For region us-iso-west-1 with FIPS disabled and DualStack enabled", "Client builder does the validation"); tests.put("For region us-iso-east-1 with FIPS enabled and DualStack enabled", "Client builder does the validation"); tests.put("For region us-iso-east-1 with FIPS disabled and DualStack enabled", "Client builder does the validation"); tests.put("For region us-isob-east-1 with FIPS enabled and DualStack enabled", "Client builder does the validation"); tests.put("For region us-isob-east-1 with FIPS disabled and DualStack enabled", "Client builder does the validation"); tests.put("For region us-isob-west-1 with FIPS enabled and DualStack enabled", "Client builder does the validation"); tests.put("For region us-isob-west-1 with FIPS disabled and DualStack enabled", "Client builder does the validation"); tests.put("Missing region", "Client does validation"); GLOBAL_SKIP_ENDPOINT_TESTS = Collections.unmodifiableMap(tests); } private final IntermediateModel model; private final EndpointRulesSpecUtils endpointRulesSpecUtils; private final PoetExtension poetExtension; public EndpointRulesClientTestSpec(IntermediateModel model) { this.model = model; this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); this.poetExtension = new PoetExtension(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder b = PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.PUBLIC) .superclass(BaseRuleSetClientTest.class); if (endpointRulesSpecUtils.isS3()) { b.addField(s3RegionEndpointSystemPropertySaveValueField()); } if (!shouldGenerateClientEndpointTests()) { return b.build(); } b.addMethod(methodSetupMethod()); b.addMethod(teardownMethod()); if (hasSyncClient()) { b.addMethod(syncTest()); } b.addMethod(asyncTest()); if (hasSyncClient()) { b.addMethod(syncTestsSourceMethod()); } b.addMethod(asyncTestsSourceMethod()); return b.build(); } @Override public ClassName className() { return endpointRulesSpecUtils.clientEndpointTestsName(); } private String findDefaultRequest() { Map<String, OperationModel> operations = this.model.getOperations(); // If this is an endpoint discovery service, then use the endpoint // operation since it goes to the service endpoint Optional<String> endpointOperation = operations.entrySet() .stream() .filter(e -> e.getValue().isEndpointOperation()) .map(Map.Entry::getKey) .findFirst(); if (endpointOperation.isPresent()) { return endpointOperation.get(); } // Ideally look for something that we don't need to set any parameters // on. That means either a request with no members or one that does not // have any members bound to the URI path Optional<String> name = operations.entrySet().stream() .filter(e -> canBeEmpty(e.getValue())) .findFirst() .map(Map.Entry::getKey); if (name.isPresent()) { return name.get(); } // Settle for a non-streaming operation... Optional<String> nonStreaming = operations.entrySet().stream().filter(e -> !e.getValue().hasStreamingInput() && !e.getValue().hasStreamingOutput()) .map(Map.Entry::getKey) .findFirst(); // Failing that, just pick the first one return nonStreaming.orElseGet(() -> operations.keySet().stream().findFirst().get()); } private MethodSpec syncTest() { AnnotationSpec methodSourceSpec = AnnotationSpec.builder(MethodSource.class) .addMember("value", "$S", "syncTestCases") .build(); MethodSpec.Builder b = MethodSpec.methodBuilder("syncClient_usesCorrectEndpoint") .addModifiers(Modifier.PUBLIC) .addParameter(SyncTestCase.class, "tc") .addAnnotation(methodSourceSpec) .addAnnotation(ParameterizedTest.class) .returns(void.class); b.addStatement("runAndVerify(tc)"); return b.build(); } private MethodSpec asyncTest() { AnnotationSpec methodSourceSpec = AnnotationSpec.builder(MethodSource.class) .addMember("value", "$S", "asyncTestCases") .build(); MethodSpec.Builder b = MethodSpec.methodBuilder("asyncClient_usesCorrectEndpoint") .addModifiers(Modifier.PUBLIC) .addParameter(AsyncTestCase.class, "tc") .addAnnotation(methodSourceSpec) .addAnnotation(ParameterizedTest.class) .returns(void.class); b.addStatement("runAndVerify(tc)"); return b.build(); } private MethodSpec syncTestsSourceMethod() { String defaultOperation = findDefaultRequest(); OperationModel defaultOpModel = model.getOperation(defaultOperation); MethodSpec.Builder b = MethodSpec.methodBuilder("syncTestCases") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(ParameterizedTypeName.get(List.class, SyncTestCase.class)); b.addCode("return $T.asList(", Arrays.class); EndpointTestSuiteModel endpointTestSuiteModel = model.getEndpointTestSuiteModel(); Iterator<EndpointTestModel> testIter = endpointTestSuiteModel.getTestCases().iterator(); boolean isFirst = true; while (testIter.hasNext()) { EndpointTestModel test = testIter.next(); if (testCaseHasOperationInputs(test)) { Iterator<OperationInput> operationInputsIter = test.getOperationInputs().iterator(); if (!isFirst) { b.addCode(", "); } isFirst = false; while (operationInputsIter.hasNext()) { OperationInput opInput = operationInputsIter.next(); OperationModel opModel = model.getOperation(opInput.getOperationName()); b.addCode("new $T($S, $L, $L$L)", SyncTestCase.class, test.getDocumentation(), syncOperationCallLambda(opModel, test.getParams(), opInput.getOperationParams()), TestGeneratorUtils.createExpect(test.getExpect(), opModel, opInput.getOperationParams()), getSkipReasonBlock(test.getDocumentation())); if (operationInputsIter.hasNext()) { b.addCode(","); } } } else if (shouldGenerateClientTestsOverride()) { if (!isFirst) { b.addCode(", "); } isFirst = false; b.addCode("new $T($S, $L, $L$L)", SyncTestCase.class, test.getDocumentation(), syncOperationCallLambda(defaultOpModel, test.getParams(), Collections.emptyMap()), TestGeneratorUtils.createExpect(test.getExpect(), defaultOpModel, null), getSkipReasonBlock(test.getDocumentation())); } } b.addStatement(")"); return b.build(); } private CodeBlock syncOperationCallLambda(OperationModel opModel, Map<String, TreeNode> params, Map<String, TreeNode> opParams) { CodeBlock.Builder b = CodeBlock.builder(); b.beginControlFlow("() -> "); b.addStatement("$T builder = $T.builder()", syncClientBuilder(), syncClientClass()); b.addStatement("builder.credentialsProvider($T.CREDENTIALS_PROVIDER)", BaseRuleSetClientTest.class); if (AuthUtils.usesBearerAuth(model)) { b.addStatement("builder.tokenProvider($T.TOKEN_PROVIDER)", BaseRuleSetClientTest.class); } b.addStatement("builder.httpClient(getSyncHttpClient())"); if (params != null) { b.add(setClientParams("builder", params)); } b.addStatement("$T request = $L", poetExtension.getModelClass(opModel.getInputShape().getShapeName()), requestCreation(opModel, opParams)); b.addStatement("builder.build().$L", syncOperationInvocation(opModel)); b.endControlFlow(); return b.build(); } private CodeBlock asyncOperationCallLambda(OperationModel opModel, Map<String, TreeNode> params, Map<String, TreeNode> opParams) { CodeBlock.Builder b = CodeBlock.builder(); b.beginControlFlow("() -> "); b.addStatement("$T builder = $T.builder()", asyncClientBuilder(), asyncClientClass()); b.addStatement("builder.credentialsProvider($T.CREDENTIALS_PROVIDER)", BaseRuleSetClientTest.class); if (AuthUtils.usesBearerAuth(model)) { b.addStatement("builder.tokenProvider($T.TOKEN_PROVIDER)", BaseRuleSetClientTest.class); } b.addStatement("builder.httpClient(getAsyncHttpClient())"); if (params != null) { b.add(setClientParams("builder", params)); } b.addStatement("$T request = $L", poetExtension.getModelClass(opModel.getInputShape().getShapeName()), requestCreation(opModel, opParams)); CodeBlock asyncInvoke = asyncOperationInvocation(opModel); b.addStatement("return builder.build().$L", asyncInvoke); b.endControlFlow(); return b.build(); } private CodeBlock syncOperationInvocation(OperationModel opModel) { CodeBlock.Builder b = CodeBlock.builder(); b.add("$N(", opModel.getMethodName()); b.add("$N", "request"); if (opModel.hasStreamingInput()) { b.add(", $T.fromString($S)", RequestBody.class, "hello"); } b.add(")"); return b.build(); } private CodeBlock asyncOperationInvocation(OperationModel opModel) { CodeBlock.Builder b = CodeBlock.builder(); b.add("$N(", opModel.getMethodName()); b.add("$N", "request"); if (opModel.hasEventStreamInput()) { b.add(", new $T()", EmptyPublisher.class); b.add(", $T.mock($T.class)", Mockito.class, poetExtension.eventStreamResponseHandlerType(opModel)); } else if (opModel.hasStreamingInput()) { b.add(", $T.fromString($S)", AsyncRequestBody.class, "hello"); } if (opModel.hasStreamingOutput()) { b.add(", $T.get($S)", Paths.class, "test.dat"); } b.add(")"); return b.build(); } private MethodSpec asyncTestsSourceMethod() { String opName = findDefaultRequest(); OperationModel defaultOpModel = model.getOperation(opName); MethodSpec.Builder b = MethodSpec.methodBuilder("asyncTestCases") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(ParameterizedTypeName.get(List.class, AsyncTestCase.class)); b.addCode("return $T.asList(", Arrays.class); EndpointTestSuiteModel endpointTestSuiteModel = model.getEndpointTestSuiteModel(); Iterator<EndpointTestModel> testIter = endpointTestSuiteModel.getTestCases().iterator(); boolean isFirst = true; while (testIter.hasNext()) { EndpointTestModel test = testIter.next(); if (testCaseHasOperationInputs(test)) { Iterator<OperationInput> operationInputsIter = test.getOperationInputs().iterator(); if (!isFirst) { b.addCode(", "); } isFirst = false; while (operationInputsIter.hasNext()) { OperationInput opInput = operationInputsIter.next(); OperationModel opModel = model.getOperation(opInput.getOperationName()); b.addCode("new $T($S, $L, $L$L)", AsyncTestCase.class, test.getDocumentation(), asyncOperationCallLambda(opModel, test.getParams(), opInput.getOperationParams()), TestGeneratorUtils.createExpect(test.getExpect(), opModel, opInput.getOperationParams()), getSkipReasonBlock(test.getDocumentation())); if (operationInputsIter.hasNext()) { b.addCode(","); } } } else if (shouldGenerateClientTestsOverride()) { if (!isFirst) { b.addCode(", "); } isFirst = false; b.addCode("new $T($S, $L, $L$L)", AsyncTestCase.class, test.getDocumentation(), asyncOperationCallLambda(defaultOpModel, test.getParams(), Collections.emptyMap()), TestGeneratorUtils.createExpect(test.getExpect(), defaultOpModel, null), getSkipReasonBlock(test.getDocumentation())); } } b.addStatement(")"); return b.build(); } private CodeBlock requestCreation(OperationModel opModel, Map<String, TreeNode> opParams) { CodeBlock.Builder b = CodeBlock.builder(); ShapeModel inputModel = opModel.getInputShape(); b.add("$T.builder()", poetExtension.getModelClass(inputModel.getShapeName())); ShapeModel inputShape = opModel.getInputShape(); if (opParams != null) { opParams.forEach((n, v) -> { MemberModel memberModel = opModel.getInputShape().getMemberByName(n); CodeBlock memberValue = createMemberValue(memberModel, v); b.add(".$N($L)", memberModel.getFluentSetterMethodName(), memberValue); }); } if (canBeEmpty(opModel)) { return b.add(".build()").build(); } String hostPrefix = getHostPrefixTemplate(opModel).orElse(""); inputShape.getMembers().forEach(m -> { if (!boundToPath(m) && !hostPrefix.contains("{" + m.getC2jName() + "}")) { return; } // if it's in operationInputs, then it's already set if (opParams.containsKey(m.getName())) { return; } b.add(".$N(", m.getFluentSetterMethodName()); switch (m.getVariable().getSimpleType()) { case "Boolean": b.add("true"); break; case "String": b.add("$S", "aws"); break; case "Long": case "Integer": b.add("1"); break; default: throw new RuntimeException("Don't know how to set member: " + opModel.getOperationName() + "#" + m.getName() + " with type " + m.getVariable().getSimpleType()); } b.add(")"); }); b.add(".build()"); return b.build(); } private static boolean canBeEmpty(OperationModel opModel) { List<MemberModel> members = opModel.getInputShape().getMembers(); if (members == null || members.isEmpty()) { return true; } if (opModel.hasStreamingOutput() || opModel.hasStreamingInput()) { return false; } String hostPrefix = getHostPrefixTemplate(opModel).orElse(""); if (hostPrefix.contains("{") && hostPrefix.contains("}")) { return false; } Optional<MemberModel> pathMemberOrStreaming = members.stream() .filter(EndpointRulesClientTestSpec::boundToPath) .findFirst(); return !pathMemberOrStreaming.isPresent(); } private static boolean boundToPath(MemberModel member) { ParameterHttpMapping http = member.getHttp(); if (http == null) { return false; } return http.getLocation() == Location.URI; } private ClassName syncClientClass() { return poetExtension.getClientClass(model.getMetadata().getSyncInterface()); } private ClassName syncClientBuilder() { return poetExtension.getClientClass(model.getMetadata().getSyncBuilderInterface()); } private ClassName asyncClientClass() { return poetExtension.getClientClass(model.getMetadata().getAsyncInterface()); } private ClassName asyncClientBuilder() { return poetExtension.getClientClass(model.getMetadata().getAsyncBuilderInterface()); } private CodeBlock setClientParams(String builderName, Map<String, TreeNode> params) { CodeBlock.Builder b = CodeBlock.builder(); if (hasS3ConfigParams(params)) { CodeBlock.Builder config = CodeBlock.builder(); config.add("$T.builder()", configClass()); params.forEach((n, v) -> { if (!endpointRulesSpecUtils.isDeclaredParam(n)) { return; } CodeBlock valueLiteral = endpointRulesSpecUtils.treeNodeToLiteral(v); switch (n) { case "UseDualStack": config.add(".dualstackEnabled($L)", valueLiteral); break; case "Accelerate": config.add(".accelerateModeEnabled($L)", valueLiteral); break; case "ForcePathStyle": config.add(".pathStyleAccessEnabled($L)", valueLiteral); break; case "UseArnRegion": config.add(".useArnRegionEnabled($L)", valueLiteral); break; case "DisableMultiRegionAccessPoints": config.add(".multiRegionEnabled(!$L)", valueLiteral); break; default: break; } }); config.add(".build()"); b.addStatement("$N.serviceConfiguration($L)", builderName, config.build()); } params.forEach((n, v) -> { if (!isClientParam(n)) { return; } ParameterModel paramModel = param(n); CodeBlock valueLiteral = endpointRulesSpecUtils.treeNodeToLiteral(v); if (paramModel.getBuiltInEnum() != null) { switch (paramModel.getBuiltInEnum()) { case AWS_REGION: b.addStatement("$N.region($T.of($L))", builderName, Region.class, valueLiteral); break; case AWS_USE_DUAL_STACK: // If this is S3, it will be set in S3Configuration instead if (!hasS3ConfigParams(params)) { b.addStatement("$N.dualstackEnabled($L)", builderName, valueLiteral); } break; case AWS_USE_FIPS: b.addStatement("$N.fipsEnabled($L)", builderName, valueLiteral); break; case SDK_ENDPOINT: b.addStatement("$N.endpointOverride($T.create($L))", builderName, URI.class, valueLiteral); break; case AWS_S3_USE_GLOBAL_ENDPOINT: b.addStatement("$T.setProperty($L, $L ? \"global\" : \"regional\")", System.class, s3RegionalEndpointSystemPropertyCode(), valueLiteral); break; default: break; } } else { String setterName = endpointRulesSpecUtils.clientContextParamMethodName(n); b.addStatement("$N.$N($L)", builderName, setterName, valueLiteral); } }); return b.build(); } private boolean isClientParam(String name) { ParameterModel param = param(name); if (param == null) { return false; } boolean isBuiltIn = param.getBuiltInEnum() != null; Map<String, ClientContextParam> clientContextParams = model.getClientContextParams(); boolean isClientContextParam = clientContextParams != null && clientContextParams.containsKey(name); return isBuiltIn || isClientContextParam; } private ParameterModel param(String name) { return model.getEndpointRuleSetModel().getParameters().get(name); } private boolean hasSyncClient() { return model.getOperations() .values() .stream() .anyMatch(o -> !(o.hasEventStreamOutput() || o.hasEventStreamInput())); } private boolean hasS3ConfigParams(Map<String, TreeNode> params) { String[] s3ConfigurationParams = { "ForcePathStyle", "Accelerate", "UseArnRegion", "DisableMultiRegionAccessPoints", "UseDualStack" }; if (!endpointRulesSpecUtils.isS3() && !endpointRulesSpecUtils.isS3Control()) { return false; } return Stream.of(s3ConfigurationParams).anyMatch(params.keySet()::contains); } private ClassName configClass() { return poetExtension.getClientClass(model.getCustomizationConfig().getServiceConfig().getClassName()); } private Map<String, String> getSkippedTests() { Map<String, String> skippedTests = new HashMap<>(GLOBAL_SKIP_ENDPOINT_TESTS); Map<String, String> customSkippedTests = model.getCustomizationConfig().getSkipEndpointTests(); if (customSkippedTests != null) { skippedTests.putAll(customSkippedTests); } return skippedTests; } private boolean shouldGenerateClientEndpointTests() { boolean someTestCasesHaveOperationInputs = model.getEndpointTestSuiteModel().getTestCases().stream() .anyMatch(t -> t.getOperationInputs() != null); return shouldGenerateClientTestsOverride() || someTestCasesHaveOperationInputs; } /** * Always generate client endpoint tests if the test case has operation inputs */ private static boolean testCaseHasOperationInputs(EndpointTestModel test) { return test.getOperationInputs() != null; } /** * Some services can run tests without operation inputs if there are other conditions that allow * codegen to create a functioning test case */ private boolean shouldGenerateClientTestsOverride() { return model.getCustomizationConfig().isGenerateEndpointClientTests(); } private CodeBlock getSkipReasonBlock(String testName) { if (getSkippedTests().containsKey(testName)) { Validate.notNull(getSkippedTests().get(testName), "Test %s must have a reason for skipping", testName); return CodeBlock.builder().add(", $S", getSkippedTests().get(testName)).build(); } return CodeBlock.builder().build(); } private MethodSpec methodSetupMethod() { MethodSpec.Builder b = MethodSpec.methodBuilder("methodSetup") .addModifiers(Modifier.PUBLIC) .addAnnotation(BeforeEach.class) .returns(void.class); b.addStatement("super.methodSetup()"); // S3 rules assume UseGlobalEndpoint == false by default if (endpointRulesSpecUtils.isS3()) { b.addStatement("$T.setProperty($L, $S)", System.class, s3RegionalEndpointSystemPropertyCode(), "regional"); } return b.build(); } private CodeBlock s3RegionalEndpointSystemPropertyCode() { return CodeBlock.builder() .add("$T.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property()", SdkSystemSetting.class) .build(); } private FieldSpec s3RegionEndpointSystemPropertySaveValueField() { return FieldSpec.builder(String.class, "regionalEndpointPropertySaveValue") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .initializer("$T.getProperty($L)", System.class, s3RegionalEndpointSystemPropertyCode()) .build(); } private MethodSpec teardownMethod() { MethodSpec.Builder b = MethodSpec.methodBuilder("teardown") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addAnnotation(AfterAll.class) .returns(void.class); if (endpointRulesSpecUtils.isS3()) { b.beginControlFlow("if (regionalEndpointPropertySaveValue != null)") .addStatement("$T.setProperty($L, regionalEndpointPropertySaveValue)", System.class, s3RegionalEndpointSystemPropertyCode()) .endControlFlow() .beginControlFlow("else") .addStatement("$T.clearProperty($L)", System.class, s3RegionalEndpointSystemPropertyCode()) .endControlFlow(); } return b.build(); } private CodeBlock createMemberValue(MemberModel memberModel, TreeNode valueNode) { if (memberModel.isSimple()) { return endpointRulesSpecUtils.treeNodeToLiteral(valueNode); } CodeBlock.Builder b = CodeBlock.builder(); if (memberModel.isList()) { Iterator<JrsValue> elementValuesIter = ((JrsArray) valueNode).elements(); MemberModel listMemberModel = memberModel.getListModel().getListMemberModel(); b.add("$T.asList(", Arrays.class); while (elementValuesIter.hasNext()) { JrsValue v = elementValuesIter.next(); b.add(createMemberValue(listMemberModel, v)); if (elementValuesIter.hasNext()) { b.add(","); } } b.add(")"); return b.build(); } if (memberModel.isMap()) { // Not necessary at the moment throw new RuntimeException("Don't know how to create map member."); } return createModelClass(model.getShapes().get(memberModel.getC2jShape()), valueNode); } private CodeBlock createModelClass(ShapeModel shapeModel, TreeNode valueNode) { ClassName modelClassName = poetExtension.getModelClass(shapeModel.getC2jName()); CodeBlock.Builder b = CodeBlock.builder(); b.add("$T.builder()", modelClassName); JrsObject obj = (JrsObject) valueNode; Iterator<String> fieldNamesIter = obj.fieldNames(); while (fieldNamesIter.hasNext()) { String fieldName = fieldNamesIter.next(); MemberModel member = shapeModel.getMemberByName(fieldName); JrsValue value = obj.get(fieldName); b.add(".$N($L)", member.getFluentSetterMethodName(), createMemberValue(member, value)); } b.add(".build()"); return b.build(); } }
3,448
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/rules/RuleSetCreationSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.jr.stree.JrsArray; import com.fasterxml.jackson.jr.stree.JrsBoolean; import com.fasterxml.jackson.jr.stree.JrsNumber; import com.fasterxml.jackson.jr.stree.JrsObject; import com.fasterxml.jackson.jr.stree.JrsString; import com.fasterxml.jackson.jr.stree.JrsValue; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.rules.endpoints.ConditionModel; import software.amazon.awssdk.codegen.model.rules.endpoints.EndpointModel; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterDeprecatedModel; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterModel; import software.amazon.awssdk.codegen.model.rules.endpoints.RuleModel; import software.amazon.awssdk.codegen.model.service.EndpointRuleSetModel; import software.amazon.awssdk.utils.MapUtils; public class RuleSetCreationSpec { private static final String RULE_METHOD_PREFIX = "endpointRule_"; private final EndpointRulesSpecUtils endpointRulesSpecUtils; private final EndpointRuleSetModel ruleSetModel; private int ruleCounter = 0; private final List<MethodSpec> helperMethods = new ArrayList<>(); public RuleSetCreationSpec(IntermediateModel intermediateModel) { this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(intermediateModel); this.ruleSetModel = intermediateModel.getEndpointRuleSetModel(); } public CodeBlock ruleSetCreationExpr() { CodeBlock.Builder b = CodeBlock.builder(); b.add("$T.builder()", endpointRulesSpecUtils.rulesRuntimeClassName("EndpointRuleset")) .add(".version($S)", ruleSetModel.getVersion()) .add(".serviceId($S)", ruleSetModel.getServiceId()) .add(".parameters($L)", parameters(ruleSetModel.getParameters())); ruleSetModel.getRules().stream() .map(this::rule) .forEach(m -> b.add(".addRule($N())", m.name)); b.add(".build()"); return b.build(); } public List<MethodSpec> helperMethods() { return helperMethods; } private CodeBlock parameters(Map<String, ParameterModel> params) { CodeBlock.Builder b = CodeBlock.builder(); b.add("$T.builder()", endpointRulesSpecUtils.rulesRuntimeClassName("Parameters")); params.forEach((name, model) -> { b.add(".addParameter($L)", parameter(name, model)); }); b.add(".build()"); return b.build(); } private CodeBlock parameter(String name, ParameterModel model) { CodeBlock.Builder b = CodeBlock.builder(); b.add("$T.builder()", endpointRulesSpecUtils.rulesRuntimeClassName("Parameter")) .add(".name($S)", name) .add(".type($T.fromValue($S))", endpointRulesSpecUtils.rulesRuntimeClassName("ParameterType"), model.getType()) .add(".required($L)", Boolean.TRUE.equals(model.isRequired())); if (model.getBuiltIn() != null) { b.add(".builtIn($S)", model.getBuiltIn()); } if (model.getDocumentation() != null) { b.add(".documentation($S)", model.getDocumentation()); } if (model.getDefault() != null) { TreeNode defaultValue = model.getDefault(); JsonToken token = defaultValue.asToken(); CodeBlock value; if (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE) { value = endpointRulesSpecUtils.valueCreationCode("boolean", CodeBlock.builder() .add("$L", ((JrsBoolean) defaultValue).booleanValue()) .build()); } else if (token == JsonToken.VALUE_STRING) { value = endpointRulesSpecUtils.valueCreationCode("string", CodeBlock.builder() .add("$S", ((JrsString) defaultValue).getValue()) .build()); } else { throw new RuntimeException("Can't set default value type " + token.name()); } b.add(".defaultValue($L)", value); } if (model.getDeprecated() != null) { ParameterDeprecatedModel deprecated = model.getDeprecated(); b.add(".deprecated(new $T($S, $S))", endpointRulesSpecUtils.rulesRuntimeClassName("Parameter.Deprecated"), deprecated.getMessage(), deprecated.getSince()); } b.add(".build()"); return b.build(); } private MethodSpec rule(RuleModel model) { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(nextRuleMethodName()); methodBuilder.addModifiers(Modifier.PRIVATE, Modifier.STATIC); methodBuilder.returns(endpointRulesSpecUtils.rulesRuntimeClassName("Rule")); CodeBlock.Builder b = CodeBlock.builder(); b.add("$T.builder()", endpointRulesSpecUtils.rulesRuntimeClassName("Rule")); model.getConditions().forEach(c -> b.add(".addCondition($L)", condition(c))); if ("error".equals(model.getType())) { b.add(".error($S)", model.getError()); } else if ("tree".equals(model.getType())) { CodeBlock.Builder rulesArray = CodeBlock.builder() .add("$T.asList(", Arrays.class); int nRules = model.getRules().size(); for (int i = 0; i < nRules; ++i) { MethodSpec childRule = rule(model.getRules().get(i)); rulesArray.add("$N()", childRule.name); if (i + 1 < nRules) { rulesArray.add(", "); } } rulesArray.add(")"); b.add(".treeRule($L)", rulesArray.build()); } else if ("endpoint".equals(model.getType())) { CodeBlock endpoint = endpoint(model.getEndpoint()); b.add(".endpoint($L)", endpoint); } MethodSpec m = methodBuilder.addStatement("return $L", b.build()).build(); helperMethods.add(m); return m; } private CodeBlock endpoint(EndpointModel model) { CodeBlock.Builder b = CodeBlock.builder(); b.add("$T.builder()", endpointRulesSpecUtils.rulesRuntimeClassName("EndpointResult")); TreeNode url = model.getUrl(); b.add(".url($L)", expr(url)); if (model.getHeaders() != null) { model.getHeaders().forEach((name, valueList) -> { valueList.forEach(value -> b.add(".addHeaderValue($S, $L)", name, expr(value))); }); } if (model.getProperties() != null) { // Explicitly only support authSchemes property model.getProperties().forEach((name, property) -> { switch (name) { case "authSchemes": b.add(".addProperty($T.of($S), $T.fromTuple($T.asList(", endpointRulesSpecUtils.rulesRuntimeClassName("Identifier"), "authSchemes", endpointRulesSpecUtils.rulesRuntimeClassName("Literal"), Arrays.class); Iterator<JrsValue> authSchemesIter = ((JrsArray) property).elements(); while (authSchemesIter.hasNext()) { b.add("$T.fromRecord($T.of(", endpointRulesSpecUtils.rulesRuntimeClassName("Literal"), MapUtils.class); JrsObject authScheme = (JrsObject) authSchemesIter.next(); Iterator<String> authSchemeFieldsIter = authScheme.fieldNames(); while (authSchemeFieldsIter.hasNext()) { String schemeProp = authSchemeFieldsIter.next(); JrsValue propValue = authScheme.get(schemeProp); b.add("$T.of($S), ", endpointRulesSpecUtils.rulesRuntimeClassName("Identifier"), schemeProp); if ("signingRegionSet".equalsIgnoreCase(schemeProp)) { b.add("$T.fromTuple($T.asList(", endpointRulesSpecUtils.rulesRuntimeClassName("Literal"), Arrays.class); Iterator<JrsValue> signingRegions = ((JrsArray) propValue).elements(); while (signingRegions.hasNext()) { JrsString region = (JrsString) signingRegions.next(); b.add("$T.fromStr($S)", endpointRulesSpecUtils.rulesRuntimeClassName("Literal"), region.getValue()); if (signingRegions.hasNext()) { b.add(", "); } } b.add("))"); } else if ("disableDoubleEncoding".equalsIgnoreCase(schemeProp)) { b.add("$T.fromBool($L)", endpointRulesSpecUtils.rulesRuntimeClassName("Literal"), ((JrsBoolean) propValue).booleanValue()); } else { b.add("$T.fromStr($S)", endpointRulesSpecUtils.rulesRuntimeClassName("Literal"), ((JrsString) propValue).getValue()); } if (authSchemeFieldsIter.hasNext()) { b.add(", "); } } b.add("))"); if (authSchemesIter.hasNext()) { b.add(", "); } } b.add(")))"); break; default: break; } }); } b.add(".build()"); return b.build(); } private CodeBlock condition(ConditionModel model) { CodeBlock.Builder b = CodeBlock.builder(); b.add("$T.builder()", endpointRulesSpecUtils.rulesRuntimeClassName("Condition")) .add(".fn($L.validate())", fnNode(model)); if (model.getAssign() != null) { b.add(".result($S)", model.getAssign()); } b.add(".build()"); return b.build(); } private CodeBlock fnNode(ConditionModel model) { CodeBlock.Builder b = CodeBlock.builder(); b.add("$T.builder()", endpointRulesSpecUtils.rulesRuntimeClassName("FnNode")) .add(".fn($S)", model.getFn()) .add(".argv($T.asList(", Arrays.class); List<TreeNode> args = model.getArgv(); for (int i = 0; i < args.size(); ++i) { b.add("$L", expr(args.get(i))); if (i + 1 < args.size()) { b.add(","); } } b.add("))"); b.add(".build()"); return b.build(); } private CodeBlock expr(TreeNode n) { if (n.isValueNode()) { return valueExpr((JrsValue) n); } if (n.isObject()) { return objectExpr((JrsObject) n); } throw new RuntimeException("Don't know how to create expression from " + n); } private CodeBlock valueExpr(JrsValue n) { CodeBlock.Builder b = CodeBlock.builder(); b.add("$T.of(", endpointRulesSpecUtils.rulesRuntimeClassName("Expr")); JsonToken token = n.asToken(); switch (token) { case VALUE_STRING: b.add("$S", ((JrsString) n).getValue()); break; case VALUE_NUMBER_INT: b.add("$L", ((JrsNumber) n).getValue().intValue()); break; case VALUE_TRUE: case VALUE_FALSE: b.add("$L", ((JrsBoolean) n).booleanValue()); break; default: throw new RuntimeException("Don't know how to create expression JSON type " + token); } b.add(")"); return b.build(); } private CodeBlock objectExpr(JrsObject n) { CodeBlock.Builder b = CodeBlock.builder(); JrsValue ref = n.get("ref"); JrsValue fn = n.get("fn"); if (ref != null) { b.add("$T.ref($T.of($S))", endpointRulesSpecUtils.rulesRuntimeClassName("Expr"), endpointRulesSpecUtils.rulesRuntimeClassName("Identifier"), ref.asText()); } else if (fn != null) { String name = fn.asText(); CodeBlock.Builder fnNode = CodeBlock.builder(); fnNode.add("$T.builder()", endpointRulesSpecUtils.rulesRuntimeClassName("FnNode")) .add(".fn($S)", name); JrsArray argv = (JrsArray) n.get("argv"); fnNode.add(".argv($T.asList(", Arrays.class); Iterator<JrsValue> iter = argv.elements(); while (iter.hasNext()) { fnNode.add(expr(iter.next())); if (iter.hasNext()) { fnNode.add(","); } } fnNode.add(")).build().validate()"); b.add(fnNode.build()); } return b.build(); } private String nextRuleMethodName() { String n = String.format("%s%d", RULE_METHOD_PREFIX, ruleCounter); ruleCounter += 1; return n; } }
3,449
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/rules/EndpointProviderInterfaceSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; 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.SdkPublicApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.endpoints.EndpointProvider; public class EndpointProviderInterfaceSpec implements ClassSpec { private final IntermediateModel intermediateModel; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public EndpointProviderInterfaceSpec(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(intermediateModel); } @Override public TypeSpec poetSpec() { return PoetUtils.createInterfaceBuilder(className()) .addSuperinterface(EndpointProvider.class) .addModifiers(Modifier.PUBLIC) .addAnnotation(SdkPublicApi.class) .addJavadoc(interfaceJavadoc()) .addMethod(resolveEndpointMethod()) .addMethod(resolveEndpointConsumerBuilderMethod()) .addMethod(defaultProviderMethod()) .build(); } private MethodSpec resolveEndpointMethod() { MethodSpec.Builder b = MethodSpec.methodBuilder("resolveEndpoint"); b.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT); b.addParameter(endpointRulesSpecUtils.parametersClassName(), "endpointParams"); b.returns(endpointRulesSpecUtils.resolverReturnType()); b.addJavadoc(resolveMethodJavadoc()); return b.build(); } private MethodSpec resolveEndpointConsumerBuilderMethod() { ClassName parametersClass = endpointRulesSpecUtils.parametersClassName(); ClassName parametersBuilderClass = parametersClass.nestedClass("Builder"); TypeName consumerType = ParameterizedTypeName.get(ClassName.get(Consumer.class), parametersBuilderClass); MethodSpec.Builder b = MethodSpec.methodBuilder("resolveEndpoint"); b.addModifiers(Modifier.PUBLIC, Modifier.DEFAULT); b.addParameter(consumerType, "endpointParamsConsumer"); b.returns(endpointRulesSpecUtils.resolverReturnType()); b.addJavadoc(resolveMethodJavadoc()); b.addStatement("$T paramsBuilder = $T.builder()", parametersBuilderClass, parametersClass); b.addStatement("endpointParamsConsumer.accept(paramsBuilder)"); b.addStatement("return resolveEndpoint(paramsBuilder.build())"); return b.build(); } private MethodSpec defaultProviderMethod() { return MethodSpec.methodBuilder("defaultProvider") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(className()) .addStatement("return new $T()", endpointRulesSpecUtils.providerDefaultImplName()) .build(); } @Override public ClassName className() { return endpointRulesSpecUtils.providerInterfaceName(); } private CodeBlock interfaceJavadoc() { CodeBlock.Builder b = CodeBlock.builder(); b.add("An endpoint provider for $N. The endpoint provider takes a set of parameters using {@link $T}, and resolves an " + "{@link $T} base on the given parameters.", intermediateModel.getMetadata().getServiceName(), endpointRulesSpecUtils.parametersClassName(), Endpoint.class); return b.build(); } private CodeBlock resolveMethodJavadoc() { CodeBlock.Builder b = CodeBlock.builder(); b.add("Compute the endpoint based on the given set of parameters."); return b.build(); } }
3,450
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/rules/ClientContextParamsClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 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 com.squareup.javapoet.TypeVariableName; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ClientContextParam; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.utils.AttributeMap; public class ClientContextParamsClassSpec implements ClassSpec { private final IntermediateModel model; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public ClientContextParamsClassSpec(IntermediateModel model) { this.model = model; this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder b = PoetUtils.createClassBuilder(endpointRulesSpecUtils.clientContextParamsName()) .superclass(ParameterizedTypeName.get( ClassName.get(AttributeMap.class).nestedClass("Key"), TypeVariableName.get("T"))) .addAnnotation(SdkInternalApi.class) .addTypeVariable(TypeVariableName.get("T")) .addModifiers(Modifier.PUBLIC, Modifier.FINAL); b.addMethod(ctor()); model.getClientContextParams().forEach((n, m) -> { b.addField(paramDeclaration(n, m)); }); if (model.getCustomizationConfig() != null && model.getCustomizationConfig().getCustomClientContextParams() != null) { model.getCustomizationConfig().getCustomClientContextParams().forEach((n, m) -> { b.addField(paramDeclaration(n, m)); }); } return b.build(); } @Override public ClassName className() { return endpointRulesSpecUtils.clientContextParamsName(); } private MethodSpec ctor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class), TypeVariableName.get("T")), "valueClass") .addStatement("super(valueClass)") .build(); } private FieldSpec paramDeclaration(String name, ClientContextParam param) { String fieldName = endpointRulesSpecUtils.clientContextParamName(name); TypeName type = endpointRulesSpecUtils.toJavaType(param.getType()); FieldSpec.Builder b = FieldSpec.builder(ParameterizedTypeName.get(className(), type), fieldName) .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL); b.initializer("new $T<>($T.class)", className(), type); PoetUtils.addJavadoc(b::addJavadoc, param.getDocumentation()); return b.build(); } }
3,451
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/rules/DefaultPartitionDataProviderSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 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.TypeSpec; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Lazy; import software.amazon.awssdk.utils.Validate; public class DefaultPartitionDataProviderSpec implements ClassSpec { private final IntermediateModel model; private final EndpointRulesSpecUtils endpointRulesSpecUtils; private final ClassName partitionsClass; public DefaultPartitionDataProviderSpec(IntermediateModel model) { this.model = model; this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); this.partitionsClass = endpointRulesSpecUtils.rulesRuntimeClassName("Partitions"); } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(SdkInternalApi.class) .addSuperinterface( endpointRulesSpecUtils.rulesRuntimeClassName("PartitionDataProvider")); builder.addField(partitionDataField()); builder.addField(partitionsLazyField()); builder.addMethod(loadPartitionsMethod()); builder.addMethod(doLoadPartitionsMethod()); return builder.build(); } @Override public ClassName className() { return endpointRulesSpecUtils.rulesRuntimeClassName("DefaultPartitionDataProvider"); } private MethodSpec loadPartitionsMethod() { MethodSpec.Builder builder = MethodSpec.methodBuilder("loadPartitions") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(partitionsClass); builder.addStatement("return PARTITIONS.getValue()"); return builder.build(); } private FieldSpec partitionDataField() { FieldSpec.Builder builder = FieldSpec.builder(String.class, "DEFAULT_PARTITION_DATA", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL); builder.initializer("$S", readPartitionsJson()); return builder.build(); } private FieldSpec partitionsLazyField() { ParameterizedTypeName lazyType = ParameterizedTypeName.get(ClassName.get(Lazy.class), partitionsClass); FieldSpec.Builder builder = FieldSpec.builder(lazyType, "PARTITIONS") .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL); CodeBlock init = CodeBlock.builder() .addStatement("new $T<>($T::doLoadPartitions)", Lazy.class, className()) .build(); builder.initializer(init); return builder.build(); } private MethodSpec doLoadPartitionsMethod() { MethodSpec.Builder builder = MethodSpec.methodBuilder("doLoadPartitions") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(partitionsClass); builder.addStatement("return $T.fromNode($T.parser().parse(DEFAULT_PARTITION_DATA))", partitionsClass, JsonNode.class); return builder.build(); } private String readPartitionsJson() { String jsonPath = endpointRulesSpecUtils.rulesEngineResourceFiles() .stream() .filter(e -> e.endsWith("partitions.json.resource")) .findFirst() .orElseThrow( () -> new RuntimeException("Could not find partitions.json.resource")); return loadResourceAsString("/" + jsonPath); } private String loadResourceAsString(String path) { try { return IoUtils.toUtf8String(loadResource(path)); } catch (IOException e) { throw new UncheckedIOException(e); } } private InputStream loadResource(String name) { InputStream resourceAsStream = DefaultPartitionDataProviderSpec.class.getResourceAsStream(name); Validate.notNull(resourceAsStream, "Failed to load resource from %s", name); return resourceAsStream; } }
3,452
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/rules/EndpointResolverInterceptorSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.jr.stree.JrsBoolean; import com.fasterxml.jackson.jr.stree.JrsString; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; 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.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletionException; import java.util.function.Supplier; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.signer.AwsS3V4Signer; import software.amazon.awssdk.auth.signer.SignerLoader; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.awscore.endpoints.AwsEndpointAttribute; import software.amazon.awssdk.awscore.endpoints.authscheme.EndpointAuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4AuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4aAuthScheme; import software.amazon.awssdk.awscore.util.SignerOverrideUtils; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterModel; import software.amazon.awssdk.codegen.model.service.ClientContextParam; import software.amazon.awssdk.codegen.model.service.ContextParam; import software.amazon.awssdk.codegen.model.service.EndpointTrait; import software.amazon.awssdk.codegen.model.service.HostPrefixProcessor; import software.amazon.awssdk.codegen.model.service.StaticContextParam; 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.auth.scheme.AuthSchemeSpecUtils; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4aAuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.http.auth.aws.signer.RegionSet; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.HostnameValidator; import software.amazon.awssdk.utils.StringUtils; public class EndpointResolverInterceptorSpec implements ClassSpec { private final IntermediateModel model; private final EndpointRulesSpecUtils endpointRulesSpecUtils; private final PoetExtension poetExtension; private final boolean dependsOnHttpAuthAws; private final boolean useSraAuth; public EndpointResolverInterceptorSpec(IntermediateModel model) { this.model = model; this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); this.poetExtension = new PoetExtension(model); // We need to know whether the service has a dependency on the http-auth-aws module. Because we can't check that // directly, assume that if they're using AwsV4AuthScheme or AwsV4aAuthScheme that it's available. Set<Class<?>> supportedAuthSchemes = new AuthSchemeSpecUtils(model).allServiceConcreteAuthSchemeClasses(); this.dependsOnHttpAuthAws = supportedAuthSchemes.contains(AwsV4AuthScheme.class) || supportedAuthSchemes.contains(AwsV4aAuthScheme.class); this.useSraAuth = new AuthSchemeSpecUtils(model).useSraAuth(); } @Override public TypeSpec poetSpec() { TypeSpec.Builder b = PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(SdkInternalApi.class) .addSuperinterface(ExecutionInterceptor.class); b.addMethod(modifyRequestMethod()); b.addMethod(modifyHttpRequestMethod()); b.addMethod(ruleParams()); b.addMethod(setContextParams()); addContextParamMethods(b); b.addMethod(setStaticContextParamsMethod()); addStaticContextParamMethods(b); b.addMethod(authSchemeWithEndpointSignerPropertiesMethod()); if (hasClientContextParams()) { b.addMethod(setClientContextParamsMethod()); } b.addMethod(hostPrefixMethod()); if (!useSraAuth) { b.addMethod(signerProviderMethod()); } return b.build(); } @Override public ClassName className() { return endpointRulesSpecUtils.resolverInterceptorName(); } private MethodSpec modifyRequestMethod() { MethodSpec.Builder b = MethodSpec.methodBuilder("modifyRequest") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(SdkRequest.class) .addParameter(Context.ModifyRequest.class, "context") .addParameter(ExecutionAttributes.class, "executionAttributes"); String providerVar = "provider"; b.addStatement("$T result = context.request()", SdkRequest.class); // We skip resolution if the source of the endpoint is the endpoint discovery call b.beginControlFlow("if ($1T.endpointIsDiscovered(executionAttributes))", endpointRulesSpecUtils.rulesRuntimeClassName("AwsEndpointProviderUtils")); b.addStatement("return result"); b.endControlFlow(); b.addStatement("$1T $2N = ($1T) executionAttributes.getAttribute($3T.ENDPOINT_PROVIDER)", endpointRulesSpecUtils.providerInterfaceName(), providerVar, SdkInternalExecutionAttribute.class); b.beginControlFlow("try"); b.addStatement("$T endpoint = $N.resolveEndpoint(ruleParams(result, executionAttributes)).join()", Endpoint.class, providerVar); b.beginControlFlow("if (!$T.disableHostPrefixInjection(executionAttributes))", endpointRulesSpecUtils.rulesRuntimeClassName("AwsEndpointProviderUtils")); b.addStatement("$T hostPrefix = hostPrefix(executionAttributes.getAttribute($T.OPERATION_NAME), result)", ParameterizedTypeName.get(Optional.class, String.class), SdkExecutionAttribute.class); b.beginControlFlow("if (hostPrefix.isPresent())"); b.addStatement("endpoint = $T.addHostPrefix(endpoint, hostPrefix.get())", endpointRulesSpecUtils.rulesRuntimeClassName("AwsEndpointProviderUtils")); b.endControlFlow(); b.endControlFlow(); // If the endpoint resolver returns auth settings, use them as signer properties. // This effectively works to set the preSRA Signer ExecutionAttributes, so it is not conditional on useSraAuth. b.addStatement("$T<$T> endpointAuthSchemes = endpoint.attribute($T.AUTH_SCHEMES)", List.class, EndpointAuthScheme.class, AwsEndpointAttribute.class); b.addStatement("$T<?> selectedAuthScheme = executionAttributes.getAttribute($T.SELECTED_AUTH_SCHEME)", SelectedAuthScheme.class, SdkInternalExecutionAttribute.class); b.beginControlFlow("if (endpointAuthSchemes != null && selectedAuthScheme != null)"); b.addStatement("selectedAuthScheme = authSchemeWithEndpointSignerProperties(endpointAuthSchemes, selectedAuthScheme)"); b.addStatement("executionAttributes.putAttribute($T.SELECTED_AUTH_SCHEME, selectedAuthScheme)", SdkInternalExecutionAttribute.class); b.endControlFlow(); // For pre SRA client, use Signer as determined by endpoint resolved auth scheme if (!useSraAuth) { b.beginControlFlow("if (endpointAuthSchemes != null)"); b.addStatement("$T chosenAuthScheme = $T.chooseAuthScheme(endpointAuthSchemes)", EndpointAuthScheme.class, endpointRulesSpecUtils.rulesRuntimeClassName("AuthSchemeUtils")); b.addStatement("$T<$T> signerProvider = signerProvider(chosenAuthScheme)", Supplier.class, Signer.class); b.addStatement("result = $T.overrideSignerIfNotOverridden(result, executionAttributes, signerProvider)", SignerOverrideUtils.class); b.endControlFlow(); } b.addStatement("executionAttributes.putAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT, endpoint)"); b.addStatement("return result"); b.endControlFlow(); b.beginControlFlow("catch ($T e)", CompletionException.class); b.addStatement("$T cause = e.getCause()", Throwable.class); b.beginControlFlow("if (cause instanceof $T)", SdkClientException.class); b.addStatement("throw ($T) cause", SdkClientException.class); b.endControlFlow(); b.beginControlFlow("else"); b.addStatement("throw $T.create($S, cause)", SdkClientException.class, "Endpoint resolution failed"); b.endControlFlow(); b.endControlFlow(); return b.build(); } private MethodSpec modifyHttpRequestMethod() { MethodSpec.Builder b = MethodSpec.methodBuilder("modifyHttpRequest") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(SdkHttpRequest.class) .addParameter(Context.ModifyHttpRequest.class, "context") .addParameter(ExecutionAttributes.class, "executionAttributes"); b.addStatement("$T resolvedEndpoint = executionAttributes.getAttribute($T.RESOLVED_ENDPOINT)", Endpoint.class, SdkInternalExecutionAttribute.class); b.beginControlFlow("if (resolvedEndpoint.headers().isEmpty())"); b.addStatement("return context.httpRequest()"); b.endControlFlow(); b.addStatement("$T httpRequestBuilder = context.httpRequest().toBuilder()", SdkHttpRequest.Builder.class); b.addCode("resolvedEndpoint.headers().forEach((name, values) -> {"); b.addStatement("values.forEach(v -> httpRequestBuilder.appendHeader(name, v))"); b.addCode("});"); b.addStatement("return httpRequestBuilder.build()"); return b.build(); } private MethodSpec ruleParams() { MethodSpec.Builder b = MethodSpec.methodBuilder("ruleParams") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(endpointRulesSpecUtils.parametersClassName()) .addParameter(SdkRequest.class, "request") .addParameter(ExecutionAttributes.class, "executionAttributes"); b.addStatement("$T builder = $T.builder()", paramsBuilderClass(), endpointRulesSpecUtils.parametersClassName()); Map<String, ParameterModel> parameters = model.getEndpointRuleSetModel().getParameters(); parameters.forEach((n, m) -> { if (m.getBuiltInEnum() == null) { return; } String setterName = endpointRulesSpecUtils.paramMethodName(n); String builtInFn; switch (m.getBuiltInEnum()) { case AWS_REGION: builtInFn = "regionBuiltIn"; break; case AWS_USE_DUAL_STACK: builtInFn = "dualStackEnabledBuiltIn"; break; case AWS_USE_FIPS: builtInFn = "fipsEnabledBuiltIn"; break; case SDK_ENDPOINT: builtInFn = "endpointBuiltIn"; break; case AWS_S3_USE_GLOBAL_ENDPOINT: builtInFn = "useGlobalEndpointBuiltIn"; break; // The S3 specific built-ins are set through the existing S3Configuration which is handled above case AWS_S3_ACCELERATE: case AWS_S3_DISABLE_MULTI_REGION_ACCESS_POINTS: case AWS_S3_FORCE_PATH_STYLE: case AWS_S3_USE_ARN_REGION: case AWS_S3_CONTROL_USE_ARN_REGION: // end of S3 specific builtins case AWS_STS_USE_GLOBAL_ENDPOINT: // V2 doesn't support this, only regional endpoints return; default: throw new RuntimeException("Don't know how to set built-in " + m.getBuiltInEnum()); } b.addStatement("builder.$N($T.$N(executionAttributes))", setterName, endpointRulesSpecUtils.rulesRuntimeClassName("AwsEndpointProviderUtils"), builtInFn); }); if (hasClientContextParams()) { b.addStatement("setClientContextParams(builder, executionAttributes)"); } b.addStatement("setContextParams(builder, executionAttributes.getAttribute($T.OPERATION_NAME), request)", AwsExecutionAttribute.class); b.addStatement("setStaticContextParams(builder, executionAttributes.getAttribute($T.OPERATION_NAME))", AwsExecutionAttribute.class); b.addStatement("return builder.build()"); return b.build(); } private ClassName paramsBuilderClass() { return endpointRulesSpecUtils.parametersClassName().nestedClass("Builder"); } private MethodSpec addStaticContextParamsMethod(OperationModel opModel) { String methodName = staticContextParamsMethodName(opModel); MethodSpec.Builder b = MethodSpec.methodBuilder(methodName) .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(void.class) .addParameter(paramsBuilderClass(), "params"); opModel.getStaticContextParams().forEach((n, m) -> { String setterName = endpointRulesSpecUtils.paramMethodName(n); TreeNode value = m.getValue(); switch (value.asToken()) { case VALUE_STRING: b.addStatement("params.$N($S)", setterName, ((JrsString) value).getValue()); break; case VALUE_TRUE: case VALUE_FALSE: b.addStatement("params.$N($L)", setterName, ((JrsBoolean) value).booleanValue()); break; default: throw new RuntimeException("Don't know how to set parameter of type " + value.asToken()); } }); return b.build(); } private String staticContextParamsMethodName(OperationModel opModel) { return opModel.getMethodName() + "StaticContextParams"; } private boolean hasStaticContextParams(OperationModel opModel) { Map<String, StaticContextParam> staticContextParams = opModel.getStaticContextParams(); return staticContextParams != null && !staticContextParams.isEmpty(); } private void addStaticContextParamMethods(TypeSpec.Builder classBuilder) { Map<String, OperationModel> operations = model.getOperations(); operations.forEach((n, m) -> { if (hasStaticContextParams(m)) { classBuilder.addMethod(addStaticContextParamsMethod(m)); } }); } private void addContextParamMethods(TypeSpec.Builder classBuilder) { Map<String, OperationModel> operations = model.getOperations(); operations.forEach((n, m) -> { if (hasContextParams(m)) { classBuilder.addMethod(setContextParamsMethod(m)); } }); } private MethodSpec setStaticContextParamsMethod() { Map<String, OperationModel> operations = model.getOperations(); MethodSpec.Builder b = MethodSpec.methodBuilder("setStaticContextParams") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .addParameter(paramsBuilderClass(), "params") .addParameter(String.class, "operationName") .returns(void.class); boolean generateSwitch = operations.values().stream().anyMatch(this::hasStaticContextParams); if (generateSwitch) { b.beginControlFlow("switch (operationName)"); operations.forEach((n, m) -> { if (!hasStaticContextParams(m)) { return; } b.addCode("case $S:", n); b.addStatement("$N(params)", staticContextParamsMethodName(m)); b.addStatement("break"); }); b.addCode("default:"); b.addStatement("break"); b.endControlFlow(); } return b.build(); } private MethodSpec setContextParams() { Map<String, OperationModel> operations = model.getOperations(); MethodSpec.Builder b = MethodSpec.methodBuilder("setContextParams") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .addParameter(paramsBuilderClass(), "params") .addParameter(String.class, "operationName") .addParameter(SdkRequest.class, "request") .returns(void.class); boolean generateSwitch = operations.values().stream().anyMatch(this::hasContextParams); if (generateSwitch) { b.beginControlFlow("switch (operationName)"); operations.forEach((n, m) -> { if (!hasContextParams(m)) { return; } String requestClassName = model.getNamingStrategy().getRequestClassName(m.getOperationName()); ClassName requestClass = poetExtension.getModelClass(requestClassName); b.addCode("case $S:", n); b.addStatement("setContextParams(params, ($T) request)", requestClass); b.addStatement("break"); }); b.addCode("default:"); b.addStatement("break"); b.endControlFlow(); } return b.build(); } private MethodSpec setContextParamsMethod(OperationModel opModel) { String requestClassName = model.getNamingStrategy().getRequestClassName(opModel.getOperationName()); ClassName requestClass = poetExtension.getModelClass(requestClassName); MethodSpec.Builder b = MethodSpec.methodBuilder("setContextParams") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .addParameter(paramsBuilderClass(), "params") .addParameter(requestClass, "request") .returns(void.class); opModel.getInputShape().getMembers().forEach(m -> { ContextParam param = m.getContextParam(); if (param == null) { return; } String setterName = endpointRulesSpecUtils.paramMethodName(param.getName()); b.addStatement("params.$N(request.$N())", setterName, m.getFluentGetterMethodName()); }); return b.build(); } private boolean hasContextParams(OperationModel opModel) { return opModel.getInputShape().getMembers().stream() .anyMatch(m -> m.getContextParam() != null); } private boolean hasClientContextParams() { Map<String, ClientContextParam> clientContextParams = model.getClientContextParams(); return clientContextParams != null && !clientContextParams.isEmpty(); } private MethodSpec setClientContextParamsMethod() { MethodSpec.Builder b = MethodSpec.methodBuilder("setClientContextParams") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .addParameter(paramsBuilderClass(), "params") .addParameter(ExecutionAttributes.class, "executionAttributes") .returns(void.class); b.addStatement("$T clientContextParams = executionAttributes.getAttribute($T.CLIENT_CONTEXT_PARAMS)", AttributeMap.class, SdkInternalExecutionAttribute.class); ClassName paramsClass = endpointRulesSpecUtils.clientContextParamsName(); Map<String, ClientContextParam> params = model.getClientContextParams(); params.forEach((n, m) -> { String attrName = endpointRulesSpecUtils.clientContextParamName(n); b.addStatement("$T.ofNullable(clientContextParams.get($T.$N)).ifPresent(params::$N)", Optional.class, paramsClass, attrName, endpointRulesSpecUtils.paramMethodName(n)); }); return b.build(); } private MethodSpec hostPrefixMethod() { MethodSpec.Builder builder = MethodSpec.methodBuilder("hostPrefix") .returns(ParameterizedTypeName.get(Optional.class, String.class)) .addParameter(String.class, "operationName") .addParameter(SdkRequest.class, "request") .addModifiers(Modifier.PRIVATE, Modifier.STATIC); boolean generateSwitch = model.getOperations().values().stream().anyMatch(opModel -> StringUtils.isNotBlank(getHostPrefix(opModel))); if (!generateSwitch) { builder.addStatement("return $T.empty()", Optional.class); } else { builder.beginControlFlow("switch (operationName)"); model.getOperations().forEach((name, opModel) -> { String hostPrefix = getHostPrefix(opModel); if (StringUtils.isBlank(hostPrefix)) { return; } builder.beginControlFlow("case $S:", name); HostPrefixProcessor processor = new HostPrefixProcessor(hostPrefix); if (processor.c2jNames().isEmpty()) { builder.addStatement("return $T.of($S)", Optional.class, processor.hostWithStringSpecifier()); } else { String requestVar = opModel.getInput().getVariableName(); processor.c2jNames().forEach(c2jName -> { builder.addStatement("$1T.validateHostnameCompliant(request.getValueForField($2S, $3T.class)" + ".orElse(null), $2S, $4S)", HostnameValidator.class, c2jName, String.class, requestVar); }); builder.addCode("return $T.of($T.format($S, ", Optional.class, String.class, processor.hostWithStringSpecifier()); Iterator<String> c2jNamesIter = processor.c2jNames().listIterator(); while (c2jNamesIter.hasNext()) { builder.addCode("request.getValueForField($S, $T.class).get()", c2jNamesIter.next(), String.class); if (c2jNamesIter.hasNext()) { builder.addCode(","); } } builder.addStatement("))"); } builder.endControlFlow(); }); builder.addCode("default:"); builder.addStatement("return $T.empty()", Optional.class); builder.endControlFlow(); } return builder.build(); } private String getHostPrefix(OperationModel opModel) { EndpointTrait endpointTrait = opModel.getEndpointTrait(); if (endpointTrait == null) { return null; } return endpointTrait.getHostPrefix(); } private MethodSpec authSchemeWithEndpointSignerPropertiesMethod() { TypeVariableName tExtendsIdentity = TypeVariableName.get("T", Identity.class); TypeName selectedAuthSchemeOfT = ParameterizedTypeName.get(ClassName.get(SelectedAuthScheme.class), TypeVariableName.get("T")); TypeName listOfEndpointAuthScheme = ParameterizedTypeName.get(List.class, EndpointAuthScheme.class); MethodSpec.Builder method = MethodSpec.methodBuilder("authSchemeWithEndpointSignerProperties") .addModifiers(Modifier.PRIVATE) .addTypeVariable(tExtendsIdentity) .returns(selectedAuthSchemeOfT) .addParameter(listOfEndpointAuthScheme, "endpointAuthSchemes") .addParameter(selectedAuthSchemeOfT, "selectedAuthScheme"); method.beginControlFlow("for ($T endpointAuthScheme : endpointAuthSchemes)", EndpointAuthScheme.class); if (useSraAuth) { // Don't include signer properties for auth options that don't match our selected auth scheme method.beginControlFlow("if (!endpointAuthScheme.schemeId()" + ".equals(selectedAuthScheme.authSchemeOption().schemeId()))"); method.addStatement("continue"); method.endControlFlow(); } method.addStatement("$T option = selectedAuthScheme.authSchemeOption().toBuilder()", AuthSchemeOption.Builder.class); if (dependsOnHttpAuthAws) { method.addCode(copyV4EndpointSignerPropertiesToAuth()); method.addCode(copyV4aEndpointSignerPropertiesToAuth()); } method.addStatement("throw new $T(\"Endpoint auth scheme '\" + endpointAuthScheme.name() + \"' cannot be mapped to the " + "SDK auth scheme. Was it declared in the service's model?\")", IllegalArgumentException.class); method.endControlFlow(); method.addStatement("return selectedAuthScheme"); return method.build(); } private static CodeBlock copyV4EndpointSignerPropertiesToAuth() { CodeBlock.Builder code = CodeBlock.builder(); code.beginControlFlow("if (endpointAuthScheme instanceof $T)", SigV4AuthScheme.class); code.addStatement("$1T v4AuthScheme = ($1T) endpointAuthScheme", SigV4AuthScheme.class); code.beginControlFlow("if (v4AuthScheme.isDisableDoubleEncodingSet())"); code.addStatement("option.putSignerProperty($T.DOUBLE_URL_ENCODE, !v4AuthScheme.disableDoubleEncoding())", AwsV4HttpSigner.class); code.endControlFlow(); code.beginControlFlow("if (v4AuthScheme.signingRegion() != null)"); code.addStatement("option.putSignerProperty($T.REGION_NAME, v4AuthScheme.signingRegion())", AwsV4HttpSigner.class); code.endControlFlow(); code.beginControlFlow("if (v4AuthScheme.signingName() != null)"); code.addStatement("option.putSignerProperty($T.SERVICE_SIGNING_NAME, v4AuthScheme.signingName())", AwsV4HttpSigner.class); code.endControlFlow(); code.addStatement("return new $T<>(selectedAuthScheme.identity(), selectedAuthScheme.signer(), option.build())", SelectedAuthScheme.class); code.endControlFlow(); return code.build(); } private static CodeBlock copyV4aEndpointSignerPropertiesToAuth() { CodeBlock.Builder code = CodeBlock.builder(); code.beginControlFlow("if (endpointAuthScheme instanceof $T)", SigV4aAuthScheme.class); code.addStatement("$1T v4aAuthScheme = ($1T) endpointAuthScheme", SigV4aAuthScheme.class); code.beginControlFlow("if (v4aAuthScheme.isDisableDoubleEncodingSet())"); code.addStatement("option.putSignerProperty($T.DOUBLE_URL_ENCODE, !v4aAuthScheme.disableDoubleEncoding())", AwsV4aHttpSigner.class); code.endControlFlow(); code.beginControlFlow("if (v4aAuthScheme.signingRegionSet() != null)"); code.addStatement("$1T regionSet = $1T.create(v4aAuthScheme.signingRegionSet())", RegionSet.class); code.addStatement("option.putSignerProperty($T.REGION_SET, regionSet)", AwsV4aHttpSigner.class); code.endControlFlow(); code.beginControlFlow("if (v4aAuthScheme.signingName() != null)"); code.addStatement("option.putSignerProperty($T.SERVICE_SIGNING_NAME, v4aAuthScheme.signingName())", AwsV4aHttpSigner.class); code.endControlFlow(); code.addStatement("return new $T<>(selectedAuthScheme.identity(), selectedAuthScheme.signer(), option.build())", SelectedAuthScheme.class); code.endControlFlow(); return code.build(); } private MethodSpec signerProviderMethod() { MethodSpec.Builder builder = MethodSpec.methodBuilder("signerProvider") .addModifiers(Modifier.PRIVATE) .addParameter(EndpointAuthScheme.class, "authScheme") .returns(ParameterizedTypeName.get(Supplier.class, Signer.class)); builder.beginControlFlow("switch (authScheme.name())"); builder.addCode("case $S:", "sigv4"); if (endpointRulesSpecUtils.isS3() || endpointRulesSpecUtils.isS3Control()) { builder.addStatement("return $T::create", AwsS3V4Signer.class); } else { builder.addStatement("return $T::create", Aws4Signer.class); } builder.addCode("case $S:", "sigv4a"); if (endpointRulesSpecUtils.isS3() || endpointRulesSpecUtils.isS3Control()) { builder.addStatement("return $T::getS3SigV4aSigner", SignerLoader.class); } else { builder.addStatement("return $T::getSigV4aSigner", SignerLoader.class); } builder.addCode("default:"); builder.addStatement("break"); builder.endControlFlow(); builder.addStatement("throw $T.create($S + authScheme.name())", SdkClientException.class, "Don't know how to create signer for auth scheme: "); return builder.build(); } }
3,453
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/rules/EndpointProviderSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 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.TypeSpec; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.rules.endpoints.BuiltInParameter; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Validate; public class EndpointProviderSpec implements ClassSpec { private static final String RULE_SET_FIELD_NAME = "ENDPOINT_RULE_SET"; private final IntermediateModel intermediateModel; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public EndpointProviderSpec(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(intermediateModel); } @Override public TypeSpec poetSpec() { TypeSpec.Builder b = PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addSuperinterface(endpointRulesSpecUtils.providerInterfaceName()) .addField(ruleSet()) .addMethod(resolveEndpointMethod()) .addMethod(toIdentifierValueMap()) .addAnnotation(SdkInternalApi.class); b.addMethod(ruleSetBuildMethod(b)); b.addMethod(equalsMethod()); b.addMethod(hashCodeMethod()); return b.build(); } private MethodSpec equalsMethod() { return MethodSpec.methodBuilder("equals") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(boolean.class) .addParameter(Object.class, "rhs") .addStatement("return rhs != null && getClass().equals(rhs.getClass())") .build(); } private MethodSpec hashCodeMethod() { return MethodSpec.methodBuilder("hashCode") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(int.class) .addStatement("return getClass().hashCode()") .build(); } @Override public ClassName className() { Metadata md = intermediateModel.getMetadata(); return ClassName.get(md.getFullInternalEndpointRulesPackageName(), "Default" + endpointRulesSpecUtils.providerInterfaceName().simpleName()); } private FieldSpec ruleSet() { return FieldSpec.builder(endpointRulesSpecUtils.rulesRuntimeClassName("EndpointRuleset"), RULE_SET_FIELD_NAME) .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("ruleSet()") .build(); } private MethodSpec toIdentifierValueMap() { ParameterizedTypeName resultType = ParameterizedTypeName.get(ClassName.get(Map.class), endpointRulesSpecUtils.rulesRuntimeClassName("Identifier"), endpointRulesSpecUtils.rulesRuntimeClassName("Value")); String paramsName = "params"; MethodSpec.Builder b = MethodSpec.methodBuilder("toIdentifierValueMap") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .addParameter(endpointRulesSpecUtils.parametersClassName(), paramsName) .returns(resultType); Map<String, ParameterModel> params = intermediateModel.getEndpointRuleSetModel().getParameters(); String resultName = "paramsMap"; b.addStatement("$T $N = new $T<>()", resultType, resultName, HashMap.class); params.forEach((name, model) -> { String methodVarName = endpointRulesSpecUtils.paramMethodName(name); CodeBlock identifierExpr = CodeBlock.of("$T.of($S)", endpointRulesSpecUtils.rulesRuntimeClassName("Identifier"), name); CodeBlock coerce; // We treat region specially and generate it as the Region type, // so we need to call id() to convert it back to string if (model.getBuiltInEnum() == BuiltInParameter.AWS_REGION) { coerce = CodeBlock.builder().add(".id()").build(); } else { coerce = CodeBlock.builder().build(); } CodeBlock valueExpr = endpointRulesSpecUtils.valueCreationCode( model.getType(), CodeBlock.builder() .add("$N.$N()$L", paramsName, methodVarName, coerce) .build()); b.beginControlFlow("if ($N.$N() != null)", paramsName, methodVarName); b.addStatement("$N.put($L, $L)", resultName, identifierExpr, valueExpr); b.endControlFlow(); }); b.addStatement("return $N", resultName); return b.build(); } private MethodSpec resolveEndpointMethod() { String paramsName = "endpointParams"; MethodSpec.Builder b = MethodSpec.methodBuilder("resolveEndpoint") .addModifiers(Modifier.PUBLIC) .returns(endpointRulesSpecUtils.resolverReturnType()) .addAnnotation(Override.class) .addParameter(endpointRulesSpecUtils.parametersClassName(), paramsName); b.addCode(validateRequiredParams()); b.addStatement("$T res = new $T().evaluate($N, toIdentifierValueMap($N))", endpointRulesSpecUtils.rulesRuntimeClassName("Value"), endpointRulesSpecUtils.rulesRuntimeClassName("DefaultRuleEngine"), RULE_SET_FIELD_NAME, paramsName); b.beginControlFlow("try"); b.addStatement("return $T.completedFuture($T.valueAsEndpointOrThrow($N))", CompletableFuture.class, endpointRulesSpecUtils.rulesRuntimeClassName("AwsEndpointProviderUtils"), "res"); b.endControlFlow(); b.beginControlFlow("catch ($T error)", Exception.class); b.addStatement("return $T.failedFuture(error)", CompletableFutureUtils.class); b.endControlFlow(); return b.build(); } private MethodSpec ruleSetBuildMethod(TypeSpec.Builder classBuilder) { RuleSetCreationSpec ruleSetCreationSpec = new RuleSetCreationSpec(intermediateModel); MethodSpec.Builder b = MethodSpec.methodBuilder("ruleSet") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(endpointRulesSpecUtils.rulesRuntimeClassName("EndpointRuleset")) .addStatement("return $L", ruleSetCreationSpec.ruleSetCreationExpr()); ruleSetCreationSpec.helperMethods().forEach(classBuilder::addMethod); return b.build(); } private CodeBlock validateRequiredParams() { CodeBlock.Builder b = CodeBlock.builder(); Map<String, ParameterModel> parameters = intermediateModel.getEndpointRuleSetModel().getParameters(); parameters.entrySet().stream() .filter(e -> Boolean.TRUE.equals(e.getValue().isRequired())) .forEach(e -> { b.addStatement("$T.notNull($N.$N(), $S)", Validate.class, "endpointParams", endpointRulesSpecUtils.paramMethodName(e.getKey()), String.format("Parameter '%s' must not be null", e.getKey())); }); return b.build(); } }
3,454
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/rules/EndpointRulesSpecUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.jr.stree.JrsBoolean; import com.fasterxml.jackson.jr.stree.JrsString; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URL; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.jar.JarFile; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.rules.endpoints.BuiltInParameter; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterModel; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.internal.CodegenNamingUtils; public class EndpointRulesSpecUtils { private final IntermediateModel intermediateModel; public EndpointRulesSpecUtils(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; } public String basePackage() { return intermediateModel.getMetadata().getFullEndpointRulesPackageName(); } public ClassName rulesRuntimeClassName(String name) { return ClassName.get(intermediateModel.getMetadata().getFullInternalEndpointRulesPackageName(), name); } public ClassName parametersClassName() { return ClassName.get(basePackage(), intermediateModel.getMetadata().getServiceName() + "EndpointParams"); } public ClassName providerInterfaceName() { return ClassName.get(basePackage(), intermediateModel.getMetadata().getServiceName() + "EndpointProvider"); } public ClassName providerDefaultImplName() { Metadata md = intermediateModel.getMetadata(); return ClassName.get(md.getFullInternalEndpointRulesPackageName(), "Default" + providerInterfaceName().simpleName()); } public ClassName resolverInterceptorName() { Metadata md = intermediateModel.getMetadata(); return ClassName.get(md.getFullInternalEndpointRulesPackageName(), md.getServiceName() + "ResolveEndpointInterceptor"); } public ClassName requestModifierInterceptorName() { Metadata md = intermediateModel.getMetadata(); return ClassName.get(md.getFullInternalEndpointRulesPackageName(), md.getServiceName() + "RequestSetEndpointInterceptor"); } public ClassName clientEndpointTestsName() { Metadata md = intermediateModel.getMetadata(); return ClassName.get(md.getFullEndpointRulesPackageName(), md.getServiceName() + "ClientEndpointTests"); } public ClassName endpointProviderTestsName() { Metadata md = intermediateModel.getMetadata(); return ClassName.get(md.getFullEndpointRulesPackageName(), md.getServiceName() + "EndpointProviderTests"); } public ClassName clientContextParamsName() { Metadata md = intermediateModel.getMetadata(); return ClassName.get(md.getFullEndpointRulesPackageName(), md.getServiceName() + "ClientContextParams"); } public String paramMethodName(String param) { return Utils.unCapitalize(CodegenNamingUtils.pascalCase(param)); } public String clientContextParamMethodName(String param) { return Utils.unCapitalize(CodegenNamingUtils.pascalCase(param)); } public String clientContextParamName(String paramName) { return intermediateModel.getNamingStrategy().getEnumValueName(paramName); } public TypeName toJavaType(String type) { switch (type.toLowerCase(Locale.ENGLISH)) { case "boolean": return TypeName.get(Boolean.class); case "string": return TypeName.get(String.class); default: throw new RuntimeException("Unknown type: " + type); } } public CodeBlock valueCreationCode(String type, CodeBlock param) { String methodName; switch (type.toLowerCase(Locale.ENGLISH)) { case "boolean": methodName = "fromBool"; break; case "string": methodName = "fromStr"; break; default: throw new RuntimeException("Don't know how to create a Value instance from type " + type); } return CodeBlock.builder() .add("$T.$N($L)", rulesRuntimeClassName("Value"), methodName, param) .build(); } public TypeName parameterType(ParameterModel param) { if (param.getBuiltInEnum() == null || param.getBuiltInEnum() != BuiltInParameter.AWS_REGION) { return toJavaType(param.getType()); } if (param.getBuiltInEnum() == BuiltInParameter.AWS_REGION) { return ClassName.get(Region.class); } return toJavaType(param.getType()); } public CodeBlock treeNodeToLiteral(TreeNode treeNode) { CodeBlock.Builder b = CodeBlock.builder(); switch (treeNode.asToken()) { case VALUE_STRING: b.add("$S", Validate.isInstanceOf(JrsString.class, treeNode, "Expected string").getValue()); break; case VALUE_TRUE: case VALUE_FALSE: b.add("$L", Validate.isInstanceOf(JrsBoolean.class, treeNode, "Expected boolean").booleanValue()); break; default: throw new RuntimeException("Don't know how to set default value for parameter of type " + treeNode.asToken()); } return b.build(); } public boolean isS3() { return "S3".equals(intermediateModel.getMetadata().getServiceName()); } public boolean isS3Control() { return "S3Control".equals(intermediateModel.getMetadata().getServiceName()); } public TypeName resolverReturnType() { return ParameterizedTypeName.get(CompletableFuture.class, Endpoint.class); } public List<String> rulesEngineResourceFiles() { URL currentJarUrl = EndpointRulesSpecUtils.class.getProtectionDomain().getCodeSource().getLocation(); try (JarFile jarFile = new JarFile(currentJarUrl.getFile())) { return jarFile.stream() .map(ZipEntry::getName) .filter(e -> e.startsWith("software/amazon/awssdk/codegen/rules")) .collect(Collectors.toList()); } catch (IOException e) { throw new UncheckedIOException(e); } } public Map<String, ParameterModel> parameters() { return intermediateModel.getEndpointRuleSetModel().getParameters(); } public boolean isDeclaredParam(String paramName) { Map<String, ParameterModel> parameters = intermediateModel.getEndpointRuleSetModel().getParameters(); return parameters.containsKey(paramName); } /** * Creates a data-class level field for the given parameter. For instance * * <pre> * private final Region region; * </pre> */ public FieldSpec parameterClassField(String name, ParameterModel model) { return parameterFieldSpecBuilder(name, model) .addModifiers(Modifier.PRIVATE) .addModifiers(Modifier.FINAL) .build(); } /** * Creates a data-class method to access the given parameter. For instance * * <pre> * public Region region() {…}; * </pre> */ public MethodSpec parameterClassAccessorMethod(String name, ParameterModel model) { MethodSpec.Builder b = parameterMethodBuilder(name, model); b.returns(parameterType(model)); b.addStatement("return $N", variableName(name)); return b.build(); } /** * Creates a data-interface method to access the given parameter. For instance * * <pre> * Region region(); * </pre> */ public MethodSpec parameterInterfaceAccessorMethod(String name, ParameterModel model) { MethodSpec.Builder b = parameterMethodBuilder(name, model); b.returns(parameterType(model)); b.addModifiers(Modifier.ABSTRACT); return b.build(); } /** * Creates a builder-class level field for the given parameter initialized to its default value when present. For instance * * <pre> * private Boolean useGlobalEndpoint = false; * </pre> */ public FieldSpec parameterBuilderFieldSpec(String name, ParameterModel model) { return parameterFieldSpecBuilder(name, model) .initializer(parameterDefaultValueCode(model)) .build(); } /** * Creates a builder-interface method to set the given parameter. For instance * * <pre> * Builder region(Region region); * </pre> * */ public MethodSpec parameterBuilderSetterMethodDeclaration(ClassName containingClass, String name, ParameterModel model) { MethodSpec.Builder b = parameterMethodBuilder(name, model); b.addModifiers(Modifier.ABSTRACT); b.addParameter(parameterSpec(name, model)); b.returns(containingClass.nestedClass("Builder")); return b.build(); } /** * Creates a builder-class method to set the given parameter. For instance * * <pre> * public Builder region(Region region) {…}; * </pre> */ public MethodSpec parameterBuilderSetterMethod(ClassName containingClass, String name, ParameterModel model) { String memberName = variableName(name); MethodSpec.Builder b = parameterMethodBuilder(name, model) .addAnnotation(Override.class) .addParameter(parameterSpec(name, model)) .returns(containingClass.nestedClass("Builder")) .addStatement("this.$1N = $1N", memberName); TreeNode defaultValue = model.getDefault(); if (defaultValue != null) { b.beginControlFlow("if (this.$N == null)", memberName); b.addStatement("this.$N = $L", memberName, parameterDefaultValueCode(model)); b.endControlFlow(); } b.addStatement("return this"); return b.build(); } /** * Used internally to create a field for the given parameter. Returns the builder that can be further tailor to be used for * data-classes or for builder-classes. */ private FieldSpec.Builder parameterFieldSpecBuilder(String name, ParameterModel model) { return FieldSpec.builder(parameterType(model), variableName(name)) .addModifiers(Modifier.PRIVATE); } /** * Used internally to create the spec for a parameter to be used in a method for the given param model. For instance, for * {@code ParameterModel} for {@code Region} it creates this parameter for the builder setter. * * <pre> * public Builder region( * Region region // <<--- This * ) {…}; * </pre> */ private ParameterSpec parameterSpec(String name, ParameterModel model) { return ParameterSpec.builder(parameterType(model), variableName(name)).build(); } /** * Used internally to create a accessor method for the given parameter model. Returns the builder that can be further * tailor to be used for data-classes/interfaces and builder-classes/interfaces. */ private MethodSpec.Builder parameterMethodBuilder(String name, ParameterModel model) { MethodSpec.Builder b = MethodSpec.methodBuilder(paramMethodName(name)); b.addModifiers(Modifier.PUBLIC); if (model.getDeprecated() != null) { b.addAnnotation(Deprecated.class); } return b; } /** * Used internally to create the code to initialize the default value modeled for the given parameter. For instance, if the * modeled default for region is "us-east-1", it will create * * <pre> * Region.of("us-east-1") * </pre> * * and if the modeled default value for a boolean parameter useGlobalEndpoint is "false", it will create * * <pre> * false * </pre> */ private CodeBlock parameterDefaultValueCode(ParameterModel parameterModel) { CodeBlock.Builder b = CodeBlock.builder(); TreeNode defaultValue = parameterModel.getDefault(); if (defaultValue == null) { return b.build(); } switch (defaultValue.asToken()) { case VALUE_STRING: String stringValue = ((JrsString) defaultValue).getValue(); if (parameterModel.getBuiltInEnum() == BuiltInParameter.AWS_REGION) { b.add("$T.of($S)", Region.class, stringValue); } else { b.add("$S", stringValue); } break; case VALUE_TRUE: case VALUE_FALSE: b.add("$L", ((JrsBoolean) defaultValue).booleanValue()); break; default: throw new RuntimeException("Don't know how to set default value for parameter of type " + defaultValue.asToken()); } return b.build(); } /** * Returns the name as a variable name using the intermediate model naming strategy. */ public String variableName(String name) { return intermediateModel.getNamingStrategy().getVariableName(name); } }
3,455
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/rules/EndpointParametersClassSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Map; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; public class EndpointParametersClassSpec implements ClassSpec { private final IntermediateModel intermediateModel; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public EndpointParametersClassSpec(IntermediateModel intermediateModel) { this.intermediateModel = intermediateModel; this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(intermediateModel); } @Override public TypeSpec poetSpec() { TypeSpec.Builder b = PoetUtils.createClassBuilder(className()) .addJavadoc("The parameters object used to resolve an endpoint for the $L service.", intermediateModel.getMetadata().getServiceName()) .addMethod(ctor()) .addMethod(builderMethod()) .addType(builderInterfaceSpec()) .addType(builderImplSpec()) .addAnnotation(SdkPublicApi.class) .addSuperinterface(toCopyableBuilderInterface()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL); parameters().forEach((name, model) -> { b.addField(endpointRulesSpecUtils.parameterClassField(name, model)); b.addMethod(endpointRulesSpecUtils.parameterClassAccessorMethod(name, model)); }); b.addMethod(toBuilderMethod()); return b.build(); } @Override public ClassName className() { return endpointRulesSpecUtils.parametersClassName(); } private TypeSpec builderInterfaceSpec() { TypeSpec.Builder b = TypeSpec.interfaceBuilder(builderInterfaceName()) .addSuperinterface(copyableBuilderExtendsInterface()) .addModifiers(Modifier.PUBLIC); parameters().forEach((name, model) -> { b.addMethod(endpointRulesSpecUtils.parameterBuilderSetterMethodDeclaration(className(), name, model)); }); b.addMethod(MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(className()) .build()); return b.build(); } private TypeSpec builderImplSpec() { TypeSpec.Builder b = TypeSpec.classBuilder(builderClassName()) .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .addSuperinterface(builderInterfaceName()); b.addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build()); b.addMethod(toBuilderConstructor().build()); parameters().forEach((name, model) -> { b.addField(endpointRulesSpecUtils.parameterBuilderFieldSpec(name, model)); b.addMethod(endpointRulesSpecUtils.parameterBuilderSetterMethod(className(), name, model)); }); b.addMethod(MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(className()) .addCode(CodeBlock.builder() .addStatement("return new $T(this)", className()) .build()) .build()); return b.build(); } private ClassName builderInterfaceName() { return className().nestedClass("Builder"); } private ClassName builderClassName() { return className().nestedClass("BuilderImpl"); } private Map<String, ParameterModel> parameters() { return intermediateModel.getEndpointRuleSetModel().getParameters(); } private MethodSpec ctor() { MethodSpec.Builder b = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(builderClassName(), "builder"); parameters().forEach((name, model) -> { b.addStatement("this.$1N = builder.$1N", variableName(name)); }); return b.build(); } private MethodSpec builderMethod() { return MethodSpec.methodBuilder("builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(builderInterfaceName()) .addStatement("return new $T()", builderClassName()) .build(); } private MethodSpec toBuilderMethod() { return MethodSpec.methodBuilder("toBuilder") .addModifiers(Modifier.PUBLIC) .returns(builderInterfaceName()) .addStatement("return new $T(this)", builderClassName()) .build(); } private String variableName(String name) { return intermediateModel.getNamingStrategy().getVariableName(name); } private MethodSpec.Builder toBuilderConstructor() { MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder(); constructorBuilder.addModifiers(Modifier.PRIVATE); constructorBuilder.addParameter(className(), "builder"); parameters().forEach((name, model) -> { constructorBuilder.addStatement("this.$1N = builder.$1N", variableName(name)); }); return constructorBuilder; } private TypeName toCopyableBuilderInterface() { return ParameterizedTypeName.get(ClassName.get(ToCopyableBuilder.class), className().nestedClass(builderInterfaceName().simpleName()), className()); } private TypeName copyableBuilderExtendsInterface() { return ParameterizedTypeName.get(ClassName.get(CopyableBuilder.class), builderInterfaceName(), className()); } }
3,456
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/rules/RequestEndpointInterceptorSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.SdkHttpRequest; public class RequestEndpointInterceptorSpec implements ClassSpec { private final EndpointRulesSpecUtils endpointRulesSpecUtils; public RequestEndpointInterceptorSpec(IntermediateModel model) { this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder b = PoetUtils.createClassBuilder(className()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(SdkInternalApi.class) .addSuperinterface(ExecutionInterceptor.class); b.addMethod(modifyHttpRequestMethod()); return b.build(); } @Override public ClassName className() { return endpointRulesSpecUtils.requestModifierInterceptorName(); } private MethodSpec modifyHttpRequestMethod() { MethodSpec.Builder b = MethodSpec.methodBuilder("modifyHttpRequest") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(SdkHttpRequest.class) .addParameter(Context.ModifyHttpRequest.class, "context") .addParameter(ExecutionAttributes.class, "executionAttributes"); // We skip setting the endpoint here if the source of the endpoint is the endpoint discovery call b.beginControlFlow("if ($1T.endpointIsDiscovered(executionAttributes))", endpointRulesSpecUtils.rulesRuntimeClassName("AwsEndpointProviderUtils")) .addStatement("return context.httpRequest()") .endControlFlow().build(); b.addStatement("$1T endpoint = ($1T) executionAttributes.getAttribute($2T.RESOLVED_ENDPOINT)", Endpoint.class, SdkInternalExecutionAttribute.class); b.addStatement("return $T.setUri(context.httpRequest()," + "executionAttributes.getAttribute($T.CLIENT_ENDPOINT)," + "endpoint.url())", endpointRulesSpecUtils.rulesRuntimeClassName("AwsEndpointProviderUtils"), SdkExecutionAttribute.class); return b.build(); } }
3,457
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/rules/TestGeneratorUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.jr.stree.JrsArray; import com.fasterxml.jackson.jr.stree.JrsBoolean; import com.fasterxml.jackson.jr.stree.JrsString; import com.fasterxml.jackson.jr.stree.JrsValue; import com.squareup.javapoet.CodeBlock; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.awscore.endpoints.AwsEndpointAttribute; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4AuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4aAuthScheme; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.rules.endpoints.ExpectModel; import software.amazon.awssdk.codegen.model.service.EndpointTrait; import software.amazon.awssdk.codegen.model.service.HostPrefixProcessor; import software.amazon.awssdk.core.rules.testing.model.Expect; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.utils.StringUtils; public final class TestGeneratorUtils { private TestGeneratorUtils() { } public static CodeBlock createExpect(ExpectModel expect, OperationModel opModel, Map<String, TreeNode> opParams) { CodeBlock.Builder b = CodeBlock.builder(); b.add("$T.builder()", Expect.class); if (expect.getError() != null) { b.add(".error($S)", expect.getError()); } else { CodeBlock.Builder endpointBuilder = CodeBlock.builder(); ExpectModel.Endpoint endpoint = expect.getEndpoint(); String expectedUrl = createExpectedUrl(endpoint, opModel, opParams); endpointBuilder.add("$T.builder()", Endpoint.class); endpointBuilder.add(".url($T.create($S))", URI.class, expectedUrl); if (endpoint.getHeaders() != null) { Map<String, List<String>> expectHeaders = endpoint.getHeaders(); expectHeaders.forEach((name, values) -> { values.forEach(v -> endpointBuilder.add(".putHeader($S, $S)", name, v)); }); } if (endpoint.getProperties() != null) { endpoint.getProperties().forEach((name, value) -> { addEndpointAttributeBlock(endpointBuilder, name, value); }); } endpointBuilder.add(".build()"); b.add(".endpoint($L)", endpointBuilder.build()); } b.add(".build()"); return b.build(); } public static Optional<String> getHostPrefixTemplate(OperationModel opModel) { EndpointTrait endpointTrait = opModel.getEndpointTrait(); if (endpointTrait == null) { return Optional.empty(); } return Optional.ofNullable(endpointTrait.getHostPrefix()); } private static void addEndpointAttributeBlock(CodeBlock.Builder builder, String attrName, TreeNode attrValue) { switch (attrName) { case "authSchemes": addAuthSchemesBlock(builder, attrValue); break; default: throw new RuntimeException("Encountered unknown expected endpoint attribute: " + attrName); } } private static void addAuthSchemesBlock(CodeBlock.Builder builder, TreeNode attrValue) { CodeBlock keyExpr = CodeBlock.builder() .add("$T.AUTH_SCHEMES", AwsEndpointAttribute.class) .build(); CodeBlock.Builder schemesListExpr = CodeBlock.builder() .add("$T.asList(", Arrays.class); JrsArray schemesArray = (JrsArray) attrValue; Iterator<JrsValue> elementsIter = schemesArray.elements(); while (elementsIter.hasNext()) { schemesListExpr.add("$L", authSchemeCreationExpr(elementsIter.next())); if (elementsIter.hasNext()) { schemesListExpr.add(","); } } schemesListExpr.add(")"); builder.add(".putAttribute($L, $L)", keyExpr, schemesListExpr.build()); } private static CodeBlock authSchemeCreationExpr(TreeNode attrValue) { CodeBlock.Builder schemeExpr = CodeBlock.builder(); String name = ((JrsString) attrValue.get("name")).getValue(); switch (name) { case "sigv4": schemeExpr.add("$T.builder()", SigV4AuthScheme.class); break; case "sigv4a": schemeExpr.add("$T.builder()", SigV4aAuthScheme.class); break; default: throw new RuntimeException("Unknown expected auth scheme: " + name); } Iterator<String> membersIter = attrValue.fieldNames(); while (membersIter.hasNext()) { String memberName = membersIter.next(); TreeNode memberValue = attrValue.get(memberName); switch (memberName) { case "name": break; case "signingName": schemeExpr.add(".signingName($S)", ((JrsString) memberValue).getValue()); break; case "signingRegion": schemeExpr.add(".signingRegion($S)", ((JrsString) memberValue).getValue()); break; case "disableDoubleEncoding": schemeExpr.add(".disableDoubleEncoding($L)", ((JrsBoolean) memberValue).booleanValue()); break; case "signingRegionSet": { JrsArray regions = (JrsArray) memberValue; regions.elements().forEachRemaining(r -> { schemeExpr.add(".addSigningRegion($S)", ((JrsString) r).getValue()); }); break; } default: throw new RuntimeException("Unknown auth scheme property: " + memberName); } } schemeExpr.add(".build()"); return schemeExpr.build(); } private static String createExpectedUrl(ExpectModel.Endpoint endpoint, OperationModel opModel, Map<String, TreeNode> opParams) { Optional<String> prefix = getHostPrefix(opModel, opParams); if (!prefix.isPresent()) { return endpoint.getUrl(); } URI originalUrl = URI.create(endpoint.getUrl()); try { URI newUrl = new URI(originalUrl.getScheme(), null, prefix.get() + originalUrl.getHost(), originalUrl.getPort(), originalUrl.getPath(), originalUrl.getQuery(), originalUrl.getFragment()); return newUrl.toString(); } catch (URISyntaxException e) { throw new RuntimeException("Expected url creation failed", e); } } private static Optional<String> getHostPrefix(OperationModel opModel, Map<String, TreeNode> opParams) { if (opModel == null) { return Optional.empty(); } Optional<String> hostPrefixTemplate = getHostPrefixTemplate(opModel); if (!hostPrefixTemplate.isPresent() || StringUtils.isBlank(hostPrefixTemplate.get())) { return Optional.empty(); } HostPrefixProcessor processor = new HostPrefixProcessor(hostPrefixTemplate.get()); String pattern = processor.hostWithStringSpecifier(); for (String c2jName : processor.c2jNames()) { if (opParams != null && opParams.containsKey(c2jName)) { String value = ((JrsString) opParams.get(c2jName)).getValue(); pattern = StringUtils.replaceOnce(pattern, "%s", value); } else { pattern = StringUtils.replaceOnce(pattern, "%s", "aws"); } } return Optional.of(pattern); } }
3,458
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/rules/EndpointProviderTestSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.AnnotationSpec; 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.ArrayList; import java.util.List; import java.util.Map; import javax.lang.model.element.Modifier; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.rules.endpoints.BuiltInParameter; import software.amazon.awssdk.codegen.model.rules.endpoints.EndpointTestModel; import software.amazon.awssdk.codegen.model.rules.endpoints.ParameterModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.core.rules.testing.BaseEndpointProviderTest; import software.amazon.awssdk.core.rules.testing.EndpointProviderTestCase; import software.amazon.awssdk.regions.Region; public class EndpointProviderTestSpec implements ClassSpec { private static final String PROVIDER_NAME = "PROVIDER"; private final IntermediateModel model; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public EndpointProviderTestSpec(IntermediateModel model) { this.model = model; this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder b = PoetUtils.createClassBuilder(className()) .superclass(BaseEndpointProviderTest.class) .addField(ruleEngine()) .addModifiers(Modifier.PUBLIC); b.addMethod(testMethod()); b.addMethod(testsCasesMethod()); return b.build(); } @Override public ClassName className() { return endpointRulesSpecUtils.endpointProviderTestsName(); } private FieldSpec ruleEngine() { return FieldSpec.builder(endpointRulesSpecUtils.providerInterfaceName(), PROVIDER_NAME) .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("$T.defaultProvider()", endpointRulesSpecUtils.providerInterfaceName()) .build(); } private MethodSpec testsCasesMethod() { TypeName returnType = ParameterizedTypeName.get(List.class, EndpointProviderTestCase.class); MethodSpec.Builder b = MethodSpec.methodBuilder("testCases") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(returnType); b.addStatement("$T testCases = new $T<>()", returnType, ArrayList.class); model.getEndpointTestSuiteModel().getTestCases().forEach(test -> { b.addStatement("testCases.add(new $T($L, $L))", EndpointProviderTestCase.class, createTestCase(test), TestGeneratorUtils.createExpect(test.getExpect(), null, null)); }); b.addStatement("return testCases"); return b.build(); } private MethodSpec testMethod() { AnnotationSpec methodSourceSpec = AnnotationSpec.builder(MethodSource.class) .addMember("value", "$S", "testCases") .build(); MethodSpec.Builder b = MethodSpec.methodBuilder("resolvesCorrectEndpoint") .addModifiers(Modifier.PUBLIC) .addParameter(EndpointProviderTestCase.class, "tc") .addAnnotation(methodSourceSpec) .addAnnotation(ParameterizedTest.class) .returns(void.class); b.addStatement("verify(tc)"); return b.build(); } private CodeBlock createTestCase(EndpointTestModel test) { CodeBlock.Builder b = CodeBlock.builder(); b.beginControlFlow("() ->"); ClassName parametersClass = endpointRulesSpecUtils.parametersClassName(); b.add("$T builder = $T.builder();", parametersClass.nestedClass("Builder"), parametersClass); if (test.getParams() != null) { test.getParams().forEach((n, v) -> { if (!endpointRulesSpecUtils.isDeclaredParam(n)) { return; } String setterName = endpointRulesSpecUtils.paramMethodName(n); CodeBlock valueLiteral = endpointRulesSpecUtils.treeNodeToLiteral(v); if (isRegionBuiltIn(n)) { b.add("builder.$N($T.of($L));", setterName, Region.class, valueLiteral); } else { b.add("builder.$N($L);", setterName, valueLiteral); } }); } b.add("return $N.resolveEndpoint(builder.build()).join();", PROVIDER_NAME); b.endControlFlow(); return b.build(); } private boolean isRegionBuiltIn(String paramName) { Map<String, ParameterModel> parameters = model.getEndpointRuleSetModel().getParameters(); ParameterModel param = parameters.get(paramName); return param.getBuiltInEnum() == BuiltInParameter.AWS_REGION; } }
3,459
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/builder/BaseClientBuilderClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PROTECTED; 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.TypeVariableName; import com.squareup.javapoet.WildcardTypeName; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.TokenUtils; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.token.credentials.aws.DefaultAwsTokenProvider; import software.amazon.awssdk.auth.token.signer.aws.BearerTokenSigner; import software.amazon.awssdk.awscore.client.builder.AwsDefaultClientBuilder; import software.amazon.awssdk.awscore.client.config.AwsClientOption; 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.service.AuthType; import software.amazon.awssdk.codegen.model.service.ClientContextParam; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeSpecUtils; import software.amazon.awssdk.codegen.poet.model.ServiceClientConfigurationUtils; import software.amazon.awssdk.codegen.poet.rules.EndpointRulesSpecUtils; import software.amazon.awssdk.codegen.utils.AuthUtils; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.endpointdiscovery.providers.DefaultEndpointDiscoveryProviderChain; import software.amazon.awssdk.core.interceptor.ClasspathInterceptorChainFactory; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.identity.spi.TokenIdentity; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.internal.CodegenNamingUtils; public class BaseClientBuilderClass implements ClassSpec { private static final ParameterizedTypeName GENERIC_AUTH_SCHEME_TYPE = ParameterizedTypeName.get(ClassName.get(AuthScheme.class), WildcardTypeName.subtypeOf(Object.class)); private final IntermediateModel model; private final ClassName builderInterfaceName; private final ClassName builderClassName; private final String basePackage; private final EndpointRulesSpecUtils endpointRulesSpecUtils; private final AuthSchemeSpecUtils authSchemeSpecUtils; private final ServiceClientConfigurationUtils configurationUtils; public BaseClientBuilderClass(IntermediateModel model) { this.model = model; this.basePackage = model.getMetadata().getFullClientPackageName(); this.builderInterfaceName = ClassName.get(basePackage, model.getMetadata().getBaseBuilderInterface()); this.builderClassName = ClassName.get(basePackage, model.getMetadata().getBaseBuilder()); this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); this.authSchemeSpecUtils = new AuthSchemeSpecUtils(model); this.configurationUtils = new ServiceClientConfigurationUtils(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = PoetUtils.createClassBuilder(builderClassName) .addModifiers(Modifier.ABSTRACT) .addAnnotation(SdkInternalApi.class) .addTypeVariable(PoetUtils.createBoundedTypeVariableName("B", builderInterfaceName, "B", "C")) .addTypeVariable(TypeVariableName.get("C")) .superclass(PoetUtils.createParameterizedTypeName(AwsDefaultClientBuilder.class, "B", "C")) .addJavadoc("Internal base class for {@link $T} and {@link $T}.", ClassName.get(basePackage, model.getMetadata().getSyncBuilder()), ClassName.get(basePackage, model.getMetadata().getAsyncBuilder())); // Only services that require endpoint discovery for at least one of their operations get a default value of // 'true' if (model.getEndpointOperation().isPresent()) { builder.addField(FieldSpec.builder(boolean.class, "endpointDiscoveryEnabled") .addModifiers(PROTECTED) .initializer(resolveDefaultEndpointDiscovery() ? "true" : "false") .build()); } if (authSchemeSpecUtils.useSraAuth()) { builder.addField(FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), GENERIC_AUTH_SCHEME_TYPE), "additionalAuthSchemes") .addModifiers(PRIVATE, FINAL) .initializer("new $T<>()", HashMap.class) .build()); } builder.addMethod(serviceEndpointPrefixMethod()); builder.addMethod(serviceNameMethod()); builder.addMethod(mergeServiceDefaultsMethod()); mergeInternalDefaultsMethod().ifPresent(builder::addMethod); builder.addMethod(finalizeServiceConfigurationMethod()); if (!authSchemeSpecUtils.useSraAuth()) { defaultAwsAuthSignerMethod().ifPresent(builder::addMethod); } builder.addMethod(signingNameMethod()); builder.addMethod(defaultEndpointProviderMethod()); if (authSchemeSpecUtils.useSraAuth()) { builder.addMethod(authSchemeProviderMethod()); builder.addMethod(defaultAuthSchemeProviderMethod()); builder.addMethod(putAuthSchemeMethod()); builder.addMethod(authSchemesMethod()); } if (hasClientContextParams()) { model.getClientContextParams().forEach((n, m) -> { builder.addMethod(clientContextParamSetter(n, m)); }); } if (hasSdkClientContextParams()) { model.getCustomizationConfig().getCustomClientContextParams().forEach((n, m) -> { builder.addMethod(clientContextParamSetter(n, m)); }); } if (model.getCustomizationConfig().getServiceConfig().getClassName() != null) { builder.addMethod(setServiceConfigurationMethod()) .addMethod(beanStyleSetServiceConfigurationMethod()); } if (AuthUtils.usesBearerAuth(model)) { builder.addMethod(defaultBearerTokenProviderMethod()); if (!authSchemeSpecUtils.useSraAuth()) { builder.addMethod(defaultTokenAuthSignerMethod()); } } addServiceHttpConfigIfNeeded(builder, model); builder.addMethod(invokePluginsMethod()); builder.addMethod(internalPluginsMethod()); builder.addMethod(validateClientOptionsMethod()); return builder.build(); } private boolean resolveDefaultEndpointDiscovery() { return model.getEndpointOperation() .map(OperationModel::isEndpointCacheRequired) .orElse(false); } private MethodSpec signingNameMethod() { return MethodSpec.methodBuilder("signingName") .addAnnotation(Override.class) .addModifiers(PROTECTED, FINAL) .returns(String.class) .addCode("return $S;", model.getMetadata().getSigningName()) .build(); } private Optional<MethodSpec> defaultAwsAuthSignerMethod() { return awsAuthSignerDefinitionMethodBody().map(body -> MethodSpec.methodBuilder("defaultSigner") .returns(Signer.class) .addModifiers(PRIVATE) .addCode(body) .build()); } private MethodSpec serviceEndpointPrefixMethod() { return MethodSpec.methodBuilder("serviceEndpointPrefix") .addAnnotation(Override.class) .addModifiers(PROTECTED, FINAL) .returns(String.class) .addCode("return $S;", model.getMetadata().getEndpointPrefix()) .build(); } private MethodSpec serviceNameMethod() { return MethodSpec.methodBuilder("serviceName") .addAnnotation(Override.class) .addModifiers(PROTECTED, FINAL) .returns(String.class) .addCode("return $S;", model.getMetadata().getServiceName()) .build(); } private MethodSpec mergeServiceDefaultsMethod() { boolean crc32FromCompressedDataEnabled = model.getCustomizationConfig().isCalculateCrc32FromCompressedData(); MethodSpec.Builder builder = MethodSpec.methodBuilder("mergeServiceDefaults") .addAnnotation(Override.class) .addModifiers(PROTECTED, FINAL) .returns(SdkClientConfiguration.class) .addParameter(SdkClientConfiguration.class, "config") .addCode("return config.merge(c -> c"); builder.addCode(".option($T.ENDPOINT_PROVIDER, defaultEndpointProvider())", SdkClientOption.class); if (authSchemeSpecUtils.useSraAuth()) { builder.addCode(".option($T.AUTH_SCHEME_PROVIDER, defaultAuthSchemeProvider())", SdkClientOption.class); builder.addCode(".option($T.AUTH_SCHEMES, authSchemes())", SdkClientOption.class); } else { if (defaultAwsAuthSignerMethod().isPresent()) { builder.addCode(".option($T.SIGNER, defaultSigner())\n", SdkAdvancedClientOption.class); } } builder.addCode(".option($T.CRC32_FROM_COMPRESSED_DATA_ENABLED, $L)\n", SdkClientOption.class, crc32FromCompressedDataEnabled); String clientConfigClassName = model.getCustomizationConfig().getServiceConfig().getClassName(); if (StringUtils.isNotBlank(clientConfigClassName)) { builder.addCode(".option($T.SERVICE_CONFIGURATION, $T.builder().build())\n", SdkClientOption.class, ClassName.bestGuess(clientConfigClassName)); } if (AuthUtils.usesBearerAuth(model)) { builder.addCode(".lazyOption($1T.TOKEN_PROVIDER, p -> $2T.toSdkTokenProvider(p.get($1T.TOKEN_IDENTITY_PROVIDER)))", AwsClientOption.class, TokenUtils.class); builder.addCode(".option($T.TOKEN_IDENTITY_PROVIDER, defaultTokenProvider())\n", AwsClientOption.class); if (!authSchemeSpecUtils.useSraAuth()) { builder.addCode(".option($T.TOKEN_SIGNER, defaultTokenSigner())", SdkAdvancedClientOption.class); } } builder.addCode(");"); return builder.build(); } private Optional<MethodSpec> mergeInternalDefaultsMethod() { String userAgent = model.getCustomizationConfig().getUserAgent(); RetryMode defaultRetryMode = model.getCustomizationConfig().getDefaultRetryMode(); // If none of the options are customized, then we do not need to bother overriding the method if (userAgent == null && defaultRetryMode == null) { return Optional.empty(); } MethodSpec.Builder builder = MethodSpec.methodBuilder("mergeInternalDefaults") .addAnnotation(Override.class) .addModifiers(PROTECTED, FINAL) .returns(SdkClientConfiguration.class) .addParameter(SdkClientConfiguration.class, "config") .addCode("return config.merge(c -> {\n"); if (userAgent != null) { builder.addCode("c.option($T.INTERNAL_USER_AGENT, $S);\n", SdkClientOption.class, userAgent); } if (defaultRetryMode != null) { builder.addCode("c.option($T.DEFAULT_RETRY_MODE, $T.$L);\n", SdkClientOption.class, RetryMode.class, defaultRetryMode.name()); } builder.addCode("});\n"); return Optional.of(builder.build()); } private MethodSpec finalizeServiceConfigurationMethod() { String requestHandlerDirectory = Utils.packageToDirectory(model.getMetadata().getFullClientPackageName()); String requestHandlerPath = String.format("%s/execution.interceptors", requestHandlerDirectory); MethodSpec.Builder builder = MethodSpec.methodBuilder("finalizeServiceConfiguration") .addAnnotation(Override.class) .addModifiers(PROTECTED, FINAL) .returns(SdkClientConfiguration.class) .addParameter(SdkClientConfiguration.class, "config"); // Initialize configuration values builder.addStatement("$T endpointInterceptors = new $T<>()", ParameterizedTypeName.get(List.class, ExecutionInterceptor.class), ArrayList.class); List<ClassName> builtInInterceptors = new ArrayList<>(); if (authSchemeSpecUtils.useSraAuth()) { builtInInterceptors.add(authSchemeSpecUtils.authSchemeInterceptor()); } builtInInterceptors.add(endpointRulesSpecUtils.resolverInterceptorName()); builtInInterceptors.add(endpointRulesSpecUtils.requestModifierInterceptorName()); for (String interceptor : model.getCustomizationConfig().getInterceptors()) { builtInInterceptors.add(ClassName.bestGuess(interceptor)); } for (ClassName interceptor : builtInInterceptors) { builder.addStatement("endpointInterceptors.add(new $T())", interceptor); } builder.addCode("$1T interceptorFactory = new $1T();\n", ClasspathInterceptorChainFactory.class) .addCode("$T<$T> interceptors = interceptorFactory.getInterceptors($S);\n", List.class, ExecutionInterceptor.class, requestHandlerPath); builder.addStatement("$T additionalInterceptors = new $T<>()", ParameterizedTypeName.get(List.class, ExecutionInterceptor.class), ArrayList.class); builder.addStatement("interceptors = $T.mergeLists(endpointInterceptors, interceptors)", CollectionUtils.class); builder.addStatement("interceptors = $T.mergeLists(interceptors, additionalInterceptors)", CollectionUtils.class); builder.addCode("interceptors = $T.mergeLists(interceptors, config.option($T.EXECUTION_INTERCEPTORS));\n", CollectionUtils.class, SdkClientOption.class); if (model.getEndpointOperation().isPresent()) { builder.beginControlFlow("if (!endpointDiscoveryEnabled)") .addStatement("$1T chain = new $1T(config)", DefaultEndpointDiscoveryProviderChain.class) .addStatement("endpointDiscoveryEnabled = chain.resolveEndpointDiscovery()") .endControlFlow(); } String clientConfigClassName = model.getCustomizationConfig().getServiceConfig().getClassName(); if (StringUtils.isNotBlank(clientConfigClassName)) { mergeServiceConfiguration(builder, clientConfigClassName); } if (model.getCustomizationConfig().useGlobalEndpoint()) { builder.addStatement("$T resolver = new UseGlobalEndpointResolver(config)", ClassName.get("software.amazon.awssdk.services.s3.internal.endpoints", "UseGlobalEndpointResolver")); } // Update configuration builder.addStatement("$T builder = config.toBuilder()", SdkClientConfiguration.Builder.class); builder.addCode("builder.lazyOption($T.IDENTITY_PROVIDERS, c -> {", SdkClientOption.class) .addStatement("$1T.Builder result = $1T.builder()", IdentityProviders.class); if (AuthUtils.usesBearerAuth(model)) { builder.addStatement("$T<?> tokenIdentityProvider = c.get($T.TOKEN_IDENTITY_PROVIDER)", IdentityProvider.class, AwsClientOption.class); builder.beginControlFlow("if (tokenIdentityProvider != null)"); builder.addStatement("result.putIdentityProvider(tokenIdentityProvider)"); builder.endControlFlow(); } if (AuthUtils.usesAwsAuth(model)) { builder.addStatement("$T<?> credentialsIdentityProvider = c.get($T.CREDENTIALS_IDENTITY_PROVIDER)", IdentityProvider.class, AwsClientOption.class); builder.beginControlFlow("if (credentialsIdentityProvider != null)", AwsClientOption.class); builder.addStatement("result.putIdentityProvider(credentialsIdentityProvider)"); builder.endControlFlow(); } builder.addStatement("return result.build()") .addCode("});"); builder.addCode("builder.option($1T.EXECUTION_INTERCEPTORS, interceptors)", SdkClientOption.class); if (model.getCustomizationConfig().getServiceConfig().hasDualstackProperty()) { builder.addCode(".option($T.DUALSTACK_ENDPOINT_ENABLED, finalServiceConfig.dualstackEnabled())", AwsClientOption.class); } if (model.getCustomizationConfig().getServiceConfig().hasFipsProperty()) { builder.addCode(".option($T.FIPS_ENDPOINT_ENABLED, finalServiceConfig.fipsModeEnabled())", AwsClientOption.class); } if (model.getEndpointOperation().isPresent()) { builder.addCode(".option($T.ENDPOINT_DISCOVERY_ENABLED, endpointDiscoveryEnabled)\n", SdkClientOption.class); } if (StringUtils.isNotBlank(model.getCustomizationConfig().getCustomRetryPolicy())) { builder.addCode(".option($1T.RETRY_POLICY, $2T.resolveRetryPolicy(config))", SdkClientOption.class, PoetUtils.classNameFromFqcn(model.getCustomizationConfig().getCustomRetryPolicy())); } if (StringUtils.isNotBlank(clientConfigClassName)) { builder.addCode(".option($T.SERVICE_CONFIGURATION, finalServiceConfig)", SdkClientOption.class); } if (model.getCustomizationConfig().useGlobalEndpoint()) { builder.addCode(".option($1T.USE_GLOBAL_ENDPOINT, resolver.resolve(config.option($1T.AWS_REGION)))", AwsClientOption.class); } if (hasClientContextParams()) { builder.addCode(".option($T.CLIENT_CONTEXT_PARAMS, clientContextParams.build())", SdkClientOption.class); } builder.addCode(";\n"); builder.addStatement("return builder.build()"); return builder.build(); } private void mergeServiceConfiguration(MethodSpec.Builder builder, String clientConfigClassName) { ClassName clientConfigClass = ClassName.bestGuess(clientConfigClassName); builder.addCode("$1T.Builder serviceConfigBuilder = (($1T) config.option($2T.SERVICE_CONFIGURATION)).toBuilder();" + "serviceConfigBuilder.profileFile(serviceConfigBuilder.profileFileSupplier() != null ? " + "serviceConfigBuilder.profileFileSupplier() : config.option($2T.PROFILE_FILE_SUPPLIER));" + "serviceConfigBuilder.profileName(serviceConfigBuilder.profileName() " + "!= null ? serviceConfigBuilder.profileName() : config.option($2T.PROFILE_NAME));", clientConfigClass, SdkClientOption.class); if (model.getCustomizationConfig().getServiceConfig().hasDualstackProperty()) { builder.addCode("if (serviceConfigBuilder.dualstackEnabled() != null) {") .addCode(" $T.validState(config.option($T.DUALSTACK_ENDPOINT_ENABLED) == null, \"Dualstack has been " + "configured on both $L and the client/global level. Please limit dualstack configuration to " + "one location.\");", Validate.class, AwsClientOption.class, clientConfigClassName) .addCode("} else {") .addCode(" serviceConfigBuilder.dualstackEnabled(config.option($T.DUALSTACK_ENDPOINT_ENABLED));", AwsClientOption.class) .addCode("}"); } if (model.getCustomizationConfig().getServiceConfig().hasFipsProperty()) { builder.addCode("if (serviceConfigBuilder.fipsModeEnabled() != null) {") .addCode(" $T.validState(config.option($T.FIPS_ENDPOINT_ENABLED) == null, \"Fips has been " + "configured on both $L and the client/global level. Please limit fips configuration to " + "one location.\");", Validate.class, AwsClientOption.class, clientConfigClassName) .addCode("} else {") .addCode(" serviceConfigBuilder.fipsModeEnabled(config.option($T.FIPS_ENDPOINT_ENABLED));", AwsClientOption.class) .addCode("}"); } if (model.getCustomizationConfig().getServiceConfig().hasUseArnRegionProperty()) { builder.addCode("if (serviceConfigBuilder.useArnRegionEnabled() != null) {") .addCode(" $T.validState(clientContextParams.get($T.USE_ARN_REGION) == null, \"UseArnRegion has been " + "configured on both $L and the client/global level. Please limit UseArnRegion configuration to " + "one location.\");", Validate.class, endpointRulesSpecUtils.clientContextParamsName(), clientConfigClassName) .addCode("} else {") .addCode(" serviceConfigBuilder.useArnRegionEnabled(clientContextParams.get($T.USE_ARN_REGION));", endpointRulesSpecUtils.clientContextParamsName()) .addCode("}"); } if (model.getCustomizationConfig().getServiceConfig().hasMultiRegionEnabledProperty()) { builder.addCode("if (serviceConfigBuilder.multiRegionEnabled() != null) {") .addCode(" $T.validState(clientContextParams.get($T.DISABLE_MULTI_REGION_ACCESS_POINTS) == null, " + "\"DisableMultiRegionAccessPoints has been configured on both $L and the client/global level. " + "Please limit DisableMultiRegionAccessPoints configuration to one location.\");", Validate.class, endpointRulesSpecUtils.clientContextParamsName(), clientConfigClassName) .addCode("} else if (clientContextParams.get($T.DISABLE_MULTI_REGION_ACCESS_POINTS) != null) {", endpointRulesSpecUtils.clientContextParamsName()) .addCode(" serviceConfigBuilder.multiRegionEnabled(!clientContextParams.get($T" + ".DISABLE_MULTI_REGION_ACCESS_POINTS));", endpointRulesSpecUtils.clientContextParamsName()) .addCode("}"); } if (model.getCustomizationConfig().getServiceConfig().hasForcePathTypeEnabledProperty()) { builder.addCode("if (serviceConfigBuilder.pathStyleAccessEnabled() != null) {") .addCode(" $T.validState(clientContextParams.get($T.FORCE_PATH_STYLE) == null, " + "\"ForcePathStyle has been configured on both $L and the client/global level. " + "Please limit ForcePathStyle configuration to one location.\");", Validate.class, endpointRulesSpecUtils.clientContextParamsName(), clientConfigClassName) .addCode("} else {") .addCode(" serviceConfigBuilder.pathStyleAccessEnabled(clientContextParams.get($T" + ".FORCE_PATH_STYLE));", endpointRulesSpecUtils.clientContextParamsName()) .addCode("}"); } if (model.getCustomizationConfig().getServiceConfig().hasAccelerateModeEnabledProperty()) { builder.addCode("if (serviceConfigBuilder.accelerateModeEnabled() != null) {") .addCode(" $T.validState(clientContextParams.get($T.ACCELERATE) == null, " + "\"Accelerate has been configured on both $L and the client/global level. " + "Please limit Accelerate configuration to one location.\");", Validate.class, endpointRulesSpecUtils.clientContextParamsName(), clientConfigClassName) .addCode("} else {") .addCode(" serviceConfigBuilder.accelerateModeEnabled(clientContextParams.get($T" + ".ACCELERATE));", endpointRulesSpecUtils.clientContextParamsName()) .addCode("}"); } builder.addStatement("$T finalServiceConfig = serviceConfigBuilder.build()", clientConfigClass); if (model.getCustomizationConfig().getServiceConfig().hasUseArnRegionProperty()) { builder.addCode( CodeBlock.builder() .addStatement("clientContextParams.put($T.USE_ARN_REGION, finalServiceConfig.useArnRegionEnabled())", endpointRulesSpecUtils.clientContextParamsName()) .build()); } if (model.getCustomizationConfig().getServiceConfig().hasMultiRegionEnabledProperty()) { builder.addCode( CodeBlock.builder() .addStatement("clientContextParams.put($T.DISABLE_MULTI_REGION_ACCESS_POINTS, !finalServiceConfig" + ".multiRegionEnabled())", endpointRulesSpecUtils.clientContextParamsName()) .build()); } if (model.getCustomizationConfig().getServiceConfig().hasForcePathTypeEnabledProperty()) { builder.addCode(CodeBlock.builder() .addStatement("clientContextParams.put($T.FORCE_PATH_STYLE, finalServiceConfig" + ".pathStyleAccessEnabled())", endpointRulesSpecUtils.clientContextParamsName()) .build()); } if (model.getCustomizationConfig().getServiceConfig().hasAccelerateModeEnabledProperty()) { builder.addCode(CodeBlock.builder() .addStatement("clientContextParams.put($T.ACCELERATE, finalServiceConfig" + ".accelerateModeEnabled())", endpointRulesSpecUtils.clientContextParamsName()) .build()); } } private MethodSpec setServiceConfigurationMethod() { ClassName serviceConfiguration = ClassName.get(basePackage, model.getCustomizationConfig().getServiceConfig().getClassName()); return MethodSpec.methodBuilder("serviceConfiguration") .addModifiers(Modifier.PUBLIC) .returns(TypeVariableName.get("B")) .addParameter(serviceConfiguration, "serviceConfiguration") .addStatement("clientConfiguration.option($T.SERVICE_CONFIGURATION, serviceConfiguration)", SdkClientOption.class) .addStatement("return thisBuilder()") .build(); } private MethodSpec beanStyleSetServiceConfigurationMethod() { ClassName serviceConfiguration = ClassName.get(basePackage, model.getCustomizationConfig().getServiceConfig().getClassName()); return MethodSpec.methodBuilder("setServiceConfiguration") .addModifiers(Modifier.PUBLIC) .addParameter(serviceConfiguration, "serviceConfiguration") .addStatement("serviceConfiguration(serviceConfiguration)") .build(); } private void addServiceHttpConfigIfNeeded(TypeSpec.Builder builder, IntermediateModel model) { String serviceDefaultFqcn = model.getCustomizationConfig().getServiceSpecificHttpConfig(); boolean supportsH2 = model.getMetadata().supportsH2(); if (serviceDefaultFqcn != null || supportsH2) { builder.addMethod(serviceSpecificHttpConfigMethod(serviceDefaultFqcn, supportsH2)); } } private MethodSpec serviceSpecificHttpConfigMethod(String serviceDefaultFqcn, boolean supportsH2) { return MethodSpec.methodBuilder("serviceHttpConfig") .addAnnotation(Override.class) .addModifiers(PROTECTED, FINAL) .returns(AttributeMap.class) .addCode(serviceSpecificHttpConfigMethodBody(serviceDefaultFqcn, supportsH2)) .build(); } private CodeBlock serviceSpecificHttpConfigMethodBody(String serviceDefaultFqcn, boolean supportsH2) { CodeBlock.Builder builder = CodeBlock.builder(); if (serviceDefaultFqcn != null) { builder.addStatement("$T result = $T.defaultHttpConfig()", AttributeMap.class, PoetUtils.classNameFromFqcn(model.getCustomizationConfig().getServiceSpecificHttpConfig())); } else { builder.addStatement("$1T result = $1T.empty()", AttributeMap.class); } if (supportsH2) { builder.addStatement("return result.merge(AttributeMap.builder()" + ".put($T.PROTOCOL, $T.HTTP2)" + ".build())", SdkHttpConfigurationOption.class, Protocol.class); } else { builder.addStatement("return result"); } return builder.build(); } private Optional<CodeBlock> awsAuthSignerDefinitionMethodBody() { AuthType authType = model.getMetadata().getAuthType(); switch (authType) { case V4: return Optional.of(v4SignerDefinitionMethodBody()); case S3: case S3V4: return Optional.of(s3SignerDefinitionMethodBody()); case BEARER: case NONE: return Optional.empty(); default: throw new UnsupportedOperationException("Unsupported signer type: " + authType); } } private CodeBlock v4SignerDefinitionMethodBody() { return CodeBlock.of("return $T.create();", Aws4Signer.class); } private CodeBlock s3SignerDefinitionMethodBody() { return CodeBlock.of("return $T.create();\n", ClassName.get("software.amazon.awssdk.auth.signer", "AwsS3V4Signer")); } private MethodSpec defaultEndpointProviderMethod() { return MethodSpec.methodBuilder("defaultEndpointProvider") .addModifiers(PRIVATE) .returns(endpointRulesSpecUtils.providerInterfaceName()) .addStatement("return $T.defaultProvider()", endpointRulesSpecUtils.providerInterfaceName()) .build(); } private MethodSpec authSchemeProviderMethod() { return MethodSpec.methodBuilder("authSchemeProvider") .addModifiers(Modifier.PUBLIC) .returns(TypeVariableName.get("B")) .addParameter(authSchemeSpecUtils.providerInterfaceName(), "authSchemeProvider") .addStatement("clientConfiguration.option($T.AUTH_SCHEME_PROVIDER, authSchemeProvider)", SdkClientOption.class) .addStatement("return thisBuilder()") .build(); } private MethodSpec defaultAuthSchemeProviderMethod() { return MethodSpec.methodBuilder("defaultAuthSchemeProvider") .addModifiers(PRIVATE) .returns(authSchemeSpecUtils.providerInterfaceName()) .addStatement("return $T.defaultProvider()", authSchemeSpecUtils.providerInterfaceName()) .build(); } private MethodSpec putAuthSchemeMethod() { return MethodSpec.methodBuilder("putAuthScheme") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeVariableName.get("B")) .addParameter(GENERIC_AUTH_SCHEME_TYPE, "authScheme") .addStatement("additionalAuthSchemes.put(authScheme.schemeId(), authScheme)") .addStatement("return thisBuilder()") .build(); } private MethodSpec clientContextParamSetter(String name, ClientContextParam param) { String setterName = endpointRulesSpecUtils.paramMethodName(name); String keyName = model.getNamingStrategy().getEnumValueName(name); TypeName type = endpointRulesSpecUtils.toJavaType(param.getType()); return MethodSpec.methodBuilder(setterName) .addModifiers(Modifier.PUBLIC) .returns(TypeVariableName.get("B")) .addParameter(type, setterName) .addStatement("clientContextParams.put($T.$N, $N)", endpointRulesSpecUtils.clientContextParamsName(), keyName, setterName) .addStatement("return thisBuilder()") .build(); } private MethodSpec defaultBearerTokenProviderMethod() { return MethodSpec.methodBuilder("defaultTokenProvider") .returns(ParameterizedTypeName.get(ClassName.get(IdentityProvider.class), WildcardTypeName.subtypeOf(TokenIdentity.class))) .addModifiers(PRIVATE) .addStatement("return $T.create()", DefaultAwsTokenProvider.class) .build(); } private MethodSpec defaultTokenAuthSignerMethod() { return MethodSpec.methodBuilder("defaultTokenSigner") .returns(Signer.class) .addModifiers(PRIVATE) .addStatement("return $T.create()", BearerTokenSigner.class) .build(); } private MethodSpec authSchemesMethod() { TypeName returns = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), ParameterizedTypeName.get(ClassName.get(AuthScheme.class), WildcardTypeName.subtypeOf(Object.class))); MethodSpec.Builder builder = MethodSpec.methodBuilder("authSchemes") .addModifiers(PRIVATE) .returns(returns); Set<Class<?>> concreteAuthSchemeClasses = authSchemeSpecUtils.allServiceConcreteAuthSchemeClasses(); builder.addStatement("$T schemes = new $T<>($L + this.additionalAuthSchemes.size())", returns, HashMap.class, concreteAuthSchemeClasses.size()); for (Class<?> concreteAuthScheme : concreteAuthSchemeClasses) { String instanceVariable = CodegenNamingUtils.lowercaseFirstChar(concreteAuthScheme.getSimpleName()); builder.addStatement("$1T $2L = $1T.create()", concreteAuthScheme, instanceVariable); builder.addStatement("schemes.put($1N.schemeId(), $1N)", instanceVariable); } builder.addStatement("schemes.putAll(this.additionalAuthSchemes)"); builder.addStatement("return schemes", Collections.class); return builder.build(); } private MethodSpec invokePluginsMethod() { MethodSpec.Builder builder = MethodSpec.methodBuilder("invokePlugins") .addAnnotation(Override.class) .addModifiers(PROTECTED) .addParameter(SdkClientConfiguration.class, "config") .returns(SdkClientConfiguration.class); builder.addStatement("$T internalPlugins = internalPlugins()", ParameterizedTypeName.get(List.class, SdkPlugin.class)); builder.addStatement("$T externalPlugins = plugins()", ParameterizedTypeName.get(List.class, SdkPlugin.class)) .beginControlFlow("if (internalPlugins.isEmpty() && externalPlugins.isEmpty())") .addStatement("return config") .endControlFlow(); builder.addStatement("$T plugins = $T.mergeLists(internalPlugins, externalPlugins)", ParameterizedTypeName.get(List.class, SdkPlugin.class), CollectionUtils.class); builder.addStatement("$T configuration = config.toBuilder()", SdkClientConfiguration.Builder.class) .addStatement("$1T serviceConfigBuilder = new $1T(configuration)", configurationUtils.serviceClientConfigurationBuilderClassName()) .beginControlFlow("for ($T plugin : plugins)", SdkPlugin.class) .addStatement("plugin.configureClient(serviceConfigBuilder)") .endControlFlow() .addStatement("return configuration.build()"); return builder.build(); } private MethodSpec internalPluginsMethod() { ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName .get(ClassName.get(List.class), ClassName.get(SdkPlugin.class)); MethodSpec.Builder builder = MethodSpec.methodBuilder("internalPlugins") .addModifiers(PRIVATE) .returns(parameterizedTypeName); List<String> internalPlugins = model.getCustomizationConfig().getInternalPlugins(); if (internalPlugins.isEmpty()) { return builder.addStatement("return $T.emptyList()", Collections.class) .build(); } builder.addStatement("$T internalPlugins = new $T<>()", parameterizedTypeName, ArrayList.class); for (String internalPlugin : internalPlugins) { ClassName pluginClass = ClassName.bestGuess(internalPlugin); builder.addStatement("internalPlugins.add(new $T())", pluginClass); } builder.addStatement("return internalPlugins"); return builder.build(); } @Override public ClassName className() { return builderClassName; } private boolean hasClientContextParams() { Map<String, ClientContextParam> clientContextParams = model.getClientContextParams(); return clientContextParams != null && !clientContextParams.isEmpty(); } private boolean hasSdkClientContextParams() { return model.getCustomizationConfig() != null && model.getCustomizationConfig().getCustomClientContextParams() != null && !model.getCustomizationConfig().getCustomClientContextParams().isEmpty(); } private MethodSpec validateClientOptionsMethod() { MethodSpec.Builder builder = MethodSpec.methodBuilder("validateClientOptions") .addModifiers(PROTECTED, Modifier.STATIC) .addParameter(SdkClientConfiguration.class, "c") .returns(void.class); if (AuthUtils.usesAwsAuth(model) && !authSchemeSpecUtils.useSraAuth()) { builder.addStatement("$T.notNull(c.option($T.SIGNER), $S)", Validate.class, SdkAdvancedClientOption.class, "The 'overrideConfiguration.advancedOption[SIGNER]' must be configured in the client builder."); } if (AuthUtils.usesBearerAuth(model)) { if (!authSchemeSpecUtils.useSraAuth()) { builder.addStatement("$T.notNull(c.option($T.TOKEN_SIGNER), $S)", Validate.class, SdkAdvancedClientOption.class, "The 'overrideConfiguration.advancedOption[TOKEN_SIGNER]' " + "must be configured in the client builder."); } builder.addStatement("$T.notNull(c.option($T.TOKEN_IDENTITY_PROVIDER), $S)", Validate.class, AwsClientOption.class, "The 'tokenProvider' must be configured in the client builder."); } return builder.build(); } }
3,460
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/builder/SyncClientBuilderClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.rules.EndpointRulesSpecUtils; import software.amazon.awssdk.codegen.utils.AuthUtils; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.TokenIdentity; public class SyncClientBuilderClass implements ClassSpec { private final IntermediateModel model; private final ClassName clientInterfaceName; private final ClassName clientClassName; private final ClassName builderInterfaceName; private final ClassName builderClassName; private final ClassName builderBaseClassName; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public SyncClientBuilderClass(IntermediateModel model) { String basePackage = model.getMetadata().getFullClientPackageName(); this.model = model; this.clientInterfaceName = ClassName.get(basePackage, model.getMetadata().getSyncInterface()); this.clientClassName = ClassName.get(basePackage, model.getMetadata().getSyncClient()); this.builderInterfaceName = ClassName.get(basePackage, model.getMetadata().getSyncBuilderInterface()); this.builderClassName = ClassName.get(basePackage, model.getMetadata().getSyncBuilder()); this.builderBaseClassName = ClassName.get(basePackage, model.getMetadata().getBaseBuilder()); this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = PoetUtils.createClassBuilder(builderClassName) .addAnnotation(SdkInternalApi.class) .addModifiers(Modifier.FINAL) .superclass(ParameterizedTypeName.get(builderBaseClassName, builderInterfaceName, clientInterfaceName)) .addSuperinterface(builderInterfaceName) .addJavadoc("Internal implementation of {@link $T}.", builderInterfaceName); if (model.getEndpointOperation().isPresent()) { builder.addMethod(endpointDiscoveryEnabled()); if (model.getCustomizationConfig().isEnableEndpointDiscoveryMethodRequired()) { builder.addMethod(enableEndpointDiscovery()); } } builder.addMethod(endpointProviderMethod()); if (AuthUtils.usesBearerAuth(model)) { builder.addMethod(tokenProviderMethodImpl()); } builder.addMethod(buildClientMethod()); return builder.build(); } private MethodSpec endpointDiscoveryEnabled() { return MethodSpec.methodBuilder("endpointDiscoveryEnabled") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(builderClassName) .addParameter(boolean.class, "endpointDiscoveryEnabled") .addStatement("this.endpointDiscoveryEnabled = endpointDiscoveryEnabled") .addStatement("return this") .build(); } private MethodSpec enableEndpointDiscovery() { return MethodSpec.methodBuilder("enableEndpointDiscovery") .addAnnotation(Override.class) .addAnnotation(Deprecated.class) .addJavadoc("@deprecated Use {@link #endpointDiscoveryEnabled($T)} instead.", boolean.class) .addModifiers(Modifier.PUBLIC) .returns(builderClassName) .addStatement("endpointDiscoveryEnabled = true") .addStatement("return this") .build(); } private MethodSpec endpointProviderMethod() { return MethodSpec.methodBuilder("endpointProvider") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(className()) .addParameter(endpointRulesSpecUtils.providerInterfaceName(), "endpointProvider") .addStatement("clientConfiguration.option($T.ENDPOINT_PROVIDER, endpointProvider)", SdkClientOption.class) .addStatement("return this") .build(); } private MethodSpec buildClientMethod() { MethodSpec.Builder builder = MethodSpec.methodBuilder("buildClient") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED, Modifier.FINAL) .returns(clientInterfaceName) .addStatement("$T clientConfiguration = super.syncClientConfiguration()", SdkClientConfiguration.class) .addStatement("this.validateClientOptions(clientConfiguration)"); builder.addStatement("$1T client = new $2T(clientConfiguration)", clientInterfaceName, clientClassName); if (model.syncClientDecoratorClassName().isPresent()) { builder.addStatement("return new $T().decorate(client, clientConfiguration, clientContextParams.copy().build())", PoetUtils.classNameFromFqcn(model.syncClientDecoratorClassName().get())); } else { builder.addStatement("return client"); } return builder.build(); } private MethodSpec tokenProviderMethodImpl() { ParameterizedTypeName tokenProviderTypeName = ParameterizedTypeName.get(ClassName.get(IdentityProvider.class), WildcardTypeName.subtypeOf(TokenIdentity.class)); return MethodSpec.methodBuilder("tokenProvider").addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(tokenProviderTypeName, "tokenProvider") .returns(builderClassName) .addStatement("clientConfiguration.option($T.TOKEN_IDENTITY_PROVIDER, tokenProvider)", AwsClientOption.class) .addStatement("return this") .build(); } @Override public ClassName className() { return builderClassName; } }
3,461
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/builder/AsyncClientBuilderInterface.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 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 java.util.function.Consumer; import javax.lang.model.element.Modifier; import software.amazon.awssdk.awscore.client.builder.AwsAsyncClientBuilder; import software.amazon.awssdk.codegen.model.config.customization.MultipartCustomization; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class AsyncClientBuilderInterface implements ClassSpec { private static final Logger log = Logger.loggerFor(AsyncClientBuilderInterface.class); private final ClassName builderInterfaceName; private final ClassName clientInterfaceName; private final ClassName baseBuilderInterfaceName; private final IntermediateModel model; public AsyncClientBuilderInterface(IntermediateModel model) { String basePackage = model.getMetadata().getFullClientPackageName(); this.clientInterfaceName = ClassName.get(basePackage, model.getMetadata().getAsyncInterface()); this.builderInterfaceName = ClassName.get(basePackage, model.getMetadata().getAsyncBuilderInterface()); this.baseBuilderInterfaceName = ClassName.get(basePackage, model.getMetadata().getBaseBuilderInterface()); this.model = model; } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = PoetUtils .createInterfaceBuilder(builderInterfaceName) .addSuperinterface(ParameterizedTypeName.get(ClassName.get(AwsAsyncClientBuilder.class), builderInterfaceName, clientInterfaceName)) .addSuperinterface(ParameterizedTypeName.get(baseBuilderInterfaceName, builderInterfaceName, clientInterfaceName)) .addJavadoc(getJavadoc()); MultipartCustomization multipartCustomization = model.getCustomizationConfig().getMultipartCustomization(); if (multipartCustomization != null) { includeMultipartMethod(builder, multipartCustomization); } return builder.build(); } private void includeMultipartMethod(TypeSpec.Builder builder, MultipartCustomization multipartCustomization) { log.debug(() -> String.format("Adding multipart config methods to builder interface for service '%s'", model.getMetadata().getServiceId())); // .multipartEnabled(Boolean) builder.addMethod( MethodSpec.methodBuilder("multipartEnabled") .addModifiers(Modifier.DEFAULT, Modifier.PUBLIC) .returns(builderInterfaceName) .addParameter(Boolean.class, "enabled") .addCode("throw new $T();", UnsupportedOperationException.class) .addJavadoc(CodeBlock.of(multipartCustomization.getMultipartEnableMethodDoc())) .build()); // .multipartConfiguration(MultipartConfiguration) String multiPartConfigMethodName = "multipartConfiguration"; String multipartConfigClass = Validate.notNull(multipartCustomization.getMultipartConfigurationClass(), "'multipartConfigurationClass' must be defined"); ClassName mulitpartConfigClassName = PoetUtils.classNameFromFqcn(multipartConfigClass); builder.addMethod( MethodSpec.methodBuilder(multiPartConfigMethodName) .addModifiers(Modifier.DEFAULT, Modifier.PUBLIC) .returns(builderInterfaceName) .addParameter(ParameterSpec.builder(mulitpartConfigClassName, "multipartConfiguration").build()) .addCode("throw new $T();", UnsupportedOperationException.class) .addJavadoc(CodeBlock.of(multipartCustomization.getMultipartConfigMethodDoc())) .build()); // .multipartConfiguration(Consumer<MultipartConfiguration>) ClassName mulitpartConfigBuilderClassName = PoetUtils.classNameFromFqcn(multipartConfigClass + ".Builder"); ParameterizedTypeName consumerBuilderType = ParameterizedTypeName.get(ClassName.get(Consumer.class), mulitpartConfigBuilderClassName); builder.addMethod( MethodSpec.methodBuilder(multiPartConfigMethodName) .addModifiers(Modifier.DEFAULT, Modifier.PUBLIC) .returns(builderInterfaceName) .addParameter(ParameterSpec.builder(consumerBuilderType, "multipartConfiguration").build()) .addStatement("$T builder = $T.builder()", mulitpartConfigBuilderClassName, mulitpartConfigClassName) .addStatement("multipartConfiguration.accept(builder)") .addStatement("return multipartConfiguration(builder.build())") .addJavadoc(CodeBlock.of(multipartCustomization.getMultipartConfigMethodDoc())) .build()); } @Override public ClassName className() { return builderInterfaceName; } private CodeBlock getJavadoc() { return CodeBlock.of("A builder for creating an instance of {@link $1T}. This can be created with the static " + "{@link $1T#builder()} method.", clientInterfaceName); } }
3,462
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/builder/SyncClientBuilderInterface.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; public class SyncClientBuilderInterface implements ClassSpec { private final ClassName builderInterfaceName; private final ClassName clientInterfaceName; private final ClassName baseBuilderInterfaceName; public SyncClientBuilderInterface(IntermediateModel model) { String basePackage = model.getMetadata().getFullClientPackageName(); this.clientInterfaceName = ClassName.get(basePackage, model.getMetadata().getSyncInterface()); this.builderInterfaceName = ClassName.get(basePackage, model.getMetadata().getSyncBuilderInterface()); this.baseBuilderInterfaceName = ClassName.get(basePackage, model.getMetadata().getBaseBuilderInterface()); } @Override public TypeSpec poetSpec() { return PoetUtils.createInterfaceBuilder(builderInterfaceName) .addSuperinterface(ParameterizedTypeName.get(ClassName.get(AwsSyncClientBuilder.class), builderInterfaceName, clientInterfaceName)) .addSuperinterface(ParameterizedTypeName.get(baseBuilderInterfaceName, builderInterfaceName, clientInterfaceName)) .addJavadoc(getJavadoc()) .build(); } @Override public ClassName className() { return builderInterfaceName; } private CodeBlock getJavadoc() { return CodeBlock.of("A builder for creating an instance of {@link $1T}. This can be created with the static " + "{@link $1T#builder()} method.", clientInterfaceName); } }
3,463
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/builder/BaseClientBuilderInterface.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; 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 com.squareup.javapoet.WildcardTypeName; import java.util.function.Consumer; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.auth.token.credentials.aws.DefaultAwsTokenProvider; import software.amazon.awssdk.auth.token.signer.aws.BearerTokenSigner; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.service.ClientContextParam; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeSpecUtils; import software.amazon.awssdk.codegen.poet.rules.EndpointRulesSpecUtils; import software.amazon.awssdk.codegen.utils.AuthUtils; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.TokenIdentity; import software.amazon.awssdk.utils.internal.CodegenNamingUtils; public class BaseClientBuilderInterface implements ClassSpec { private static final ParameterizedTypeName TOKEN_IDENTITY_PROVIDER_TYPE_NAME = ParameterizedTypeName.get(ClassName.get(IdentityProvider.class), WildcardTypeName.subtypeOf(TokenIdentity.class)); private final IntermediateModel model; private final String basePackage; private final ClassName builderInterfaceName; private final EndpointRulesSpecUtils endpointRulesSpecUtils; private final AuthSchemeSpecUtils authSchemeSpecUtils; public BaseClientBuilderInterface(IntermediateModel model) { this.model = model; this.basePackage = model.getMetadata().getFullClientPackageName(); this.builderInterfaceName = ClassName.get(basePackage, model.getMetadata().getBaseBuilderInterface()); this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); this.authSchemeSpecUtils = new AuthSchemeSpecUtils(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = PoetUtils.createInterfaceBuilder(builderInterfaceName) .addAnnotation(SdkPublicApi.class) .addTypeVariable(PoetUtils.createBoundedTypeVariableName("B", builderInterfaceName, "B", "C")) .addTypeVariable(TypeVariableName.get("C")) .addSuperinterface(PoetUtils.createParameterizedTypeName(AwsClientBuilder.class, "B", "C")) .addJavadoc(getJavadoc()); if (model.getEndpointOperation().isPresent()) { if (model.getCustomizationConfig().isEnableEndpointDiscoveryMethodRequired()) { builder.addMethod(enableEndpointDiscovery()); } builder.addMethod(endpointDiscovery()); } if (model.getCustomizationConfig().getServiceConfig().getClassName() != null) { builder.addMethod(serviceConfigurationMethod()); builder.addMethod(serviceConfigurationConsumerBuilderMethod()); } builder.addMethod(endpointProviderMethod()); builder.addMethod(authSchemeProviderMethod()); if (hasClientContextParams()) { model.getClientContextParams().forEach((n, m) -> { builder.addMethod(clientContextParamSetter(n, m)); }); } if (hasSdkClientContextParams()) { model.getCustomizationConfig().getCustomClientContextParams().forEach((n, m) -> { builder.addMethod(clientContextParamSetter(n, m)); }); } if (generateTokenProviderMethod()) { builder.addMethod(tokenProviderMethod()); builder.addMethod(tokenIdentityProviderMethod()); } return builder.build(); } private CodeBlock getJavadoc() { return CodeBlock.of("This includes configuration specific to $L that is supported by both {@link $T} and {@link $T}.", model.getMetadata().getDescriptiveServiceName(), ClassName.get(basePackage, model.getMetadata().getSyncBuilderInterface()), ClassName.get(basePackage, model.getMetadata().getAsyncBuilderInterface())); } private MethodSpec enableEndpointDiscovery() { return MethodSpec.methodBuilder("enableEndpointDiscovery") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(TypeVariableName.get("B")) .addAnnotation(Deprecated.class) .addJavadoc("@deprecated Use {@link #endpointDiscoveryEnabled($T)} instead.", boolean.class) .build(); } private MethodSpec endpointDiscovery() { return MethodSpec.methodBuilder("endpointDiscoveryEnabled") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(TypeVariableName.get("B")) .addParameter(boolean.class, "endpointDiscovery") .build(); } private MethodSpec serviceConfigurationMethod() { ClassName serviceConfiguration = ClassName.get(basePackage, model.getCustomizationConfig().getServiceConfig().getClassName()); return MethodSpec.methodBuilder("serviceConfiguration") .addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC) .returns(TypeVariableName.get("B")) .addParameter(serviceConfiguration, "serviceConfiguration") .build(); } private MethodSpec serviceConfigurationConsumerBuilderMethod() { ClassName serviceConfiguration = ClassName.get(basePackage, model.getCustomizationConfig().getServiceConfig().getClassName()); TypeName consumerBuilder = ParameterizedTypeName.get(ClassName.get(Consumer.class), serviceConfiguration.nestedClass("Builder")); return MethodSpec.methodBuilder("serviceConfiguration") .addModifiers(Modifier.DEFAULT, Modifier.PUBLIC) .returns(TypeVariableName.get("B")) .addParameter(consumerBuilder, "serviceConfiguration") .addStatement("return serviceConfiguration($T.builder().applyMutation(serviceConfiguration).build())", serviceConfiguration) .build(); } private MethodSpec endpointProviderMethod() { return MethodSpec.methodBuilder("endpointProvider") .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) .addParameter(endpointRulesSpecUtils.providerInterfaceName(), "endpointProvider") .addJavadoc("Set the {@link $T} implementation that will be used by the client to determine " + "the endpoint for each request. This is optional; if none is provided a " + "default implementation will be used the SDK.", endpointRulesSpecUtils.providerInterfaceName()) .returns(TypeVariableName.get("B")) .addStatement("throw new $T()", UnsupportedOperationException.class) .build(); } private MethodSpec authSchemeProviderMethod() { return MethodSpec.methodBuilder("authSchemeProvider") .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) .addParameter(authSchemeSpecUtils.providerInterfaceName(), "authSchemeProvider") .addJavadoc("Set the {@link $T} implementation that will be used by the client to resolve the " + "auth scheme for each request. This is optional; if none is provided a " + "default implementation will be used the SDK.", authSchemeSpecUtils.providerInterfaceName()) .returns(TypeVariableName.get("B")) .addStatement("throw new $T()", UnsupportedOperationException.class) .build(); } private MethodSpec clientContextParamSetter(String name, ClientContextParam param) { String setterName = Utils.unCapitalize(CodegenNamingUtils.pascalCase(name)); TypeName type = endpointRulesSpecUtils.toJavaType(param.getType()); MethodSpec.Builder b = MethodSpec.methodBuilder(setterName) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addParameter(type, setterName) .returns(TypeVariableName.get("B")); PoetUtils.addJavadoc(b::addJavadoc, param.getDocumentation()); return b.build(); } private boolean generateTokenProviderMethod() { return AuthUtils.usesBearerAuth(model); } private MethodSpec tokenProviderMethod() { return MethodSpec.methodBuilder("tokenProvider") .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) .returns(TypeVariableName.get("B")) .addParameter(SdkTokenProvider.class, "tokenProvider") .addJavadoc("Set the token provider to use for bearer token authorization. This is optional, if none " + "is provided, the SDK will use {@link $T}.\n" + "<p>\n" + "If the service, or any of its operations require Bearer Token Authorization, then the " + "SDK will default to this token provider to retrieve the token to use for authorization.\n" + "<p>\n" + "This provider works in conjunction with the {@code $T.TOKEN_SIGNER} set on the client. " + "By default it is {@link $T}.", DefaultAwsTokenProvider.class, SdkAdvancedClientOption.class, BearerTokenSigner.class) .addStatement("return tokenProvider(($T) tokenProvider)", TOKEN_IDENTITY_PROVIDER_TYPE_NAME) .build(); } private MethodSpec tokenIdentityProviderMethod() { return MethodSpec.methodBuilder("tokenProvider") .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) .returns(TypeVariableName.get("B")) .addParameter(TOKEN_IDENTITY_PROVIDER_TYPE_NAME, "tokenProvider") .addJavadoc("Set the token provider to use for bearer token authorization. This is optional, if none " + "is provided, the SDK will use {@link $T}.\n" + "<p>\n" + "If the service, or any of its operations require Bearer Token Authorization, then the " + "SDK will default to this token provider to retrieve the token to use for authorization.\n" + "<p>\n" + "This provider works in conjunction with the {@code $T.TOKEN_SIGNER} set on the client. " + "By default it is {@link $T}.", DefaultAwsTokenProvider.class, SdkAdvancedClientOption.class, BearerTokenSigner.class) .addStatement("throw new $T()", UnsupportedOperationException.class) .build(); } @Override public ClassName className() { return builderInterfaceName; } private boolean hasClientContextParams() { return model.getClientContextParams() != null && !model.getClientContextParams().isEmpty(); } private boolean hasSdkClientContextParams() { return model.getCustomizationConfig() != null && model.getCustomizationConfig().getCustomClientContextParams() != null && !model.getCustomizationConfig().getCustomClientContextParams().isEmpty(); } }
3,464
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/builder/AsyncClientBuilderClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 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 com.squareup.javapoet.WildcardTypeName; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.codegen.model.config.customization.MultipartCustomization; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.rules.EndpointRulesSpecUtils; import software.amazon.awssdk.codegen.utils.AuthUtils; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.TokenIdentity; public class AsyncClientBuilderClass implements ClassSpec { private final IntermediateModel model; private final ClassName clientInterfaceName; private final ClassName clientClassName; private final ClassName builderInterfaceName; private final ClassName builderClassName; private final ClassName builderBaseClassName; private final EndpointRulesSpecUtils endpointRulesSpecUtils; public AsyncClientBuilderClass(IntermediateModel model) { String basePackage = model.getMetadata().getFullClientPackageName(); this.model = model; this.clientInterfaceName = ClassName.get(basePackage, model.getMetadata().getAsyncInterface()); this.clientClassName = ClassName.get(basePackage, model.getMetadata().getAsyncClient()); this.builderInterfaceName = ClassName.get(basePackage, model.getMetadata().getAsyncBuilderInterface()); this.builderClassName = ClassName.get(basePackage, model.getMetadata().getAsyncBuilder()); this.builderBaseClassName = ClassName.get(basePackage, model.getMetadata().getBaseBuilder()); this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = PoetUtils.createClassBuilder(builderClassName) .addAnnotation(SdkInternalApi.class) .addModifiers(Modifier.FINAL) .superclass(ParameterizedTypeName.get(builderBaseClassName, builderInterfaceName, clientInterfaceName)) .addSuperinterface(builderInterfaceName) .addJavadoc("Internal implementation of {@link $T}.", builderInterfaceName); if (model.getEndpointOperation().isPresent()) { builder.addMethod(endpointDiscoveryEnabled()); if (model.getCustomizationConfig().isEnableEndpointDiscoveryMethodRequired()) { builder.addMethod(enableEndpointDiscovery()); } } builder.addMethod(endpointProviderMethod()); if (AuthUtils.usesBearerAuth(model)) { builder.addMethod(tokenProviderMethod()); } MultipartCustomization multipartCustomization = model.getCustomizationConfig().getMultipartCustomization(); if (multipartCustomization != null) { builder.addMethod(multipartEnabledMethod(multipartCustomization)); builder.addMethod(multipartConfigMethods(multipartCustomization)); } builder.addMethod(buildClientMethod()); return builder.build(); } private MethodSpec endpointDiscoveryEnabled() { return MethodSpec.methodBuilder("endpointDiscoveryEnabled") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(builderClassName) .addParameter(boolean.class, "endpointDiscoveryEnabled") .addStatement("this.endpointDiscoveryEnabled = endpointDiscoveryEnabled") .addStatement("return this") .build(); } private MethodSpec enableEndpointDiscovery() { return MethodSpec.methodBuilder("enableEndpointDiscovery") .addAnnotation(Override.class) .addAnnotation(Deprecated.class) .addJavadoc("@deprecated Use {@link #endpointDiscoveryEnabled($T)} instead.", boolean.class) .addModifiers(Modifier.PUBLIC) .returns(builderClassName) .addStatement("endpointDiscoveryEnabled = true") .addStatement("return this") .build(); } private MethodSpec endpointProviderMethod() { MethodSpec.Builder b = MethodSpec.methodBuilder("endpointProvider") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(endpointRulesSpecUtils.providerInterfaceName(), "endpointProvider") .returns(builderClassName); b.addStatement("clientConfiguration.option($T.ENDPOINT_PROVIDER, endpointProvider)", SdkClientOption.class); b.addStatement("return this"); return b.build(); } private MethodSpec buildClientMethod() { MethodSpec.Builder builder = MethodSpec.methodBuilder("buildClient") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED, Modifier.FINAL) .returns(clientInterfaceName) .addStatement("$T clientConfiguration = super.asyncClientConfiguration()", SdkClientConfiguration.class) .addStatement("this.validateClientOptions(clientConfiguration)"); builder.addStatement("$1T client = new $2T(clientConfiguration)", clientInterfaceName, clientClassName); if (model.asyncClientDecoratorClassName().isPresent()) { builder.addStatement("return new $T().decorate(client, clientConfiguration, clientContextParams.copy().build())", PoetUtils.classNameFromFqcn(model.asyncClientDecoratorClassName().get())); } else { builder.addStatement("return client"); } return builder.build(); } private MethodSpec tokenProviderMethod() { ParameterizedTypeName tokenProviderTypeName = ParameterizedTypeName.get(ClassName.get(IdentityProvider.class), WildcardTypeName.subtypeOf(TokenIdentity.class)); return MethodSpec.methodBuilder("tokenProvider").addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(tokenProviderTypeName, "tokenProvider") .returns(builderClassName) .addStatement("clientConfiguration.option($T.TOKEN_IDENTITY_PROVIDER, tokenProvider)", AwsClientOption.class) .addStatement("return this") .build(); } private MethodSpec multipartEnabledMethod(MultipartCustomization multipartCustomization) { return MethodSpec.methodBuilder("multipartEnabled") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(builderInterfaceName) .addParameter(Boolean.class, "enabled") .addStatement("clientContextParams.put($N, enabled)", multipartCustomization.getContextParamEnabledKey()) .addStatement("return this") .build(); } private MethodSpec multipartConfigMethods(MultipartCustomization multipartCustomization) { ClassName mulitpartConfigClassName = PoetUtils.classNameFromFqcn(multipartCustomization.getMultipartConfigurationClass()); return MethodSpec.methodBuilder("multipartConfiguration") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(ParameterSpec.builder(mulitpartConfigClassName, "multipartConfig").build()) .returns(builderInterfaceName) .addStatement("clientContextParams.put($N, multipartConfig)", multipartCustomization.getContextParamConfigKey()) .addStatement("return this") .build(); } @Override public ClassName className() { return builderClassName; } }
3,465
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/transform/MarshallerSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.ArrayList; import java.util.List; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; 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.transform.protocols.EventStreamJsonMarshallerSpec; import software.amazon.awssdk.codegen.poet.transform.protocols.JsonMarshallerSpec; import software.amazon.awssdk.codegen.poet.transform.protocols.MarshallerProtocolSpec; import software.amazon.awssdk.codegen.poet.transform.protocols.QueryMarshallerSpec; import software.amazon.awssdk.codegen.poet.transform.protocols.XmlMarshallerSpec; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.utils.Validate; public class MarshallerSpec implements ClassSpec { private final IntermediateModel intermediateModel; private final ShapeModel shapeModel; private final ClassName baseMashallerName; private final TypeName httpRequestName; private final ClassName requestName; private final ClassName className; private final ClassName requestClassName; private final MarshallerProtocolSpec protocolSpec; public MarshallerSpec(IntermediateModel intermediateModel, ShapeModel shapeModel) { this.intermediateModel = intermediateModel; this.shapeModel = shapeModel; String modelPackage = intermediateModel.getMetadata().getFullModelPackageName(); this.baseMashallerName = ClassName.get(Marshaller.class); this.httpRequestName = ClassName.get(SdkHttpFullRequest.class); this.requestName = ClassName.get(modelPackage, shapeModel.getShapeName()); this.className = new PoetExtension(intermediateModel).getRequestTransformClass(shapeModel.getShapeName() + "Marshaller"); this.requestClassName = ClassName.get(modelPackage, shapeModel.getShapeName()); this.protocolSpec = getProtocolSpecs(intermediateModel.getMetadata().getProtocol()); } @Override public TypeSpec poetSpec() { return TypeSpec.classBuilder(className) .addJavadoc("{@link $T} Marshaller", requestClassName) .addModifiers(Modifier.PUBLIC) .addAnnotation(PoetUtils.generatedAnnotation()) .addAnnotation(SdkInternalApi.class) .addSuperinterface(ParameterizedTypeName.get(baseMashallerName, requestName)) .addFields(protocolSpec.memberVariables()) .addFields(protocolSpec.additionalFields()) .addMethods(methods()) .build(); } @Override public ClassName className() { return className; } private List<MethodSpec> methods() { List<MethodSpec> methodSpecs = new ArrayList<>(); protocolSpec.constructor().ifPresent(methodSpecs::add); methodSpecs.add(marshallMethod()); methodSpecs.addAll(protocolSpec.additionalMethods()); return methodSpecs; } private MethodSpec marshallMethod() { String variableName = shapeModel.getVariable().getVariableName(); MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder("marshall") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(requestClassName, variableName) .returns(httpRequestName); methodSpecBuilder.addStatement("$T.paramNotNull($L, $S)", ClassName.get(Validate.class), variableName, variableName); methodSpecBuilder.beginControlFlow("try"); methodSpecBuilder.addCode(protocolSpec.marshalCodeBlock(requestClassName)); methodSpecBuilder.endControlFlow(); methodSpecBuilder.beginControlFlow("catch (Exception e)"); methodSpecBuilder.addStatement("throw $T.builder().message(\"Unable to marshall request to JSON: \" + " + "e.getMessage()).cause(e).build()", ClassName .get(SdkClientException.class)); methodSpecBuilder.endControlFlow(); return methodSpecBuilder.build(); } private MarshallerProtocolSpec getProtocolSpecs(software.amazon.awssdk.codegen.model.intermediate.Protocol protocol) { switch (protocol) { case REST_JSON: case CBOR: case AWS_JSON: return getJsonMarshallerSpec(); case QUERY: case EC2: return new QueryMarshallerSpec(intermediateModel, shapeModel); case REST_XML: return new XmlMarshallerSpec(intermediateModel, shapeModel); default: throw new RuntimeException("Unknown protocol: " + protocol.name()); } } private MarshallerProtocolSpec getJsonMarshallerSpec() { if (shapeModel.isEvent()) { return new EventStreamJsonMarshallerSpec(intermediateModel, shapeModel); } return new JsonMarshallerSpec(shapeModel); } }
3,466
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/transform
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/transform/protocols/EventStreamJsonMarshallerSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.protocols; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; 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.intermediate.ShapeModel; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; /** * MarshallerSpec for event shapes in Json protocol */ public final class EventStreamJsonMarshallerSpec extends JsonMarshallerSpec { public EventStreamJsonMarshallerSpec(IntermediateModel model, ShapeModel shapeModel) { super(shapeModel); } @Override public CodeBlock marshalCodeBlock(ClassName requestClassName) { String variableName = shapeModel.getVariable().getVariableName(); CodeBlock.Builder builder = CodeBlock.builder() .addStatement("$T<$T> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING)", ProtocolMarshaller.class, SdkHttpFullRequest.class) .add("return protocolMarshaller.marshall($L).toBuilder()", variableName) .add(".putHeader($S, $S)", ":message-type", "event") .add(".putHeader($S, $N.sdkEventType().toString())", ":event-type", variableName); // Add :content-type header only if payload is present if (!shapeModel.hasNoEventPayload()) { builder.add(".putHeader(\":content-type\", $L)", determinePayloadContentType()); } builder.add(".build();"); return builder.build(); } @Override protected FieldSpec operationInfoField() { CodeBlock.Builder builder = CodeBlock.builder() .add("$T.builder()", OperationInfo.class) .add(".hasExplicitPayloadMember($L)", shapeModel.isHasPayloadMember() || shapeModel.getExplicitEventPayloadMember() != null) .add(".hasPayloadMembers($L)", shapeModel.hasPayloadMembers()) .add(".hasImplicitPayloadMembers($L)", shapeModel.hasImplicitEventPayloadMembers()) // Adding httpMethod to avoid validation failure while creating the SdkHttpFullRequest .add(".httpMethod($T.GET)", SdkHttpMethod.class) .add(".hasEvent(true)") .add(".build()"); return FieldSpec.builder(ClassName.get(OperationInfo.class), "SDK_OPERATION_BINDING") .addModifiers(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC) .initializer(builder.build()) .build(); } private String determinePayloadContentType() { MemberModel explicitEventPayload = shapeModel.getExplicitEventPayloadMember(); if (explicitEventPayload != null) { return getPayloadContentType(explicitEventPayload); } return "protocolFactory.getContentType()"; } private String getPayloadContentType(MemberModel memberModel) { String blobContentType = "\"application/octet-stream\""; String stringContentType = "\"text/plain\""; String variableType = memberModel.getVariable().getVariableType(); if ("software.amazon.awssdk.core.SdkBytes".equals(variableType)) { return blobContentType; } else if ("String".equals(variableType)) { return stringContentType; } return "protocolFactory.getContentType()"; } }
3,467
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/transform
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/transform/protocols/XmlMarshallerSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.protocols; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.protocols.xml.AwsXmlProtocolFactory; /** * MarshallerSpec for Xml protocol */ public class XmlMarshallerSpec extends QueryMarshallerSpec { public XmlMarshallerSpec(IntermediateModel model, ShapeModel shapeModel) { super(model, shapeModel); } @Override protected Class<?> protocolFactoryClass() { return AwsXmlProtocolFactory.class; } }
3,468
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/transform
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/transform/protocols/QueryMarshallerSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.protocols; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; 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.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.Protocol; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.query.AwsQueryProtocolFactory; import software.amazon.awssdk.protocols.xml.AwsXmlProtocolFactory; import software.amazon.awssdk.utils.StringUtils; public class QueryMarshallerSpec implements MarshallerProtocolSpec { protected final ShapeModel shapeModel; private final Metadata metadata; public QueryMarshallerSpec(IntermediateModel model, ShapeModel shapeModel) { this.metadata = model.getMetadata(); this.shapeModel = shapeModel; } @Override public ParameterSpec protocolFactoryParameter() { return ParameterSpec.builder(protocolFactoryClass(), "protocolFactory").build(); } protected Class<?> protocolFactoryClass() { return AwsQueryProtocolFactory.class; } @Override public CodeBlock marshalCodeBlock(ClassName requestClassName) { String variableName = shapeModel.getVariable().getVariableName(); return CodeBlock.builder() .addStatement("$T<$T> protocolMarshaller = protocolFactory.createProtocolMarshaller" + "(SDK_OPERATION_BINDING)", ProtocolMarshaller.class, SdkHttpFullRequest.class) .addStatement("return protocolMarshaller.marshall($L)", variableName) .build(); } @Override public FieldSpec protocolFactory() { return FieldSpec.builder(protocolFactoryClass(), "protocolFactory") .addModifiers(Modifier.PRIVATE, Modifier.FINAL).build(); } @Override public Optional<MethodSpec> constructor() { return Optional.of(MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(protocolFactoryParameter()) .addStatement("this.protocolFactory = protocolFactory") .build()); } @Override public List<FieldSpec> memberVariables() { List<FieldSpec> fields = new ArrayList<>(); CodeBlock.Builder initializationCodeBlockBuilder = CodeBlock.builder() .add("$T.builder()", OperationInfo.class); initializationCodeBlockBuilder.add(".requestUri($S)", shapeModel.getMarshaller().getRequestUri()) .add(".httpMethod($T.$L)", SdkHttpMethod.class, shapeModel.getMarshaller().getVerb()) .add(".hasExplicitPayloadMember($L)", shapeModel.isHasPayloadMember() || shapeModel.getExplicitEventPayloadMember() != null) .add(".hasPayloadMembers($L)", shapeModel.hasPayloadMembers()); if (StringUtils.isNotBlank(shapeModel.getMarshaller().getTarget())) { initializationCodeBlockBuilder.add(".operationIdentifier($S)", shapeModel.getMarshaller().getTarget()) .add(".apiVersion($S)", metadata.getApiVersion()); } if (shapeModel.isHasStreamingMember()) { initializationCodeBlockBuilder.add(".hasStreamingInput(true)"); } if (metadata.getProtocol() == Protocol.REST_XML) { String rootMarshallLocationName = shapeModel.getMarshaller() != null ? shapeModel.getMarshaller().getLocationName() : null; initializationCodeBlockBuilder.add(".putAdditionalMetadata($T.ROOT_MARSHALL_LOCATION_ATTRIBUTE, $S)", AwsXmlProtocolFactory.class, rootMarshallLocationName); initializationCodeBlockBuilder.add(".putAdditionalMetadata($T.XML_NAMESPACE_ATTRIBUTE, $S)", AwsXmlProtocolFactory.class, xmlNameSpaceUri()); } CodeBlock codeBlock = initializationCodeBlockBuilder.add(".build()").build(); FieldSpec.Builder instance = FieldSpec.builder(ClassName.get(OperationInfo.class), "SDK_OPERATION_BINDING") .addModifiers(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC) .initializer(codeBlock); fields.add(instance.build()); fields.add(protocolFactory()); return fields; } private String xmlNameSpaceUri() { if (shapeModel.getMarshaller() != null && shapeModel.getMarshaller().getXmlNameSpaceUri() != null) { return shapeModel.getMarshaller().getXmlNameSpaceUri(); } Set<String> xmlUris = shapeModel.getMembers().stream() .filter(m -> m.getXmlNameSpaceUri() != null) .map(MemberModel::getXmlNameSpaceUri) .collect(Collectors.toSet()); if (xmlUris.isEmpty()) { return null; } else if (xmlUris.size() == 1) { return xmlUris.iterator().next(); } else { throw new RuntimeException("Request has more than 1 xmlNameSpace uri."); } } }
3,469
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/transform
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/transform/protocols/MarshallerProtocolSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.protocols; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import java.util.ArrayList; import java.util.List; import java.util.Optional; public interface MarshallerProtocolSpec { ParameterSpec protocolFactoryParameter(); CodeBlock marshalCodeBlock(ClassName requestClassName); FieldSpec protocolFactory(); default List<FieldSpec> memberVariables() { return new ArrayList<>(); } default List<FieldSpec> additionalFields() { return new ArrayList<>(); } default List<MethodSpec> additionalMethods() { return new ArrayList<>(); } default Optional<MethodSpec> constructor() { return Optional.empty(); } }
3,470
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/transform
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/transform/protocols/JsonMarshallerSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.protocols; import static software.amazon.awssdk.codegen.poet.eventstream.EventStreamUtils.isEventStreamParentModel; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.json.BaseAwsJsonProtocolFactory; import software.amazon.awssdk.utils.StringUtils; /** * MarshallerSpec for Json protocol */ public class JsonMarshallerSpec implements MarshallerProtocolSpec { protected final ShapeModel shapeModel; public JsonMarshallerSpec(ShapeModel shapeModel) { this.shapeModel = shapeModel; } @Override public ParameterSpec protocolFactoryParameter() { return ParameterSpec.builder(protocolFactoryClass(), "protocolFactory").build(); } @Override public Optional<MethodSpec> constructor() { return Optional.of(MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(protocolFactoryParameter()) .addStatement("this.protocolFactory = protocolFactory") .build()); } @Override public CodeBlock marshalCodeBlock(ClassName requestClassName) { String variableName = shapeModel.getVariable().getVariableName(); return CodeBlock.builder() .addStatement("$T<$T> protocolMarshaller = protocolFactory.createProtocolMarshaller" + "(SDK_OPERATION_BINDING)", ProtocolMarshaller.class, SdkHttpFullRequest.class) .addStatement("return protocolMarshaller.marshall($L)", variableName) .build(); } @Override public FieldSpec protocolFactory() { return FieldSpec.builder(protocolFactoryClass(), "protocolFactory") .addModifiers(Modifier.PRIVATE, Modifier.FINAL).build(); } private Class<BaseAwsJsonProtocolFactory> protocolFactoryClass() { return BaseAwsJsonProtocolFactory.class; } @Override public List<FieldSpec> memberVariables() { List<FieldSpec> fields = new ArrayList<>(); fields.add(operationInfoField()); fields.add(protocolFactory()); return fields; } protected FieldSpec operationInfoField() { CodeBlock.Builder initializationCodeBlockBuilder = CodeBlock.builder() .add("$T.builder()", OperationInfo.class); initializationCodeBlockBuilder.add(".requestUri($S)", shapeModel.getMarshaller().getRequestUri()) .add(".httpMethod($T.$L)", SdkHttpMethod.class, shapeModel.getMarshaller().getVerb()) .add(".hasExplicitPayloadMember($L)", shapeModel.isHasPayloadMember() || shapeModel.getExplicitEventPayloadMember() != null) .add(".hasImplicitPayloadMembers($L)", shapeModel.hasImplicitPayloadMembers()) .add(".hasPayloadMembers($L)", shapeModel.hasPayloadMembers()); if (StringUtils.isNotBlank(shapeModel.getMarshaller().getTarget())) { initializationCodeBlockBuilder.add(".operationIdentifier($S)", shapeModel.getMarshaller().getTarget()); } if (shapeModel.isHasStreamingMember()) { initializationCodeBlockBuilder.add(".hasStreamingInput(true)"); } if (isEventStreamParentModel(shapeModel)) { initializationCodeBlockBuilder.add(".hasEventStreamingInput(true)"); } CodeBlock codeBlock = initializationCodeBlockBuilder.add(".build()").build(); return FieldSpec.builder(ClassName.get(OperationInfo.class), "SDK_OPERATION_BINDING") .addModifiers(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC) .initializer(codeBlock) .build(); } }
3,471
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/client/DelegatingAsyncClientClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static javax.lang.model.element.Modifier.ABSTRACT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PROTECTED; import static javax.lang.model.element.Modifier.PUBLIC; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.model.config.customization.UtilitiesMethod; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.core.SdkClient; import software.amazon.awssdk.utils.Validate; public class DelegatingAsyncClientClass extends AsyncClientInterface { private final IntermediateModel model; private final ClassName className; private final PoetExtension poetExtensions; public DelegatingAsyncClientClass(IntermediateModel model) { super(model); this.model = model; this.className = ClassName.get(model.getMetadata().getFullClientPackageName(), "Delegating" + model.getMetadata().getAsyncInterface()); this.poetExtensions = new PoetExtension(model); } @Override protected TypeSpec.Builder createTypeSpec() { return PoetUtils.createClassBuilder(className); } @Override protected void addInterfaceClass(TypeSpec.Builder type) { ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getAsyncInterface()); type.addSuperinterface(interfaceClass) .addMethod(constructor(interfaceClass)); } @Override protected void addAnnotations(TypeSpec.Builder type) { type.addAnnotation(SdkPublicApi.class); } @Override protected void addModifiers(TypeSpec.Builder type) { type.addModifiers(ABSTRACT, PUBLIC); } @Override protected void addFields(TypeSpec.Builder type) { ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getAsyncInterface()); type.addField(FieldSpec.builder(interfaceClass, "delegate") .addModifiers(PRIVATE, FINAL) .build()); } @Override protected void addAdditionalMethods(TypeSpec.Builder type) { type.addMethod(nameMethod()) .addMethod(delegateMethod()) .addMethod(invokeMethod()); } private MethodSpec nameMethod() { return MethodSpec.methodBuilder("serviceName") .addAnnotation(Override.class) .addModifiers(PUBLIC, FINAL) .returns(String.class) .addStatement("return delegate.serviceName()") .build(); } private MethodSpec delegateMethod() { return MethodSpec.methodBuilder("delegate") .addModifiers(PUBLIC) .addStatement("return this.delegate") .returns(SdkClient.class) .build(); } private MethodSpec invokeMethod() { TypeVariableName requestTypeVariableName = TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName())); TypeVariableName responseTypeVariableName = STREAMING_TYPE_VARIABLE; ParameterizedTypeName responseFutureTypeName = ParameterizedTypeName.get(ClassName.get(CompletableFuture.class), responseTypeVariableName); ParameterizedTypeName functionTypeName = ParameterizedTypeName .get(ClassName.get(Function.class), requestTypeVariableName, responseFutureTypeName); return MethodSpec.methodBuilder("invokeOperation") .addModifiers(PROTECTED) .addParameter(requestTypeVariableName, "request") .addParameter(functionTypeName, "operation") .addTypeVariable(requestTypeVariableName) .addTypeVariable(responseTypeVariableName) .returns(responseFutureTypeName) .addStatement("return operation.apply(request)") .build(); } @Override protected MethodSpec serviceClientConfigMethod() { return MethodSpec.methodBuilder("serviceClientConfiguration") .addAnnotation(Override.class) .addModifiers(PUBLIC, FINAL) .returns(new PoetExtension(model).getServiceConfigClass()) .addStatement("return delegate.serviceClientConfiguration()") .build(); } @Override protected void addCloseMethod(TypeSpec.Builder type) { MethodSpec method = MethodSpec.methodBuilder("close") .addAnnotation(Override.class) .addModifiers(PUBLIC) .addStatement("delegate.close()") .build(); type.addMethod(method); } @Override protected List<MethodSpec> operations() { return model.getOperations().values().stream() .flatMap(this::operations) .sorted(Comparator.comparing(m -> m.name)) .collect(toList()); } private Stream<MethodSpec> operations(OperationModel opModel) { List<MethodSpec> methods = new ArrayList<>(); methods.add(traditionalMethod(opModel)); return methods.stream(); } private MethodSpec constructor(ClassName interfaceClass) { return MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addParameter(interfaceClass, "delegate") .addStatement("$T.paramNotNull(delegate, \"delegate\")", Validate.class) .addStatement("this.delegate = delegate") .build(); } @Override public ClassName className() { return className; } @Override protected MethodSpec.Builder operationBody(MethodSpec.Builder builder, OperationModel opModel) { builder.addModifiers(PUBLIC) .addAnnotation(Override.class); if (builder.parameters.isEmpty()) { throw new IllegalStateException("All client methods must have an argument"); } List<ParameterSpec> parameters = new ArrayList<>(builder.parameters); String requestParameter = parameters.remove(0).name; String additionalParameters = String.format(", %s", parameters.stream().map(p -> p.name).collect(joining(", "))); builder.addStatement("return invokeOperation($N, request -> delegate.$N(request$N))", requestParameter, opModel.getMethodName(), parameters.isEmpty() ? "" : additionalParameters); return builder; } @Override protected MethodSpec.Builder utilitiesOperationBody(MethodSpec.Builder builder) { return builder.addAnnotation(Override.class).addStatement("return delegate.$N()", UtilitiesMethod.METHOD_NAME); } @Override protected MethodSpec.Builder waiterOperationBody(MethodSpec.Builder builder) { return builder.addAnnotation(Override.class).addStatement("return delegate.waiter()"); } }
3,472
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/client/AsyncClientClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PROTECTED; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static software.amazon.awssdk.codegen.internal.Constant.EVENT_PUBLISHER_PARAM_NAME; import static software.amazon.awssdk.codegen.poet.client.ClientClassUtils.addS3ArnableFieldCode; import static software.amazon.awssdk.codegen.poet.client.ClientClassUtils.applySignerOverrideMethod; import static software.amazon.awssdk.codegen.poet.client.SyncClientClass.getProtocolSpecs; 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.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import java.util.stream.Stream; import org.reactivestreams.Publisher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.AsyncAws4Signer; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.awscore.client.handler.AwsAsyncClientHandler; import software.amazon.awssdk.awscore.client.handler.AwsClientHandlerUtils; import software.amazon.awssdk.awscore.eventstream.EventStreamTaggedUnionJsonMarshaller; import software.amazon.awssdk.awscore.internal.AwsProtocolMetadata; import software.amazon.awssdk.awscore.internal.AwsServiceProtocol; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.model.config.customization.UtilitiesMethod; 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.AuthType; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.StaticImport; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeSpecUtils; import software.amazon.awssdk.codegen.poet.client.specs.ProtocolSpec; import software.amazon.awssdk.codegen.poet.eventstream.EventStreamUtils; import software.amazon.awssdk.codegen.poet.model.EventStreamSpecHelper; import software.amazon.awssdk.codegen.poet.model.ServiceClientConfigurationUtils; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.AsyncResponseTransformerUtils; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.client.handler.AsyncClientHandler; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryRefreshCache; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryRequest; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.metrics.NoOpMetricCollector; import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.FunctionalUtils; import software.amazon.awssdk.utils.Pair; public final class AsyncClientClass extends AsyncClientInterface { private final IntermediateModel model; private final PoetExtension poetExtensions; private final ClassName className; private final ProtocolSpec protocolSpec; private final ClassName serviceClientConfigurationClassName; private final ServiceClientConfigurationUtils configurationUtils; private final boolean useSraAuth; public AsyncClientClass(GeneratorTaskParams dependencies) { super(dependencies.getModel()); this.model = dependencies.getModel(); this.poetExtensions = dependencies.getPoetExtensions(); this.className = poetExtensions.getClientClass(model.getMetadata().getAsyncClient()); this.protocolSpec = getProtocolSpecs(poetExtensions, model); this.serviceClientConfigurationClassName = new PoetExtension(model).getServiceConfigClass(); this.useSraAuth = new AuthSchemeSpecUtils(model).useSraAuth(); this.configurationUtils = new ServiceClientConfigurationUtils(model); } @Override protected TypeSpec.Builder createTypeSpec() { return PoetUtils.createClassBuilder(className); } @Override protected void addInterfaceClass(TypeSpec.Builder type) { ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getAsyncInterface()); type.addSuperinterface(interfaceClass) .addJavadoc("Internal implementation of {@link $1T}.\n\n@see $1T#builder()", interfaceClass); } @Override protected void addAnnotations(TypeSpec.Builder type) { type.addAnnotation(SdkInternalApi.class); } @Override protected void addModifiers(TypeSpec.Builder type) { type.addModifiers(FINAL); } @Override protected void addFields(TypeSpec.Builder type) { type.addField(FieldSpec.builder(ClassName.get(Logger.class), "log") .addModifiers(PRIVATE, STATIC, FINAL) .initializer("$T.getLogger($T.class)", LoggerFactory.class, className) .build()) .addField(protocolMetadata()) .addField(AsyncClientHandler.class, "clientHandler", PRIVATE, FINAL) .addField(protocolSpec.protocolFactory(model)) .addField(SdkClientConfiguration.class, "clientConfiguration", PRIVATE, FINAL); // Kinesis doesn't support CBOR for STS yet so need another protocol factory for JSON if (model.getMetadata().isCborProtocol()) { type.addField(AwsJsonProtocolFactory.class, "jsonProtocolFactory", PRIVATE, FINAL); } model.getEndpointOperation().ifPresent( o -> type.addField(EndpointDiscoveryRefreshCache.class, "endpointDiscoveryCache", PRIVATE)); } @Override protected void addAdditionalMethods(TypeSpec.Builder type) { type.addMethod(constructor(type)) .addMethod(nameMethod()) .addMethods(protocolSpec.additionalMethods()) .addMethod(protocolSpec.initProtocolFactory(model)) .addMethod(resolveMetricPublishersMethod()); if (!useSraAuth) { if (model.containsRequestSigners() || model.containsRequestEventStreams() || hasStreamingV4AuthOperations()) { type.addMethod(applySignerOverrideMethod(poetExtensions, model)); type.addMethod(isSignerOverriddenOnClientMethod()); } } type.addMethod(updateSdkClientConfigurationMethod(configurationUtils.serviceClientConfigurationBuilderClassName())); protocolSpec.createErrorResponseHandler().ifPresent(type::addMethod); } @Override protected void addWaiterMethod(TypeSpec.Builder type) { type.addField(FieldSpec.builder(ClassName.get(ScheduledExecutorService.class), "executorService") .addModifiers(PRIVATE, FINAL) .build()); MethodSpec waiter = MethodSpec.methodBuilder("waiter") .addModifiers(PUBLIC) .addAnnotation(Override.class) .addStatement("return $T.builder().client(this)" + ".scheduledExecutorService(executorService).build()", poetExtensions.getAsyncWaiterInterface()) .returns(poetExtensions.getAsyncWaiterInterface()) .build(); type.addMethod(waiter); } @Override protected List<MethodSpec> operations() { return model.getOperations().values().stream() .flatMap(this::operations) .sorted(Comparator.comparing(m -> m.name)) .collect(toList()); } private Stream<MethodSpec> operations(OperationModel opModel) { List<MethodSpec> methods = new ArrayList<>(); methods.add(traditionalMethod(opModel)); return methods.stream(); } private FieldSpec protocolMetadata() { return FieldSpec.builder(AwsProtocolMetadata.class, "protocolMetadata", PRIVATE, STATIC, FINAL) .initializer("$T.builder().serviceProtocol($T.$L).build()", AwsProtocolMetadata.class, AwsServiceProtocol.class, model.getMetadata().getProtocol()) .build(); } private MethodSpec constructor(TypeSpec.Builder classBuilder) { MethodSpec.Builder builder = MethodSpec.constructorBuilder() .addModifiers(PROTECTED) .addParameter(SdkClientConfiguration.class, "clientConfiguration") .addStatement("this.clientHandler = new $T(clientConfiguration)", AwsAsyncClientHandler.class) .addStatement("this.clientConfiguration = clientConfiguration"); FieldSpec protocolFactoryField = protocolSpec.protocolFactory(model); if (model.getMetadata().isJsonProtocol()) { builder.addStatement("this.$N = init($T.builder()).build()", protocolFactoryField.name, protocolFactoryField.type); } else { builder.addStatement("this.$N = init()", protocolFactoryField.name); } if (model.getMetadata().isCborProtocol()) { builder.addStatement("this.jsonProtocolFactory = init($T.builder()).build()", AwsJsonProtocolFactory.class); } if (hasOperationWithEventStreamOutput()) { classBuilder.addField(FieldSpec.builder(ClassName.get(Executor.class), "executor", PRIVATE, FINAL) .build()); builder.addStatement("this.executor = clientConfiguration.option($T.FUTURE_COMPLETION_EXECUTOR)", SdkAdvancedAsyncClientOption.class); } if (model.getEndpointOperation().isPresent()) { builder.beginControlFlow("if (clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED))"); builder.addStatement("this.endpointDiscoveryCache = $T.create($T.create(this))", EndpointDiscoveryRefreshCache.class, poetExtensions.getClientClass(model.getNamingStrategy().getServiceName() + "AsyncEndpointDiscoveryCacheLoader")); if (model.getCustomizationConfig().allowEndpointOverrideForEndpointDiscoveryRequiredOperations()) { builder.beginControlFlow("if (clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN) == " + "Boolean.TRUE)"); builder.addStatement("log.warn($S)", "Endpoint discovery is enabled for this client, and an endpoint override was also " + "specified. This will disable endpoint discovery for methods that require it, instead " + "using the specified endpoint override. This may or may not be what you intended."); builder.endControlFlow(); } builder.endControlFlow(); } if (model.hasWaiters()) { builder.addStatement("this.executorService = clientConfiguration.option($T.SCHEDULED_EXECUTOR_SERVICE)", SdkClientOption.class); } return builder.build(); } private boolean hasOperationWithEventStreamOutput() { return model.getOperations().values().stream().anyMatch(OperationModel::hasEventStreamOutput); } private MethodSpec nameMethod() { return MethodSpec.methodBuilder("serviceName") .addAnnotation(Override.class) .addModifiers(PUBLIC, FINAL) .returns(String.class) .addStatement("return SERVICE_NAME") .build(); } @Override protected MethodSpec serviceClientConfigMethod() { return MethodSpec.methodBuilder("serviceClientConfiguration") .addAnnotation(Override.class) .addModifiers(PUBLIC, FINAL) .returns(serviceClientConfigurationClassName) .addStatement("return new $T(this.clientConfiguration.toBuilder()).build()", this.configurationUtils.serviceClientConfigurationBuilderClassName()) .build(); } protected static MethodSpec updateSdkClientConfigurationMethod( TypeName serviceClientConfigurationBuilderClassName) { MethodSpec.Builder builder = MethodSpec.methodBuilder("updateSdkClientConfiguration") .addModifiers(PRIVATE) .addParameter(SdkRequest.class, "request") .addParameter(SdkClientConfiguration.class, "clientConfiguration") .returns(SdkClientConfiguration.class); builder.addStatement("$T plugins = request.overrideConfiguration()\n" + ".map(c -> c.plugins()).orElse(Collections.emptyList())", ParameterizedTypeName.get(List.class, SdkPlugin.class)) .beginControlFlow("if (plugins.isEmpty())") .addStatement("return clientConfiguration") .endControlFlow() .addStatement("$T configuration = clientConfiguration.toBuilder()", SdkClientConfiguration.Builder.class) .addStatement("$1T serviceConfigBuilder = new $1T(configuration)", serviceClientConfigurationBuilderClassName) .beginControlFlow("for ($T plugin : plugins)", SdkPlugin.class) .addStatement("plugin.configureClient(serviceConfigBuilder)") .endControlFlow() .addStatement("return configuration.build()"); return builder.build(); } @Override protected void addCloseMethod(TypeSpec.Builder type) { MethodSpec method = MethodSpec.methodBuilder("close") .addAnnotation(Override.class) .addModifiers(PUBLIC) .addStatement("$N.close()", "clientHandler") .build(); type.addMethod(method); } @Override protected MethodSpec.Builder operationBody(MethodSpec.Builder builder, OperationModel opModel) { builder.addModifiers(PUBLIC) .addAnnotation(Override.class); builder.addStatement("$T clientConfiguration = updateSdkClientConfiguration($L, this.clientConfiguration)", SdkClientConfiguration.class, opModel.getInput().getVariableName()); builder.addStatement("$T<$T> metricPublishers = " + "resolveMetricPublishers(clientConfiguration, $N.overrideConfiguration().orElse(null))", List.class, MetricPublisher.class, opModel.getInput().getVariableName()) .addStatement("$1T apiCallMetricCollector = metricPublishers.isEmpty() ? $2T.create() : $1T.create($3S)", MetricCollector.class, NoOpMetricCollector.class, "ApiCall"); builder.beginControlFlow("try"); builder.addStatement("apiCallMetricCollector.reportMetric($T.$L, $S)", CoreMetric.class, "SERVICE_ID", model.getMetadata().getServiceId()); builder.addStatement("apiCallMetricCollector.reportMetric($T.$L, $S)", CoreMetric.class, "OPERATION_NAME", opModel.getOperationName()); if (opModel.hasStreamingOutput()) { ClassName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); builder.addStatement("$T<$T<$T, ReturnT>, $T<$T>> $N = $T.wrapWithEndOfStreamFuture($N)", Pair.class, AsyncResponseTransformer.class, responseType, CompletableFuture.class, Void.class, "pair", AsyncResponseTransformerUtils.class, "asyncResponseTransformer"); builder.addStatement("$N = $N.left()", "asyncResponseTransformer", "pair"); builder.addStatement("$T<$T> $N = $N.right()", CompletableFuture.class, Void.class, "endOfStreamFuture", "pair"); } if (!useSraAuth) { if (shouldUseAsyncWithBodySigner(opModel)) { builder.addCode(applyAsyncWithBodyV4SignerOverride(opModel)); } else { builder.addCode(ClientClassUtils.callApplySignerOverrideMethod(opModel)); } } builder.addCode(protocolSpec.responseHandler(model, opModel)); protocolSpec.errorResponseHandler(opModel).ifPresent(builder::addCode); builder.addCode(eventToByteBufferPublisher(opModel)); if (opModel.getEndpointDiscovery() != null) { builder.addStatement("boolean endpointDiscoveryEnabled = " + "clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED)"); builder.addStatement("boolean endpointOverridden = " + "clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN) == Boolean.TRUE"); if (opModel.getEndpointDiscovery().isRequired()) { if (!model.getCustomizationConfig().allowEndpointOverrideForEndpointDiscoveryRequiredOperations()) { builder.beginControlFlow("if (endpointOverridden)"); builder.addStatement("throw new $T($S)", IllegalStateException.class, "This operation requires endpoint discovery, but an endpoint override was specified " + "when the client was created. This is not supported."); builder.endControlFlow(); builder.beginControlFlow("if (!endpointDiscoveryEnabled)"); builder.addStatement("throw new $T($S)", IllegalStateException.class, "This operation requires endpoint discovery, but endpoint discovery was disabled on the " + "client."); builder.endControlFlow(); } else { builder.beginControlFlow("if (endpointOverridden)"); builder.addStatement("endpointDiscoveryEnabled = false"); builder.nextControlFlow("else if (!endpointDiscoveryEnabled)"); builder.addStatement("throw new $T($S)", IllegalStateException.class, "This operation requires endpoint discovery to be enabled, or for you to specify an " + "endpoint override when the client is created."); builder.endControlFlow(); } } builder.addStatement("$T<$T> endpointFuture = $T.completedFuture(null)", CompletableFuture.class, URI.class, CompletableFuture.class); builder.beginControlFlow("if (endpointDiscoveryEnabled)"); ParameterizedTypeName identityFutureTypeName = ParameterizedTypeName.get(ClassName.get(CompletableFuture.class), WildcardTypeName.subtypeOf(AwsCredentialsIdentity.class)); builder.addCode("$T identityFuture = $N.overrideConfiguration()", identityFutureTypeName, opModel.getInput().getVariableName()) .addCode(" .flatMap($T::credentialsIdentityProvider)", AwsRequestOverrideConfiguration.class) .addCode(" .orElseGet(() -> clientConfiguration.option($T.CREDENTIALS_IDENTITY_PROVIDER))", AwsClientOption.class) .addCode(" .resolveIdentity();"); builder.addCode("endpointFuture = identityFuture.thenApply(credentials -> {") .addCode(" $1T endpointDiscoveryRequest = $1T.builder()", EndpointDiscoveryRequest.class) .addCode(" .required($L)", opModel.getInputShape().getEndpointDiscovery().isRequired()) .addCode(" .defaultEndpoint(clientConfiguration.option($T.ENDPOINT))", SdkClientOption.class) .addCode(" .overrideConfiguration($N.overrideConfiguration().orElse(null))", opModel.getInput().getVariableName()) .addCode(" .build();") .addCode(" return endpointDiscoveryCache.get(credentials.accessKeyId(), endpointDiscoveryRequest);") .addCode("});"); builder.endControlFlow(); } addS3ArnableFieldCode(opModel, model).ifPresent(builder::addCode); builder.addCode(ClientClassUtils.addEndpointTraitCode(opModel)); builder.addCode(protocolSpec.asyncExecutionHandler(model, opModel)) .endControlFlow() .beginControlFlow("catch ($T t)", Throwable.class); // For streaming operations we also want to notify the response handler of any exception. if (opModel.hasStreamingOutput()) { ClassName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); builder.addStatement("$T<$T, ReturnT> finalAsyncResponseTransformer = asyncResponseTransformer", AsyncResponseTransformer.class, responseType); } if (opModel.hasStreamingOutput() || opModel.hasEventStreamOutput()) { String paramName = opModel.hasStreamingOutput() ? "finalAsyncResponseTransformer" : "asyncResponseHandler"; builder.addStatement("runAndLogError(log, \"Exception thrown in exceptionOccurred callback, ignoring\",\n" + "() -> $N.exceptionOccurred(t))", paramName); } builder.addStatement("metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()))") .addStatement("return $T.failedFuture(t)", CompletableFutureUtils.class) .endControlFlow(); return builder; } @Override public ClassName className() { return className; } @Override public Iterable<StaticImport> staticImports() { return singletonList(StaticImport.staticMethodImport(FunctionalUtils.class, "runAndLogError")); } private CodeBlock eventToByteBufferPublisher(OperationModel opModel) { if (!opModel.hasEventStreamInput()) { return CodeBlock.builder().build(); } ShapeModel eventStreamShape = EventStreamUtils.getEventStreamInRequest(opModel.getInputShape()); CodeBlock code = CodeBlock.builder() .add(createEventStreamTaggedUnionJsonMarshaller(eventStreamShape)) .addStatement("$1T eventPublisher = $2T.adapt($3L)", ParameterizedTypeName.get( ClassName.get(SdkPublisher.class), eventStreamType(eventStreamShape)), SdkPublisher.class, EVENT_PUBLISHER_PARAM_NAME) .add("$T adapted = eventPublisher.map(event -> eventMarshaller.marshall(event))", ParameterizedTypeName.get(Publisher.class, ByteBuffer.class)) .add(".map($T::encodeEventStreamRequestToByteBuffer);", AwsClientHandlerUtils.class) .build(); return code; } private CodeBlock createEventStreamTaggedUnionJsonMarshaller(ShapeModel eventStreamShape) { EventStreamSpecHelper specHelper = new EventStreamSpecHelper(eventStreamShape, model); CodeBlock.Builder builder = CodeBlock.builder().add("$1T eventMarshaller = $1T.builder()", EventStreamTaggedUnionJsonMarshaller.class); List<MemberModel> eventMembers = EventStreamUtils.getEventMembers(eventStreamShape) .collect(Collectors.toList()); eventMembers.forEach(event -> builder.add(".putMarshaller($T.class, new $T(protocolFactory))", specHelper.eventClassName(event), poetExtensions.getTransformClass(event.getShape() + "Marshaller"))); builder.add(".build();"); return builder.build(); } private TypeName eventStreamType(ShapeModel shapeModel) { return poetExtensions.getModelClass(shapeModel.getShapeName()); } @Override protected MethodSpec utilitiesMethod() { UtilitiesMethod config = model.getCustomizationConfig().getUtilitiesMethod(); ClassName returnType = PoetUtils.classNameFromFqcn(config.getReturnType()); String instanceClass = config.getInstanceType(); if (instanceClass == null) { instanceClass = config.getReturnType(); } ClassName instanceType = PoetUtils.classNameFromFqcn(instanceClass); return MethodSpec.methodBuilder(UtilitiesMethod.METHOD_NAME) .returns(returnType) .addModifiers(PUBLIC) .addAnnotation(Override.class) .addStatement("return $T.create($L)", instanceType, String.join(",", config.getCreateMethodParams())) .build(); } private MethodSpec resolveMetricPublishersMethod() { String clientConfigName = "clientConfiguration"; String requestOverrideConfigName = "requestOverrideConfiguration"; MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("resolveMetricPublishers") .addModifiers(PRIVATE, STATIC) .returns(ParameterizedTypeName.get(List.class, MetricPublisher.class)) .addParameter(SdkClientConfiguration.class, clientConfigName) .addParameter(RequestOverrideConfiguration.class, requestOverrideConfigName); String publishersName = "publishers"; methodBuilder.addStatement("$T $N = null", ParameterizedTypeName.get(List.class, MetricPublisher.class), publishersName); methodBuilder.beginControlFlow("if ($N != null)", requestOverrideConfigName) .addStatement("$N = $N.metricPublishers()", publishersName, requestOverrideConfigName) .endControlFlow(); methodBuilder.beginControlFlow("if ($1N == null || $1N.isEmpty())", publishersName) .addStatement("$N = $N.option($T.$N)", publishersName, clientConfigName, SdkClientOption.class, "METRIC_PUBLISHERS") .endControlFlow(); methodBuilder.beginControlFlow("if ($1N == null)", publishersName) .addStatement("$N = $T.emptyList()", publishersName, Collections.class) .endControlFlow(); methodBuilder.addStatement("return $N", publishersName); return methodBuilder.build(); } private boolean shouldUseAsyncWithBodySigner(OperationModel opModel) { if (opModel.getInputShape().getRequestSignerClassFqcn() != null) { return false; } AuthType authTypeForOperation = opModel.getAuthType(); if (authTypeForOperation == null) { authTypeForOperation = model.getMetadata().getAuthType(); } return authTypeForOperation == AuthType.V4 && opModel.hasStreamingInput(); } private CodeBlock applyAsyncWithBodyV4SignerOverride(OperationModel opModel) { return CodeBlock.builder() .beginControlFlow("if (!isSignerOverridden($N))", "clientConfiguration") .addStatement("$1L = applySignerOverride($1L, $2T.create())", opModel.getInput().getVariableName(), AsyncAws4Signer.class) .endControlFlow() .build(); } private MethodSpec isSignerOverriddenOnClientMethod() { String clientConfigurationName = "clientConfiguration"; return MethodSpec.methodBuilder("isSignerOverridden") .returns(boolean.class) .addModifiers(PRIVATE, STATIC) .addParameter(SdkClientConfiguration.class, clientConfigurationName) .addStatement("return $T.TRUE.equals($N.option($T.$N))", Boolean.class, clientConfigurationName, SdkClientOption.class, "SIGNER_OVERRIDDEN") .build(); } private boolean hasStreamingV4AuthOperations() { return model.getOperations().values().stream() .anyMatch(this::shouldUseAsyncWithBodySigner); } }
3,473
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/client/DelegatingSyncClientClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static javax.lang.model.element.Modifier.ABSTRACT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PROTECTED; import static javax.lang.model.element.Modifier.PUBLIC; import static software.amazon.awssdk.codegen.poet.client.AsyncClientInterface.STREAMING_TYPE_VARIABLE; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.Function; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.codegen.docs.SimpleMethodOverload; import software.amazon.awssdk.codegen.model.config.customization.UtilitiesMethod; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.core.SdkClient; import software.amazon.awssdk.utils.Validate; public class DelegatingSyncClientClass extends SyncClientInterface { private final IntermediateModel model; private final ClassName className; private final PoetExtension poetExtensions; public DelegatingSyncClientClass(IntermediateModel model) { super(model); this.model = model; this.className = ClassName.get(model.getMetadata().getFullClientPackageName(), "Delegating" + model.getMetadata().getSyncInterface()); this.poetExtensions = new PoetExtension(model); } @Override protected void addInterfaceClass(TypeSpec.Builder type) { ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getSyncInterface()); type.addSuperinterface(interfaceClass) .addMethod(constructor(interfaceClass)); } @Override protected TypeSpec.Builder createTypeSpec() { return PoetUtils.createClassBuilder(className); } @Override protected void addAnnotations(TypeSpec.Builder type) { type.addAnnotation(SdkPublicApi.class); } @Override protected void addModifiers(TypeSpec.Builder type) { type.addModifiers(ABSTRACT, PUBLIC); } @Override protected void addFields(TypeSpec.Builder type) { ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getSyncInterface()); type.addField(FieldSpec.builder(interfaceClass, "delegate") .addModifiers(PRIVATE, FINAL) .build()); } @Override protected void addConsumerMethod(List<MethodSpec> specs, MethodSpec spec, SimpleMethodOverload overload, OperationModel opModel) { } @Override protected void addAdditionalMethods(TypeSpec.Builder type) { type.addMethod(nameMethod()) .addMethod(delegateMethod()) .addMethod(invokeMethod()); } @Override protected void addCloseMethod(TypeSpec.Builder type) { MethodSpec method = MethodSpec.methodBuilder("close") .addAnnotation(Override.class) .addModifiers(PUBLIC) .addStatement("delegate.close()") .build(); type.addMethod(method); } @Override protected List<MethodSpec> operations() { return model.getOperations().values().stream() // TODO Sync not supported for event streaming yet. Revisit after sync/async merge .filter(o -> !o.hasEventStreamInput()) .filter(o -> !o.hasEventStreamOutput()) .flatMap(this::operations) .sorted(Comparator.comparing(m -> m.name)) .collect(toList()); } private Stream<MethodSpec> operations(OperationModel opModel) { List<MethodSpec> methods = new ArrayList<>(); methods.add(traditionalMethod(opModel)); return methods.stream(); } @Override public ClassName className() { return className; } @Override protected MethodSpec.Builder simpleMethodModifier(MethodSpec.Builder builder) { return builder.addAnnotation(Override.class); } protected MethodSpec traditionalMethod(OperationModel opModel) { MethodSpec.Builder builder = operationMethodSignature(model, opModel); return operationBody(builder, opModel).build(); } @Override protected MethodSpec.Builder operationBody(MethodSpec.Builder builder, OperationModel opModel) { builder.addModifiers(PUBLIC) .addAnnotation(Override.class); if (builder.parameters.isEmpty()) { throw new IllegalStateException("All client methods must have an argument"); } List<ParameterSpec> operationParameters = new ArrayList<>(builder.parameters); String requestParameter = operationParameters.remove(0).name; String additionalParameters = String.format(", %s", operationParameters.stream().map(p -> p.name).collect(joining(", "))); builder.addStatement("return invokeOperation($N, request -> delegate.$N(request$N))", requestParameter, opModel.getMethodName(), operationParameters.isEmpty() ? "" : additionalParameters); return builder; } @Override protected MethodSpec.Builder utilitiesOperationBody(MethodSpec.Builder builder) { return builder.addAnnotation(Override.class).addStatement("return delegate.$N()", UtilitiesMethod.METHOD_NAME); } @Override protected MethodSpec.Builder waiterOperationBody(MethodSpec.Builder builder) { return builder.addAnnotation(Override.class).addStatement("return delegate.waiter()"); } private MethodSpec constructor(ClassName interfaceClass) { return MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addParameter(interfaceClass, "delegate") .addStatement("$T.paramNotNull(delegate, \"delegate\")", Validate.class) .addStatement("this.delegate = delegate") .build(); } private MethodSpec nameMethod() { return MethodSpec.methodBuilder("serviceName") .addAnnotation(Override.class) .addModifiers(PUBLIC, FINAL) .returns(String.class) .addStatement("return delegate.serviceName()") .build(); } private MethodSpec delegateMethod() { return MethodSpec.methodBuilder("delegate") .addModifiers(PUBLIC) .addStatement("return this.delegate") .returns(SdkClient.class) .build(); } private MethodSpec invokeMethod() { TypeVariableName requestTypeVariableName = TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName())); TypeVariableName responseTypeVariableName = STREAMING_TYPE_VARIABLE; ParameterizedTypeName functionTypeName = ParameterizedTypeName .get(ClassName.get(Function.class), requestTypeVariableName, responseTypeVariableName); return MethodSpec.methodBuilder("invokeOperation") .addModifiers(PROTECTED) .addParameter(requestTypeVariableName, "request") .addParameter(functionTypeName, "operation") .addTypeVariable(requestTypeVariableName) .addTypeVariable(responseTypeVariableName) .returns(responseTypeVariableName) .addStatement("return operation.apply(request)") .build(); } @Override protected MethodSpec serviceClientConfigMethod() { return MethodSpec.methodBuilder("serviceClientConfiguration") .addAnnotation(Override.class) .addModifiers(PUBLIC, FINAL) .returns(new PoetExtension(model).getServiceConfigClass()) .addStatement("return delegate.serviceClientConfiguration()") .build(); } }
3,474
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/client/AsyncClientInterface.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.stream.Collectors.toList; import static javax.lang.model.element.Modifier.DEFAULT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static software.amazon.awssdk.codegen.internal.Constant.ASYNC_STREAMING_INPUT_PARAM; import static software.amazon.awssdk.codegen.internal.Constant.EVENT_PUBLISHER_PARAM_NAME; import static software.amazon.awssdk.codegen.internal.Constant.EVENT_RESPONSE_HANDLER_PARAM_NAME; 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 com.squareup.javapoet.TypeVariableName; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.awscore.AwsClient; import software.amazon.awssdk.codegen.docs.ClientType; import software.amazon.awssdk.codegen.docs.DocConfiguration; import software.amazon.awssdk.codegen.docs.SimpleMethodOverload; import software.amazon.awssdk.codegen.docs.WaiterDocs; import software.amazon.awssdk.codegen.model.config.customization.AdditionalBuilderMethod; import software.amazon.awssdk.codegen.model.config.customization.UtilitiesMethod; 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; import software.amazon.awssdk.codegen.poet.eventstream.EventStreamUtils; import software.amazon.awssdk.codegen.poet.model.DeprecationUtils; import software.amazon.awssdk.codegen.utils.PaginatorUtils; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.regions.ServiceMetadataProvider; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.utils.Validate; public class AsyncClientInterface implements ClassSpec { public static final TypeVariableName STREAMING_TYPE_VARIABLE = TypeVariableName.get("ReturnT"); protected final IntermediateModel model; protected final ClassName className; protected final String clientPackageName; private final String modelPackage; private final PoetExtension poetExtensions; public AsyncClientInterface(IntermediateModel model) { this.modelPackage = model.getMetadata().getFullModelPackageName(); this.clientPackageName = model.getMetadata().getFullClientPackageName(); this.model = model; this.className = ClassName.get(model.getMetadata().getFullClientPackageName(), model.getMetadata().getAsyncInterface()); this.poetExtensions = new PoetExtension(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder result = createTypeSpec(); addInterfaceClass(result); addAnnotations(result); addModifiers(result); addFields(result); if (model.getCustomizationConfig().getUtilitiesMethod() != null) { result.addMethod(utilitiesMethod()); } result.addMethods(operations()); if (model.hasWaiters()) { addWaiterMethod(result); } result.addMethod(serviceClientConfigMethod()); addAdditionalMethods(result); addCloseMethod(result); return result.build(); } protected TypeSpec.Builder createTypeSpec() { return PoetUtils.createInterfaceBuilder(className); } protected void addInterfaceClass(TypeSpec.Builder type) { type.addSuperinterface(AwsClient.class); } protected void addAnnotations(TypeSpec.Builder type) { type.addAnnotation(SdkPublicApi.class) .addAnnotation(ThreadSafe.class); } protected void addModifiers(TypeSpec.Builder type) { } protected void addCloseMethod(TypeSpec.Builder type) { } protected void addFields(TypeSpec.Builder type) { type.addField(FieldSpec.builder(String.class, "SERVICE_NAME") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$S", model.getMetadata().getSigningName()) .build()) .addField(FieldSpec.builder(String.class, "SERVICE_METADATA_ID") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$S", model.getMetadata().getEndpointPrefix()) .addJavadoc("Value for looking up the service's metadata from the {@link $T}.", ServiceMetadataProvider.class) .build()); } protected void addAdditionalMethods(TypeSpec.Builder type) { if (!model.getCustomizationConfig().isExcludeClientCreateMethod()) { type.addMethod(create()); } type.addMethod(builder()); List<AdditionalBuilderMethod> additionaBuilders = model.getCustomizationConfig().getAdditionalBuilderMethods(); if (additionaBuilders != null && !additionaBuilders.isEmpty()) { additionaBuilders.stream() .filter(builder -> software.amazon.awssdk.core.ClientType.ASYNC.equals(builder.getClientTypeEnum())) .forEach(builders -> type.addMethod(additionalBuilders(builders))); } PoetUtils.addJavadoc(type::addJavadoc, getJavadoc()); } protected void addWaiterMethod(TypeSpec.Builder type) { MethodSpec.Builder builder = MethodSpec.methodBuilder("waiter") .addModifiers(PUBLIC) .returns(poetExtensions.getAsyncWaiterInterface()) .addJavadoc(WaiterDocs.waiterMethodInClient( poetExtensions.getAsyncWaiterInterface())); type.addMethod(waiterOperationBody(builder).build()); } @Override public ClassName className() { return className; } private String getJavadoc() { return "Service client for accessing " + model.getMetadata().getDescriptiveServiceName() + " asynchronously. This can be " + "created using the static {@link #builder()} method.\n\n" + model.getMetadata().getDocumentation(); } private MethodSpec create() { return MethodSpec.methodBuilder("create") .returns(className) .addModifiers(STATIC, PUBLIC) .addJavadoc("Create a {@link $T} with the region loaded from the {@link $T} and credentials loaded " + "from the {@link $T}.", className, DefaultAwsRegionProviderChain.class, DefaultCredentialsProvider.class) .addStatement("return builder().build()") .build(); } private MethodSpec builder() { ClassName builderClass = ClassName.get(clientPackageName, model.getMetadata().getAsyncBuilder()); ClassName builderInterface = ClassName.get(clientPackageName, model.getMetadata().getAsyncBuilderInterface()); return MethodSpec.methodBuilder("builder") .returns(builderInterface) .addModifiers(STATIC, PUBLIC) .addJavadoc("Create a builder that can be used to configure and create a {@link $T}.", className) .addStatement("return new $T()", builderClass) .build(); } /** * @return List generated of methods for all operations. */ protected Iterable<MethodSpec> operations() { return model.getOperations().values().stream() .flatMap(this::operationsWithVariants) .sorted(Comparator.comparing(m -> m.name)) .collect(toList()); } private Stream<MethodSpec> operationsWithVariants(OperationModel operationModel) { List<MethodSpec> methods = new ArrayList<>(); methods.addAll(traditionalMethodWithConsumerVariant(operationModel)); methods.addAll(overloadedMethods(operationModel)); methods.addAll(paginatedMethods(operationModel)); return methods.stream() // Add Deprecated annotation if needed to all overloads .map(m -> DeprecationUtils.checkDeprecated(operationModel, m)); } /** * Generates the traditional method for an operation (i.e. one that takes a request and returns a response). */ private List<MethodSpec> traditionalMethodWithConsumerVariant(OperationModel opModel) { List<MethodSpec> methods = new ArrayList<>(); String consumerBuilderJavadoc = consumerBuilderJavadoc(opModel, SimpleMethodOverload.NORMAL); methods.add(traditionalMethod(opModel)); methods.add(ClientClassUtils.consumerBuilderVariant(methods.get(0), consumerBuilderJavadoc)); return methods; } private List<MethodSpec> paginatedMethods(OperationModel opModel) { List<MethodSpec> methods = new ArrayList<>(); if (opModel.isPaginated()) { if (opModel.getInputShape().isSimpleMethod()) { methods.add(paginatedSimpleMethod(opModel)); } MethodSpec paginatedMethod = paginatedTraditionalMethod(opModel); methods.add(paginatedMethod); String consumerBuilderJavadoc = consumerBuilderJavadoc(opModel, SimpleMethodOverload.PAGINATED); methods.add(ClientClassUtils.consumerBuilderVariant(paginatedMethod, consumerBuilderJavadoc)); } return methods; } protected MethodSpec paginatedTraditionalMethod(OperationModel opModel) { String methodName = PaginatorUtils.getPaginatedMethodName(opModel.getMethodName()); ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType()); ClassName responsePojoType = poetExtensions.getResponseClassForPaginatedAsyncOperation(opModel.getOperationName()); MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName) .returns(responsePojoType) .addParameter(requestType, opModel.getInput().getVariableName()) .addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.PAGINATED)); return paginatedMethodBody(builder, opModel).build(); } protected MethodSpec.Builder paginatedMethodBody(MethodSpec.Builder builder, OperationModel operationModel) { return builder.addModifiers(DEFAULT, PUBLIC) .addStatement("return new $T(this, $L)", poetExtensions.getResponseClassForPaginatedAsyncOperation(operationModel.getOperationName()), operationModel.getInput().getVariableName()); } private MethodSpec paginatedSimpleMethod(OperationModel opModel) { String methodName = PaginatorUtils.getPaginatedMethodName(opModel.getMethodName()); ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType()); ClassName responsePojoType = poetExtensions.getResponseClassForPaginatedAsyncOperation(opModel.getOperationName()); MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName) .addModifiers(DEFAULT, PUBLIC) .returns(responsePojoType) .addStatement("return $L($T.builder().build())", methodName, requestType) .addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.NO_ARG_PAGINATED)); return builder.build(); } /** * @param opModel Operation to generate simple methods for. * @return All simple method overloads for a given operation. */ private List<MethodSpec> overloadedMethods(OperationModel opModel) { String consumerBuilderFileJavadoc = consumerBuilderJavadoc(opModel, SimpleMethodOverload.FILE); List<MethodSpec> methodOverloads = new ArrayList<>(); if (opModel.getInputShape().isSimpleMethod()) { methodOverloads.add(noArgSimpleMethod(opModel)); } if (opModel.hasStreamingInput() && opModel.hasStreamingOutput()) { MethodSpec streamingMethod = streamingInputOutputFileSimpleMethod(opModel); methodOverloads.add(streamingMethod); methodOverloads.add(ClientClassUtils.consumerBuilderVariant(streamingMethod, consumerBuilderFileJavadoc)); } else if (opModel.hasStreamingInput()) { MethodSpec streamingInputMethod = streamingInputFileSimpleMethod(opModel); methodOverloads.add(streamingInputMethod); methodOverloads.add(ClientClassUtils.consumerBuilderVariant(streamingInputMethod, consumerBuilderFileJavadoc)); } else if (opModel.hasStreamingOutput()) { MethodSpec streamingOutputMethod = streamingOutputFileSimpleMethod(opModel); methodOverloads.add(streamingOutputMethod); methodOverloads.add(ClientClassUtils.consumerBuilderVariant(streamingOutputMethod, consumerBuilderFileJavadoc)); } return methodOverloads; } /** * Add the implementation body. The interface implements all methods by throwing an {@link UnsupportedOperationException} * except for simple method overloads which just delegate to the traditional request/response method. This is overridden * in {@link AsyncClientClass} to add an actual implementation. * * @param builder Current {@link com.squareup.javapoet.MethodSpec.Builder} to add implementation to. * @param operationModel Operation to generate method body for. * @return Builder with method body added. */ protected MethodSpec.Builder operationBody(MethodSpec.Builder builder, OperationModel operationModel) { return builder.addModifiers(DEFAULT, PUBLIC) .addStatement("throw new $T()", UnsupportedOperationException.class); } protected MethodSpec traditionalMethod(OperationModel opModel) { ClassName responsePojoType = getPojoResponseType(opModel); ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType()); MethodSpec.Builder builder = methodSignatureWithReturnType(opModel) .addParameter(requestType, opModel.getInput().getVariableName()) .addJavadoc(opModel.getDocs(model, ClientType.ASYNC)); if (opModel.hasStreamingInput()) { builder.addParameter(ClassName.get(AsyncRequestBody.class), ASYNC_STREAMING_INPUT_PARAM); } else if (opModel.hasEventStreamInput()) { String eventStreamShapeName = EventStreamUtils.getEventStreamInRequest(opModel.getInputShape()) .getShapeName(); ClassName shapeClass = ClassName.get(modelPackage, eventStreamShapeName); ParameterizedTypeName requestPublisher = ParameterizedTypeName.get(ClassName.get(Publisher.class), shapeClass); builder.addParameter(requestPublisher, EVENT_PUBLISHER_PARAM_NAME); } if (opModel.hasStreamingOutput()) { builder.addTypeVariable(STREAMING_TYPE_VARIABLE); ParameterizedTypeName asyncResponseHandlerType = ParameterizedTypeName .get(ClassName.get(AsyncResponseTransformer.class), responsePojoType, STREAMING_TYPE_VARIABLE); builder.addParameter(asyncResponseHandlerType, "asyncResponseTransformer"); } else if (opModel.hasEventStreamOutput()) { builder.addParameter(poetExtensions.eventStreamResponseHandlerType(opModel), EVENT_RESPONSE_HANDLER_PARAM_NAME); } return operationBody(builder, opModel).build(); } /** * Generate a simple method that takes no arguments for operations with no required parameters. */ private MethodSpec noArgSimpleMethod(OperationModel opModel) { return interfaceMethodSignature(opModel) .addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.NO_ARG)) .addStatement("return $N($N.builder().build())", opModel.getMethodName(), opModel.getInput().getVariableType()) .build(); } /** * Generate a simple method for operations with a streaming input member that takes a {@link Path} containing the data * to upload. */ private MethodSpec streamingInputFileSimpleMethod(OperationModel opModel) { ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType()); return interfaceMethodSignature(opModel) .addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.FILE)) .addParameter(requestType, opModel.getInput().getVariableName()) .addParameter(ClassName.get(Path.class), "sourcePath") .addStatement("return $L($L, $T.fromFile(sourcePath))", opModel.getMethodName(), opModel.getInput().getVariableName(), ClassName.get(AsyncRequestBody.class)) .build(); } /** * Generate a simple method for operations with a streaming output member that takes a {@link Path} where data * will be downloaded to. */ private MethodSpec streamingOutputFileSimpleMethod(OperationModel opModel) { ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType()); return interfaceMethodSignature(opModel) .returns(completableFutureType(getPojoResponseType(opModel))) .addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.FILE)) .addParameter(requestType, opModel.getInput().getVariableName()) .addParameter(ClassName.get(Path.class), "destinationPath") .addStatement("return $L($L, $T.toFile(destinationPath))", opModel.getMethodName(), opModel.getInput().getVariableName(), ClassName.get(AsyncResponseTransformer.class)) .build(); } /** * Generate a simple method for operations with streaming input and output members. * Streaming input member takes a {@link Path} containing the data to upload and * the streaming output member takes a {@link Path} where data will be downloaded to. */ private MethodSpec streamingInputOutputFileSimpleMethod(OperationModel opModel) { ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType()); return interfaceMethodSignature(opModel) .returns(completableFutureType(getPojoResponseType(opModel))) .addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.FILE)) .addParameter(requestType, opModel.getInput().getVariableName()) .addParameter(ClassName.get(Path.class), "sourcePath") .addParameter(ClassName.get(Path.class), "destinationPath") .addStatement("return $L($L, $T.fromFile(sourcePath), $T.toFile(destinationPath))", opModel.getMethodName(), opModel.getInput().getVariableName(), ClassName.get(AsyncRequestBody.class), ClassName.get(AsyncResponseTransformer.class)) .build(); } /** * Factory method for creating a {@link com.squareup.javapoet.MethodSpec.Builder} with correct return type. * * @return MethodSpec with only return type set. */ private MethodSpec.Builder methodSignatureWithReturnType(OperationModel opModel) { ClassName responsePojoType = getPojoResponseType(opModel); return MethodSpec.methodBuilder(opModel.getMethodName()) .returns(getAsyncReturnType(opModel, responsePojoType)); } /** * Factory method for creating a {@link com.squareup.javapoet.MethodSpec.Builder} with * correct return type and public/default modifiers for use in interfaces. * * @return MethodSpec with public/default modifiers for interface file. */ private MethodSpec.Builder interfaceMethodSignature(OperationModel opModel) { return methodSignatureWithReturnType(opModel) .addModifiers(PUBLIC, DEFAULT); } /** * @return ClassName for POJO response class. */ private ClassName getPojoResponseType(OperationModel opModel) { return ClassName.get(modelPackage, opModel.getReturnType().getReturnType()); } /** * Get the return {@link TypeName} of an async method. Depends on whether it's streaming or not. * * @param opModel Operation to get return type for. * @param responsePojoType Type of Response POJO. * @return Return type of the operation method. */ private TypeName getAsyncReturnType(OperationModel opModel, ClassName responsePojoType) { if (opModel.hasStreamingOutput()) { return completableFutureType(STREAMING_TYPE_VARIABLE); } else if (opModel.hasEventStreamOutput()) { // Event streaming doesn't support transforming into a result type so it just returns void. return completableFutureType(ClassName.get(Void.class)); } else { return completableFutureType(responsePojoType); } } /** * Returns a {@link ParameterizedTypeName} of {@link CompletableFuture} with the given typeName as the type parameter. */ private ParameterizedTypeName completableFutureType(TypeName typeName) { return ParameterizedTypeName.get(ClassName.get(CompletableFuture.class), typeName); } private String consumerBuilderJavadoc(OperationModel opModel, SimpleMethodOverload overload) { return opModel.getDocs(model, ClientType.ASYNC, overload, new DocConfiguration().isConsumerBuilder(true)); } protected MethodSpec utilitiesMethod() { UtilitiesMethod config = model.getCustomizationConfig().getUtilitiesMethod(); ClassName returnType = PoetUtils.classNameFromFqcn(config.getReturnType()); MethodSpec.Builder builder = MethodSpec.methodBuilder(UtilitiesMethod.METHOD_NAME) .returns(returnType) .addModifiers(PUBLIC) .addJavadoc("Creates an instance of {@link $T} object with the " + "configuration set on this client.", returnType); return utilitiesOperationBody(builder).build(); } protected MethodSpec serviceClientConfigMethod() { return MethodSpec.methodBuilder("serviceClientConfiguration") .addAnnotation(Override.class) .addModifiers(PUBLIC, DEFAULT) .addStatement("throw new $T()", UnsupportedOperationException.class) .returns(new PoetExtension(model).getServiceConfigClass()) .build(); } private MethodSpec additionalBuilders(AdditionalBuilderMethod additionalMethod) { String methodName = Validate.paramNotNull(additionalMethod.getMethodName(), "methodName"); ClassName returnType = PoetUtils.classNameFromFqcn( Validate.paramNotNull(additionalMethod.getReturnType(), "returnType")); ClassName instanceType = PoetUtils.classNameFromFqcn( Validate.paramNotNull(additionalMethod.getInstanceType(), "instanceType")); MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName) .returns(returnType) .addModifiers(STATIC, PUBLIC) .addJavadoc(additionalMethod.getJavaDoc()) .addStatement("return $T.$L", instanceType, additionalMethod.getStatement()); return builder.build(); } protected MethodSpec.Builder utilitiesOperationBody(MethodSpec.Builder builder) { return builder.addModifiers(DEFAULT).addStatement("throw new $T()", UnsupportedOperationException.class); } protected MethodSpec.Builder waiterOperationBody(MethodSpec.Builder builder) { return builder.addModifiers(DEFAULT, PUBLIC) .addStatement("throw new $T()", UnsupportedOperationException.class); } }
3,475
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/client/ClientClassUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.codegen.poet.PoetUtils.classNameFromFqcn; 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.TypeName; import com.squareup.javapoet.TypeVariableName; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.lang.model.element.Modifier; import software.amazon.awssdk.arns.Arn; import software.amazon.awssdk.auth.signer.EventStreamAws4Signer; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.codegen.model.config.customization.S3ArnableFieldConfig; 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.HostPrefixProcessor; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.utils.HostnameValidator; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; final class ClientClassUtils { private ClientClassUtils() { } static MethodSpec consumerBuilderVariant(MethodSpec spec, String javadoc) { Validate.validState(spec.parameters.size() > 0, "A first parameter is required to generate a consumer-builder method."); Validate.validState(spec.parameters.get(0).type instanceof ClassName, "The first parameter must be a class."); ParameterSpec firstParameter = spec.parameters.get(0); ClassName firstParameterClass = (ClassName) firstParameter.type; TypeName consumer = ParameterizedTypeName.get(ClassName.get(Consumer.class), firstParameterClass.nestedClass("Builder")); MethodSpec.Builder result = MethodSpec.methodBuilder(spec.name) .returns(spec.returnType) .addExceptions(spec.exceptions) .addAnnotations(spec.annotations) .addJavadoc(javadoc) .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) .addTypeVariables(spec.typeVariables) .addParameter(ParameterSpec.builder(consumer, firstParameter.name).build()); // Parameters StringBuilder methodBody = new StringBuilder("return $L($T.builder().applyMutation($L).build()"); for (int i = 1; i < spec.parameters.size(); i++) { ParameterSpec parameter = spec.parameters.get(i); methodBody.append(", ").append(parameter.name); result.addParameter(parameter); } methodBody.append(")"); result.addStatement(methodBody.toString(), spec.name, firstParameterClass, firstParameter.name); return result.build(); } static MethodSpec applySignerOverrideMethod(PoetExtension poetExtensions, IntermediateModel model) { String signerOverrideVariable = "signerOverride"; TypeVariableName typeVariableName = TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName())); ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName .get(ClassName.get(Consumer.class), ClassName.get(AwsRequestOverrideConfiguration.Builder.class)); CodeBlock codeBlock = CodeBlock.builder() .beginControlFlow("if (request.overrideConfiguration().flatMap(c -> c.signer())" + ".isPresent())") .addStatement("return request") .endControlFlow() .addStatement("$T $L = b -> b.signer(signer).build()", parameterizedTypeName, signerOverrideVariable) .addStatement("$1T overrideConfiguration =\n" + " request.overrideConfiguration().map(c -> c.toBuilder()" + ".applyMutation($2L).build())\n" + " .orElse((AwsRequestOverrideConfiguration.builder()" + ".applyMutation($2L).build()))", AwsRequestOverrideConfiguration.class, signerOverrideVariable) .addStatement("return (T) request.toBuilder().overrideConfiguration" + "(overrideConfiguration).build()") .build(); return MethodSpec.methodBuilder("applySignerOverride") .addModifiers(Modifier.PRIVATE) .addParameter(typeVariableName, "request") .addParameter(Signer.class, "signer") .addTypeVariable(typeVariableName) .addCode(codeBlock) .returns(typeVariableName) .build(); } static CodeBlock callApplySignerOverrideMethod(OperationModel opModel) { CodeBlock.Builder code = CodeBlock.builder(); ShapeModel inputShape = opModel.getInputShape(); if (inputShape.getRequestSignerClassFqcn() != null) { code.addStatement("$1L = applySignerOverride($1L, $2T.create())", opModel.getInput().getVariableName(), PoetUtils.classNameFromFqcn(inputShape.getRequestSignerClassFqcn())); } else if (opModel.hasEventStreamInput()) { code.addStatement("$1L = applySignerOverride($1L, $2T.create())", opModel.getInput().getVariableName(), EventStreamAws4Signer.class); } return code.build(); } static CodeBlock addEndpointTraitCode(OperationModel opModel) { CodeBlock.Builder builder = CodeBlock.builder(); if (opModel.getEndpointTrait() != null && !StringUtils.isEmpty(opModel.getEndpointTrait().getHostPrefix())) { String hostPrefix = opModel.getEndpointTrait().getHostPrefix(); HostPrefixProcessor processor = new HostPrefixProcessor(hostPrefix); builder.addStatement("String hostPrefix = $S", hostPrefix); if (processor.c2jNames().isEmpty()) { builder.addStatement("String resolvedHostExpression = $S", processor.hostWithStringSpecifier()); } else { processor.c2jNames() .forEach(name -> builder.addStatement("$T.validateHostnameCompliant($L, $S, $S)", HostnameValidator.class, inputShapeMemberGetter(opModel, name), name, opModel.getInput().getVariableName())); builder.addStatement("String resolvedHostExpression = String.format($S, $L)", processor.hostWithStringSpecifier(), processor.c2jNames().stream() .map(n -> inputShapeMemberGetter(opModel, n)) .collect(Collectors.joining(","))); } } return builder.build(); } static Optional<CodeBlock> addS3ArnableFieldCode(OperationModel opModel, IntermediateModel model) { CodeBlock.Builder builder = CodeBlock.builder(); Map<String, S3ArnableFieldConfig> s3ArnableFields = model.getCustomizationConfig().getS3ArnableFields(); if (s3ArnableFields != null && s3ArnableFields.containsKey(opModel.getInputShape().getShapeName())) { S3ArnableFieldConfig s3ArnableField = s3ArnableFields.get(opModel.getInputShape().getShapeName()); String fieldName = s3ArnableField.getField(); MemberModel arnableMember = opModel.getInputShape().tryFindMemberModelByC2jName(fieldName, true); ClassName arnResourceFqcn = classNameFromFqcn(s3ArnableField.getArnResourceFqcn()); builder.addStatement("String $N = $N.$N()", fieldName, opModel.getInput().getVariableName(), arnableMember.getFluentGetterMethodName()); builder.addStatement("$T arn = null", Arn.class); builder.beginControlFlow("if ($N != null && $N.startsWith(\"arn:\"))", fieldName, fieldName) .addStatement("arn = $T.fromString($N)", Arn.class, fieldName) .addStatement("$T s3Resource = $T.getInstance().convertArn(arn)", classNameFromFqcn(s3ArnableField.getBaseArnResourceFqcn()), classNameFromFqcn(s3ArnableField.getArnConverterFqcn())) .beginControlFlow("if (!(s3Resource instanceof $T))", arnResourceFqcn) .addStatement("throw new $T(String.format(\"Unsupported ARN type: %s\", s3Resource.type()))", IllegalArgumentException.class) .endControlFlow() .addStatement("$T resource = ($T) s3Resource", arnResourceFqcn, arnResourceFqcn); Map<String, String> otherFieldsToPopulate = s3ArnableField.getOtherFieldsToPopulate(); for (Map.Entry<String, String> entry : otherFieldsToPopulate.entrySet()) { MemberModel memberModel = opModel.getInputShape().tryFindMemberModelByC2jName(entry.getKey(), true); String variableName = memberModel.getVariable().getVariableName(); String arnVariableName = variableName + "InArn"; builder.addStatement("String $N = $N.$N()", variableName, opModel.getInput().getVariableName(), memberModel.getFluentGetterMethodName()); builder.addStatement("String $N = resource.$N", arnVariableName, entry.getValue()); builder.beginControlFlow("if ($N != null && !$N.equals($N))", variableName, variableName, arnVariableName) .addStatement("throw new $T(String.format(\"%s field provided from the request (%s) is different from " + "the one in the ARN (%s)\", $S, $N, $N))", IllegalArgumentException.class, variableName, variableName, arnVariableName) .endControlFlow(); } builder.add("$N = $N.toBuilder().$N(resource.$N())", opModel.getInput().getVariableName(), opModel.getInput().getVariableName(), arnableMember.getFluentSetterMethodName(), s3ArnableField.getArnResourceSubstitutionGetter()); for (Map.Entry<String, String> entry : otherFieldsToPopulate.entrySet()) { MemberModel memberModel = opModel.getInputShape().tryFindMemberModelByC2jName(entry.getKey(), true); String variableName = memberModel.getVariable().getVariableName(); String arnVariableName = variableName + "InArn"; builder.add(".$N($N)", memberModel.getFluentSetterMethodName(), arnVariableName); } return Optional.of(builder.addStatement(".build()").endControlFlow().build()); } return Optional.empty(); } /** * Given operation and c2j name, returns the String that represents calling the * c2j member's getter method in the opmodel input shape. * * For example, Operation is CreateConnection and c2j name is CatalogId, * returns "createConnectionRequest.catalogId()" */ private static String inputShapeMemberGetter(OperationModel opModel, String c2jName) { return opModel.getInput().getVariableName() + "." + opModel.getInputShape().getMemberByC2jName(c2jName).getFluentGetterMethodName() + "()"; } }
3,476
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/client/SdkClientOptions.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import javax.lang.model.element.Modifier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.ClassSpec; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.core.client.config.ClientOption; public class SdkClientOptions implements ClassSpec { private final IntermediateModel model; // private final EndpointRulesSpecUtils endpointRulesSpecUtils; public SdkClientOptions(IntermediateModel model) { this.model = model; // this.endpointRulesSpecUtils = new EndpointRulesSpecUtils(model); } @Override public TypeSpec poetSpec() { TypeSpec.Builder builder = PoetUtils.createClassBuilder(className()) .addTypeVariable(TypeVariableName.get("T")) .addModifiers(Modifier.PUBLIC) .addAnnotation(SdkInternalApi.class) .superclass(ParameterizedTypeName.get(ClassName.get(ClientOption.class), TypeVariableName.get("T"))); builder.addMethod(ctor()); return builder.build(); } @Override public ClassName className() { return ClassName.get(model.getMetadata().getFullClientInternalPackageName(), model.getMetadata().getServiceName() + "ClientOption"); } private MethodSpec ctor() { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class), TypeVariableName.get("T")), "valueClass") .addStatement("super(valueClass)") .build(); } }
3,477
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/client/SyncClientClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PROTECTED; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static software.amazon.awssdk.codegen.poet.client.AsyncClientClass.updateSdkClientConfigurationMethod; import static software.amazon.awssdk.codegen.poet.client.ClientClassUtils.addS3ArnableFieldCode; import static software.amazon.awssdk.codegen.poet.client.ClientClassUtils.applySignerOverrideMethod; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.awscore.internal.AwsProtocolMetadata; import software.amazon.awssdk.awscore.internal.AwsServiceProtocol; import software.amazon.awssdk.codegen.emitters.GeneratorTaskParams; import software.amazon.awssdk.codegen.model.config.customization.UtilitiesMethod; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.Protocol; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.PoetUtils; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeSpecUtils; import software.amazon.awssdk.codegen.poet.client.specs.Ec2ProtocolSpec; import software.amazon.awssdk.codegen.poet.client.specs.JsonProtocolSpec; import software.amazon.awssdk.codegen.poet.client.specs.ProtocolSpec; import software.amazon.awssdk.codegen.poet.client.specs.QueryProtocolSpec; import software.amazon.awssdk.codegen.poet.client.specs.XmlProtocolSpec; import software.amazon.awssdk.codegen.poet.model.ServiceClientConfigurationUtils; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.client.handler.SyncClientHandler; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryRefreshCache; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryRequest; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.metrics.NoOpMetricCollector; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Logger; public class SyncClientClass extends SyncClientInterface { private final IntermediateModel model; private final PoetExtension poetExtensions; private final ClassName className; private final ProtocolSpec protocolSpec; private final ClassName serviceClientConfigurationClassName; private final ServiceClientConfigurationUtils configurationUtils; private final boolean useSraAuth; public SyncClientClass(GeneratorTaskParams taskParams) { super(taskParams.getModel()); this.model = taskParams.getModel(); this.poetExtensions = taskParams.getPoetExtensions(); this.className = poetExtensions.getClientClass(model.getMetadata().getSyncClient()); this.protocolSpec = getProtocolSpecs(poetExtensions, model); this.serviceClientConfigurationClassName = new PoetExtension(model).getServiceConfigClass(); this.configurationUtils = new ServiceClientConfigurationUtils(model); this.useSraAuth = new AuthSchemeSpecUtils(model).useSraAuth(); } @Override protected void addInterfaceClass(TypeSpec.Builder type) { ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getSyncInterface()); type.addSuperinterface(interfaceClass) .addJavadoc("Internal implementation of {@link $1T}.\n\n@see $1T#builder()", interfaceClass); } @Override protected TypeSpec.Builder createTypeSpec() { return PoetUtils.createClassBuilder(className); } @Override protected void addAnnotations(TypeSpec.Builder type) { type.addAnnotation(SdkInternalApi.class); } @Override protected void addModifiers(TypeSpec.Builder type) { type.addModifiers(FINAL); } @Override protected void addFields(TypeSpec.Builder type) { type.addField(logger()) .addField(protocolMetadata()) .addField(SyncClientHandler.class, "clientHandler", PRIVATE, FINAL) .addField(protocolSpec.protocolFactory(model)) .addField(SdkClientConfiguration.class, "clientConfiguration", PRIVATE, FINAL); } @Override protected void addAdditionalMethods(TypeSpec.Builder type) { if (!useSraAuth) { if (model.containsRequestSigners()) { type.addMethod(applySignerOverrideMethod(poetExtensions, model)); } } model.getEndpointOperation().ifPresent( o -> type.addField(EndpointDiscoveryRefreshCache.class, "endpointDiscoveryCache", PRIVATE)); type.addMethod(constructor()) .addMethod(nameMethod()) .addMethods(protocolSpec.additionalMethods()) .addMethod(resolveMetricPublishersMethod()); protocolSpec.createErrorResponseHandler().ifPresent(type::addMethod); type.addMethod(updateSdkClientConfigurationMethod(configurationUtils.serviceClientConfigurationBuilderClassName())); type.addMethod(protocolSpec.initProtocolFactory(model)); } private FieldSpec logger() { return FieldSpec.builder(Logger.class, "log", PRIVATE, STATIC, FINAL) .initializer("$T.loggerFor($T.class)", Logger.class, className) .build(); } private FieldSpec protocolMetadata() { return FieldSpec.builder(AwsProtocolMetadata.class, "protocolMetadata", PRIVATE, STATIC, FINAL) .initializer("$T.builder().serviceProtocol($T.$L).build()", AwsProtocolMetadata.class, AwsServiceProtocol.class, model.getMetadata().getProtocol()) .build(); } private MethodSpec nameMethod() { return MethodSpec.methodBuilder("serviceName") .addAnnotation(Override.class) .addModifiers(PUBLIC, FINAL) .returns(String.class) .addStatement("return SERVICE_NAME") .build(); } @Override protected MethodSpec serviceClientConfigMethod() { return MethodSpec.methodBuilder("serviceClientConfiguration") .addAnnotation(Override.class) .addModifiers(PUBLIC, FINAL) .returns(serviceClientConfigurationClassName) .addStatement("return new $T(this.clientConfiguration.toBuilder()).build()", this.configurationUtils.serviceClientConfigurationBuilderClassName()) .build(); } @Override public ClassName className() { return className; } private MethodSpec constructor() { MethodSpec.Builder builder = MethodSpec.constructorBuilder() .addModifiers(PROTECTED) .addParameter(SdkClientConfiguration.class, "clientConfiguration") .addStatement("this.clientHandler = new $T(clientConfiguration)", protocolSpec.getClientHandlerClass()) .addStatement("this.clientConfiguration = clientConfiguration"); FieldSpec protocolFactoryField = protocolSpec.protocolFactory(model); if (model.getMetadata().isJsonProtocol()) { builder.addStatement("this.$N = init($T.builder()).build()", protocolFactoryField.name, protocolFactoryField.type); } else { builder.addStatement("this.$N = init()", protocolFactoryField.name); } if (model.getEndpointOperation().isPresent()) { builder.beginControlFlow("if (clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED))"); builder.addStatement("this.endpointDiscoveryCache = $T.create($T.create(this))", EndpointDiscoveryRefreshCache.class, poetExtensions.getClientClass(model.getNamingStrategy().getServiceName() + "EndpointDiscoveryCacheLoader")); if (model.getCustomizationConfig().allowEndpointOverrideForEndpointDiscoveryRequiredOperations()) { builder.beginControlFlow("if (clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN) == " + "Boolean.TRUE)"); builder.addStatement("log.warn(() -> $S)", "Endpoint discovery is enabled for this client, and an endpoint override was also " + "specified. This will disable endpoint discovery for methods that require it, instead " + "using the specified endpoint override. This may or may not be what you intended."); builder.endControlFlow(); } builder.endControlFlow(); } return builder.build(); } @Override protected List<MethodSpec> operations() { return model.getOperations().values().stream() .filter(o -> !o.hasEventStreamInput()) .filter(o -> !o.hasEventStreamOutput()) .flatMap(this::operations) .collect(Collectors.toList()); } private Stream<MethodSpec> operations(OperationModel opModel) { List<MethodSpec> methods = new ArrayList<>(); methods.add(traditionalMethod(opModel)); return methods.stream(); } private MethodSpec traditionalMethod(OperationModel opModel) { MethodSpec.Builder method = SyncClientInterface.operationMethodSignature(model, opModel) .addAnnotation(Override.class); if (!useSraAuth) { method.addCode(ClientClassUtils.callApplySignerOverrideMethod(opModel)); } method.addCode(protocolSpec.responseHandler(model, opModel)); protocolSpec.errorResponseHandler(opModel).ifPresent(method::addCode); if (opModel.getEndpointDiscovery() != null) { method.addStatement("boolean endpointDiscoveryEnabled = " + "clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED)"); method.addStatement("boolean endpointOverridden = " + "clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN) == Boolean.TRUE"); if (opModel.getEndpointDiscovery().isRequired()) { if (!model.getCustomizationConfig().allowEndpointOverrideForEndpointDiscoveryRequiredOperations()) { method.beginControlFlow("if (endpointOverridden)"); method.addStatement("throw new $T($S)", IllegalStateException.class, "This operation requires endpoint discovery, but an endpoint override was specified " + "when the client was created. This is not supported."); method.endControlFlow(); method.beginControlFlow("if (!endpointDiscoveryEnabled)"); method.addStatement("throw new $T($S)", IllegalStateException.class, "This operation requires endpoint discovery, but endpoint discovery was disabled on the " + "client."); method.endControlFlow(); } else { method.beginControlFlow("if (endpointOverridden)"); method.addStatement("endpointDiscoveryEnabled = false"); method.nextControlFlow("else if (!endpointDiscoveryEnabled)"); method.addStatement("throw new $T($S)", IllegalStateException.class, "This operation requires endpoint discovery to be enabled, or for you to specify an " + "endpoint override when the client is created."); method.endControlFlow(); } } method.addStatement("$T cachedEndpoint = null", URI.class); method.beginControlFlow("if (endpointDiscoveryEnabled)"); ParameterizedTypeName identityFutureTypeName = ParameterizedTypeName.get(ClassName.get(CompletableFuture.class), WildcardTypeName.subtypeOf(AwsCredentialsIdentity.class)); method.addCode("$T identityFuture = $N.overrideConfiguration()", identityFutureTypeName, opModel.getInput().getVariableName()) .addCode(" .flatMap($T::credentialsIdentityProvider)", AwsRequestOverrideConfiguration.class) .addCode(" .orElseGet(() -> clientConfiguration.option($T.CREDENTIALS_IDENTITY_PROVIDER))", AwsClientOption.class) .addCode(" .resolveIdentity();"); method.addCode("$T key = $T.joinLikeSync(identityFuture).accessKeyId();", String.class, CompletableFutureUtils.class); method.addCode("$1T endpointDiscoveryRequest = $1T.builder()", EndpointDiscoveryRequest.class) .addCode(" .required($L)", opModel.getInputShape().getEndpointDiscovery().isRequired()) .addCode(" .defaultEndpoint(clientConfiguration.option($T.ENDPOINT))", SdkClientOption.class) .addCode(" .overrideConfiguration($N.overrideConfiguration().orElse(null))", opModel.getInput().getVariableName()) .addCode(" .build();"); method.addStatement("cachedEndpoint = endpointDiscoveryCache.get(key, endpointDiscoveryRequest)"); method.endControlFlow(); } method.addStatement("$T clientConfiguration = updateSdkClientConfiguration($L, this.clientConfiguration)", SdkClientConfiguration.class, opModel.getInput().getVariableName()); method.addStatement("$T<$T> metricPublishers = " + "resolveMetricPublishers(clientConfiguration, $N.overrideConfiguration().orElse(null))", List.class, MetricPublisher.class, opModel.getInput().getVariableName()) .addStatement("$1T apiCallMetricCollector = metricPublishers.isEmpty() ? $2T.create() : $1T.create($3S)", MetricCollector.class, NoOpMetricCollector.class, "ApiCall"); method.beginControlFlow("try") .addStatement("apiCallMetricCollector.reportMetric($T.$L, $S)", CoreMetric.class, "SERVICE_ID", model.getMetadata().getServiceId()) .addStatement("apiCallMetricCollector.reportMetric($T.$L, $S)", CoreMetric.class, "OPERATION_NAME", opModel.getOperationName()); addS3ArnableFieldCode(opModel, model).ifPresent(method::addCode); method.addCode(ClientClassUtils.addEndpointTraitCode(opModel)); method.addCode(protocolSpec.executionHandler(opModel)) .endControlFlow() .beginControlFlow("finally") .addStatement("metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()))") .endControlFlow(); return method.build(); } @Override protected void addCloseMethod(TypeSpec.Builder type) { MethodSpec method = MethodSpec.methodBuilder("close") .addAnnotation(Override.class) .addModifiers(PUBLIC) .addStatement("$N.close()", "clientHandler") .build(); type.addMethod(method); } @Override protected MethodSpec.Builder utilitiesOperationBody(MethodSpec.Builder builder) { UtilitiesMethod config = model.getCustomizationConfig().getUtilitiesMethod(); String instanceClass = config.getInstanceType(); if (instanceClass == null) { instanceClass = config.getReturnType(); } ClassName instanceType = PoetUtils.classNameFromFqcn(instanceClass); return builder.addAnnotation(Override.class) .addStatement("return $T.create($L)", instanceType, String.join(",", config.getCreateMethodParams())); } static ProtocolSpec getProtocolSpecs(PoetExtension poetExtensions, IntermediateModel model) { Protocol protocol = model.getMetadata().getProtocol(); switch (protocol) { case QUERY: return new QueryProtocolSpec(model, poetExtensions); case REST_XML: return new XmlProtocolSpec(model, poetExtensions); case EC2: return new Ec2ProtocolSpec(model, poetExtensions); case AWS_JSON: case REST_JSON: case CBOR: return new JsonProtocolSpec(poetExtensions, model); default: throw new RuntimeException("Unknown protocol: " + protocol.name()); } } private MethodSpec resolveMetricPublishersMethod() { String clientConfigName = "clientConfiguration"; String requestOverrideConfigName = "requestOverrideConfiguration"; MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("resolveMetricPublishers") .addModifiers(PRIVATE, STATIC) .returns(ParameterizedTypeName.get(List.class, MetricPublisher.class)) .addParameter(SdkClientConfiguration.class, clientConfigName) .addParameter(RequestOverrideConfiguration.class, requestOverrideConfigName); String publishersName = "publishers"; methodBuilder.addStatement("$T $N = null", ParameterizedTypeName.get(List.class, MetricPublisher.class), publishersName); methodBuilder.beginControlFlow("if ($N != null)", requestOverrideConfigName) .addStatement("$N = $N.metricPublishers()", publishersName, requestOverrideConfigName) .endControlFlow(); methodBuilder.beginControlFlow("if ($1N == null || $1N.isEmpty())", publishersName) .addStatement("$N = $N.option($T.$N)", publishersName, clientConfigName, SdkClientOption.class, "METRIC_PUBLISHERS") .endControlFlow(); methodBuilder.beginControlFlow("if ($1N == null)", publishersName) .addStatement("$N = $T.emptyList()", publishersName, Collections.class) .endControlFlow(); methodBuilder.addStatement("return $N", publishersName); return methodBuilder.build(); } @Override protected MethodSpec.Builder waiterOperationBody(MethodSpec.Builder builder) { return builder.addAnnotation(Override.class) .addStatement("return $T.builder().client(this).build()", poetExtensions.getSyncWaiterInterface()); } }
3,478
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/client/SyncClientInterface.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.stream.Collectors.toCollection; import static java.util.stream.Collectors.toList; import static javax.lang.model.element.Modifier.DEFAULT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static software.amazon.awssdk.codegen.internal.Constant.SYNC_CLIENT_DESTINATION_PATH_PARAM_NAME; import static software.amazon.awssdk.codegen.internal.Constant.SYNC_CLIENT_SOURCE_PATH_PARAM_NAME; import static software.amazon.awssdk.codegen.internal.Constant.SYNC_STREAMING_INPUT_PARAM; import static software.amazon.awssdk.codegen.internal.Constant.SYNC_STREAMING_OUTPUT_PARAM; import static software.amazon.awssdk.codegen.poet.client.AsyncClientInterface.STREAMING_TYPE_VARIABLE; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.awscore.AwsClient; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.codegen.docs.ClientType; import software.amazon.awssdk.codegen.docs.DocConfiguration; import software.amazon.awssdk.codegen.docs.SimpleMethodOverload; import software.amazon.awssdk.codegen.docs.WaiterDocs; import software.amazon.awssdk.codegen.model.config.customization.UtilitiesMethod; 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; import software.amazon.awssdk.codegen.poet.model.DeprecationUtils; import software.amazon.awssdk.codegen.utils.PaginatorUtils; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServiceMetadataProvider; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; public class SyncClientInterface implements ClassSpec { private final IntermediateModel model; private final ClassName className; private final String clientPackageName; private final PoetExtension poetExtensions; public SyncClientInterface(IntermediateModel model) { this.model = model; this.clientPackageName = model.getMetadata().getFullClientPackageName(); this.className = ClassName.get(clientPackageName, model.getMetadata().getSyncInterface()); this.poetExtensions = new PoetExtension(model); } @Override public final TypeSpec poetSpec() { TypeSpec.Builder result = createTypeSpec(); addInterfaceClass(result); addAnnotations(result); addModifiers(result); addFields(result); result.addMethods(operations()); if (model.getCustomizationConfig().getUtilitiesMethod() != null) { result.addMethod(utilitiesMethod()); } if (model.hasWaiters()) { result.addMethod(waiterMethod()); } addAdditionalMethods(result); result.addMethod(serviceClientConfigMethod()); addCloseMethod(result); return result.build(); } protected void addInterfaceClass(TypeSpec.Builder type) { type.addSuperinterface(AwsClient.class); } protected TypeSpec.Builder createTypeSpec() { return PoetUtils.createInterfaceBuilder(className); } protected void addAnnotations(TypeSpec.Builder type) { type.addAnnotation(SdkPublicApi.class) .addAnnotation(ThreadSafe.class); } protected void addModifiers(TypeSpec.Builder type) { } protected void addCloseMethod(TypeSpec.Builder type) { } protected void addFields(TypeSpec.Builder type) { type.addField(FieldSpec.builder(String.class, "SERVICE_NAME") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$S", model.getMetadata().getSigningName()) .build()) .addField(FieldSpec.builder(String.class, "SERVICE_METADATA_ID") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("$S", model.getMetadata().getEndpointPrefix()) .addJavadoc("Value for looking up the service's metadata from the {@link $T}.", ServiceMetadataProvider.class) .build()); } protected void addAdditionalMethods(TypeSpec.Builder type) { if (!model.getCustomizationConfig().isExcludeClientCreateMethod()) { type.addMethod(create()); } type.addMethod(builder()) .addMethod(serviceMetadata()); PoetUtils.addJavadoc(type::addJavadoc, getJavadoc()); } @Override public ClassName className() { return className; } private String getJavadoc() { return "Service client for accessing " + model.getMetadata().getDescriptiveServiceName() + ". This can be " + "created using the static {@link #builder()} method.\n\n" + model.getMetadata().getDocumentation(); } private MethodSpec create() { return MethodSpec.methodBuilder("create") .returns(className) .addModifiers(STATIC, PUBLIC) .addJavadoc( "Create a {@link $T} with the region loaded from the {@link $T} and credentials loaded from the " + "{@link $T}.", className, DefaultAwsRegionProviderChain.class, DefaultCredentialsProvider.class) .addStatement("return builder().build()") .build(); } private MethodSpec builder() { ClassName builderClass = ClassName.get(clientPackageName, model.getMetadata().getSyncBuilder()); ClassName builderInterface = ClassName.get(clientPackageName, model.getMetadata().getSyncBuilderInterface()); return MethodSpec.methodBuilder("builder") .returns(builderInterface) .addModifiers(STATIC, PUBLIC) .addJavadoc("Create a builder that can be used to configure and create a {@link $T}.", className) .addStatement("return new $T()", builderClass) .build(); } private MethodSpec serviceMetadata() { return MethodSpec.methodBuilder("serviceMetadata") .returns(ServiceMetadata.class) .addModifiers(STATIC, PUBLIC) .addStatement("return $T.of(SERVICE_METADATA_ID)", ServiceMetadata.class) .build(); } protected Iterable<MethodSpec> operations() { return model.getOperations().values().stream() // TODO Sync not supported for event streaming yet. Revisit after sync/async merge .filter(o -> !o.hasEventStreamInput()) .filter(o -> !o.hasEventStreamOutput()) .flatMap(this::operationsWithVariants) .collect(toList()); } private Stream<MethodSpec> operationsWithVariants(OperationModel opModel) { List<MethodSpec> methods = new ArrayList<>(); methods.addAll(traditionalMethodWithConsumerVariant(opModel)); methods.addAll(overloadedMethods(opModel)); methods.addAll(paginatedMethods(opModel)); return methods.stream() // Add Deprecated annotation if needed to all overloads .map(m -> DeprecationUtils.checkDeprecated(opModel, m)); } private List<MethodSpec> traditionalMethodWithConsumerVariant(OperationModel opModel) { List<MethodSpec> methods = new ArrayList<>(); MethodSpec.Builder builder = operationMethodSignature(model, opModel); MethodSpec method = operationBody(builder, opModel).build(); methods.add(method); addConsumerMethod(methods, method, SimpleMethodOverload.NORMAL, opModel); return methods; } private static MethodSpec.Builder operationBaseSignature(IntermediateModel model, OperationModel opModel, Consumer<MethodSpec.Builder> addFirstParameter, SimpleMethodOverload simpleMethodOverload, String methodName) { TypeName responseType = ClassName.get(model.getMetadata().getFullModelPackageName(), opModel.getReturnType().getReturnType()); TypeName returnType = opModel.hasStreamingOutput() ? STREAMING_TYPE_VARIABLE : responseType; MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName) .returns(returnType) .addModifiers(PUBLIC) .addJavadoc(opModel.getDocs(model, ClientType.SYNC, simpleMethodOverload)) .addExceptions(getExceptionClasses(model, opModel)); addFirstParameter.accept(methodBuilder); streamingMethod(methodBuilder, opModel, responseType); return methodBuilder; } protected MethodSpec.Builder operationBody(MethodSpec.Builder builder, OperationModel opModel) { return builder.addModifiers(DEFAULT) .addStatement("throw new $T()", UnsupportedOperationException.class); } static MethodSpec.Builder operationMethodSignature(IntermediateModel model, OperationModel opModel) { return operationMethodSignature(model, opModel, SimpleMethodOverload.NORMAL, opModel.getMethodName()); } // TODO This is inconsistent with how async client reuses method signature static MethodSpec.Builder operationMethodSignature(IntermediateModel model, OperationModel opModel, SimpleMethodOverload simpleMethodOverload, String methodName) { ClassName requestType = ClassName.get(model.getMetadata().getFullModelPackageName(), opModel.getInput().getVariableType()); return operationBaseSignature(model, opModel, b -> b.addParameter(requestType, opModel.getInput().getVariableName()), simpleMethodOverload, methodName); } private MethodSpec.Builder operationSimpleMethodSignature(IntermediateModel model, OperationModel opModel, String methodName) { TypeName returnType = ClassName.get(model.getMetadata().getFullModelPackageName(), opModel.getReturnType().getReturnType()); MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName) .returns(returnType) .addModifiers(PUBLIC) .addExceptions(getExceptionClasses(model, opModel)); return simpleMethodModifier(builder); } protected List<MethodSpec> paginatedMethods(OperationModel opModel) { List<MethodSpec> paginatedMethodSpecs = new ArrayList<>(); if (opModel.isPaginated()) { if (opModel.getInputShape().isSimpleMethod()) { paginatedMethodSpecs.add(paginatedSimpleMethod(opModel)); } MethodSpec.Builder paginatedMethodBuilder = operationMethodSignature(model, opModel, SimpleMethodOverload.PAGINATED, PaginatorUtils.getPaginatedMethodName(opModel.getMethodName())) .returns(poetExtensions.getResponseClassForPaginatedSyncOperation(opModel.getOperationName())); MethodSpec paginatedMethod = paginatedMethodBody(paginatedMethodBuilder, opModel).build(); paginatedMethodSpecs.add(paginatedMethod); addConsumerMethod(paginatedMethodSpecs, paginatedMethod, SimpleMethodOverload.PAGINATED, opModel); } return paginatedMethodSpecs; } private MethodSpec paginatedSimpleMethod(OperationModel opModel) { String paginatedMethodName = PaginatorUtils.getPaginatedMethodName(opModel.getMethodName()); ClassName requestType = ClassName.get(model.getMetadata().getFullModelPackageName(), opModel.getInput().getVariableType()); return operationSimpleMethodSignature(model, opModel, paginatedMethodName) .returns(poetExtensions.getResponseClassForPaginatedSyncOperation(opModel.getOperationName())) .addStatement("return $L($T.builder().build())", paginatedMethodName, requestType) .addJavadoc(opModel.getDocs(model, ClientType.SYNC, SimpleMethodOverload.NO_ARG_PAGINATED)) .build(); } protected MethodSpec.Builder paginatedMethodBody(MethodSpec.Builder builder, OperationModel operationModel) { return builder.addModifiers(DEFAULT, PUBLIC) .addStatement("return new $T(this, $L)", poetExtensions.getResponseClassForPaginatedSyncOperation(operationModel.getOperationName()), operationModel.getInput().getVariableName()); } private static void streamingMethod(MethodSpec.Builder methodBuilder, OperationModel opModel, TypeName responseType) { if (opModel.hasStreamingInput()) { methodBuilder.addParameter(ClassName.get(RequestBody.class), SYNC_STREAMING_INPUT_PARAM); } if (opModel.hasStreamingOutput()) { methodBuilder.addTypeVariable(STREAMING_TYPE_VARIABLE); ParameterizedTypeName streamingResponseHandlerType = ParameterizedTypeName .get(ClassName.get(ResponseTransformer.class), responseType, STREAMING_TYPE_VARIABLE); methodBuilder.addParameter(streamingResponseHandlerType, SYNC_STREAMING_OUTPUT_PARAM); } } /** * @param opModel Operation to generate simple methods for. * @return All simple method overloads for a given operation. */ private List<MethodSpec> overloadedMethods(OperationModel opModel) { TypeName responseType = ClassName.get(model.getMetadata().getFullModelPackageName(), opModel.getReturnType().getReturnType()); ClassName requestType = ClassName.get(model.getMetadata().getFullModelPackageName(), opModel.getInput().getVariableType()); List<MethodSpec> simpleMethods = new ArrayList<>(); if (opModel.getInputShape().isSimpleMethod()) { simpleMethods.add(simpleMethodWithNoArgs(opModel)); } if (opModel.hasStreamingInput() && opModel.hasStreamingOutput()) { MethodSpec simpleMethod = streamingInputOutputFileSimpleMethod(opModel, responseType, requestType); simpleMethods.add(simpleMethod); addConsumerMethod(simpleMethods, simpleMethod, SimpleMethodOverload.FILE, opModel); } else if (opModel.hasStreamingInput()) { MethodSpec simpleMethod = uploadFromFileSimpleMethod(opModel, responseType, requestType); simpleMethods.add(simpleMethod); addConsumerMethod(simpleMethods, simpleMethod, SimpleMethodOverload.FILE, opModel); } else if (opModel.hasStreamingOutput()) { MethodSpec downloadToFileSimpleMethod = downloadToFileSimpleMethod(opModel, responseType, requestType); MethodSpec inputStreamSimpleMethod = inputStreamSimpleMethod(opModel, responseType, requestType); MethodSpec bytesSimpleMethod = bytesSimpleMethod(opModel, responseType, requestType); simpleMethods.add(downloadToFileSimpleMethod); addConsumerMethod(simpleMethods, downloadToFileSimpleMethod, SimpleMethodOverload.FILE, opModel); simpleMethods.add(inputStreamSimpleMethod); addConsumerMethod(simpleMethods, inputStreamSimpleMethod, SimpleMethodOverload.INPUT_STREAM, opModel); simpleMethods.add(bytesSimpleMethod); addConsumerMethod(simpleMethods, bytesSimpleMethod, SimpleMethodOverload.BYTES, opModel); } return simpleMethods; } private MethodSpec simpleMethodWithNoArgs(OperationModel opModel) { ClassName requestType = ClassName.get(model.getMetadata().getFullModelPackageName(), opModel.getInput().getVariableType()); return operationSimpleMethodSignature(model, opModel, opModel.getMethodName()) .addStatement("return $L($T.builder().build())", opModel.getMethodName(), requestType) .addJavadoc(opModel.getDocs(model, ClientType.SYNC, SimpleMethodOverload.NO_ARG)) .build(); } protected void addConsumerMethod(List<MethodSpec> specs, MethodSpec spec, SimpleMethodOverload overload, OperationModel opModel) { String fileConsumerBuilderJavadoc = consumerBuilderJavadoc(opModel, overload); specs.add(ClientClassUtils.consumerBuilderVariant(spec, fileConsumerBuilderJavadoc)); } /** * @return Simple method for streaming input operations to read data from a file. */ private MethodSpec uploadFromFileSimpleMethod(OperationModel opModel, TypeName responseType, ClassName requestType) { String methodName = opModel.getMethodName(); ParameterSpec inputVarParam = ParameterSpec.builder(requestType, opModel.getInput().getVariableName()).build(); ParameterSpec srcPathParam = ParameterSpec.builder(ClassName.get(Path.class), SYNC_CLIENT_SOURCE_PATH_PARAM_NAME).build(); MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName) .returns(responseType) .addModifiers(PUBLIC) .addParameter(inputVarParam) .addParameter(srcPathParam) .addJavadoc(opModel.getDocs(model, ClientType.SYNC, SimpleMethodOverload.FILE)) .addExceptions(getExceptionClasses(model, opModel)) .addStatement("return $L($N, $T.fromFile($N))", methodName, inputVarParam, ClassName.get(RequestBody.class), srcPathParam); return simpleMethodModifier(builder).build(); } /** * @return Simple method for streaming output operations to get content as an input stream. */ private MethodSpec inputStreamSimpleMethod(OperationModel opModel, TypeName responseType, ClassName requestType) { TypeName returnType = ParameterizedTypeName.get(ClassName.get(ResponseInputStream.class), responseType); MethodSpec.Builder builder = MethodSpec.methodBuilder(opModel.getMethodName()) .returns(returnType) .addModifiers(PUBLIC) .addParameter(requestType, opModel.getInput().getVariableName()) .addJavadoc(opModel.getDocs(model, ClientType.SYNC, SimpleMethodOverload.INPUT_STREAM)) .addExceptions(getExceptionClasses(model, opModel)) .addStatement("return $L($L, $T.toInputStream())", opModel.getMethodName(), opModel.getInput().getVariableName(), ClassName.get(ResponseTransformer.class)); return simpleMethodModifier(builder).build(); } /** * @return Simple method for streaming output operations to get the content as a byte buffer or other in-memory types. */ private MethodSpec bytesSimpleMethod(OperationModel opModel, TypeName responseType, ClassName requestType) { TypeName returnType = ParameterizedTypeName.get(ClassName.get(ResponseBytes.class), responseType); MethodSpec.Builder builder = MethodSpec.methodBuilder(opModel.getMethodName() + "AsBytes") .returns(returnType) .addModifiers(PUBLIC) .addParameter(requestType, opModel.getInput().getVariableName()) .addJavadoc(opModel.getDocs(model, ClientType.SYNC, SimpleMethodOverload.BYTES)) .addExceptions(getExceptionClasses(model, opModel)) .addStatement("return $L($L, $T.toBytes())", opModel.getMethodName(), opModel.getInput().getVariableName(), ClassName.get(ResponseTransformer.class)); return simpleMethodModifier(builder).build(); } /** * @return Simple method for streaming output operations to write response content to a file. */ private MethodSpec downloadToFileSimpleMethod(OperationModel opModel, TypeName responseType, ClassName requestType) { String methodName = opModel.getMethodName(); ParameterSpec inputVarParam = ParameterSpec.builder(requestType, opModel.getInput().getVariableName()).build(); ParameterSpec dstFileParam = ParameterSpec.builder(ClassName.get(Path.class), SYNC_CLIENT_DESTINATION_PATH_PARAM_NAME).build(); MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName) .returns(responseType) .addModifiers(PUBLIC) .addParameter(inputVarParam) .addParameter(dstFileParam) .addJavadoc(opModel.getDocs(model, ClientType.SYNC, SimpleMethodOverload.FILE)) .addExceptions(getExceptionClasses(model, opModel)) .addStatement("return $L($N, $T.toFile($N))", methodName, inputVarParam, ClassName.get(ResponseTransformer.class), dstFileParam); return simpleMethodModifier(builder).build(); } /** * Generate a simple method for operations with streaming input and output members. * Streaming input member that reads data from a file and a streaming output member that write response content to a file. */ private MethodSpec streamingInputOutputFileSimpleMethod(OperationModel opModel, TypeName responseType, ClassName requestType) { String methodName = opModel.getMethodName(); ParameterSpec inputVarParam = ParameterSpec.builder(requestType, opModel.getInput().getVariableName()).build(); ParameterSpec srcFileParam = ParameterSpec.builder(ClassName.get(Path.class), SYNC_CLIENT_SOURCE_PATH_PARAM_NAME).build(); ParameterSpec dstFileParam = ParameterSpec.builder(ClassName.get(Path.class), SYNC_CLIENT_DESTINATION_PATH_PARAM_NAME).build(); MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName) .returns(responseType) .addModifiers(PUBLIC) .addParameter(inputVarParam) .addParameter(srcFileParam) .addParameter(dstFileParam) .addJavadoc(opModel.getDocs(model, ClientType.SYNC, SimpleMethodOverload.FILE)) .addExceptions(getExceptionClasses(model, opModel)) .addStatement("return $L($N, $T.fromFile($N), $T.toFile($N))", methodName, inputVarParam, ClassName.get(RequestBody.class), srcFileParam, ClassName.get(ResponseTransformer.class), dstFileParam); return simpleMethodModifier(builder).build(); } protected MethodSpec.Builder simpleMethodModifier(MethodSpec.Builder builder) { return builder.addModifiers(DEFAULT); } private static List<ClassName> getExceptionClasses(IntermediateModel model, OperationModel opModel) { List<ClassName> exceptions = opModel.getExceptions().stream() .map(e -> ClassName.get(model.getMetadata().getFullModelPackageName(), e.getExceptionName())) .collect(toCollection(ArrayList::new)); Collections.addAll(exceptions, ClassName.get(AwsServiceException.class), ClassName.get(SdkClientException.class), ClassName.get(model.getMetadata().getFullModelPackageName(), model.getSdkModeledExceptionBaseClassName())); return exceptions; } private String consumerBuilderJavadoc(OperationModel opModel, SimpleMethodOverload overload) { return opModel.getDocs(model, ClientType.SYNC, overload, new DocConfiguration().isConsumerBuilder(true)); } protected MethodSpec utilitiesMethod() { UtilitiesMethod config = model.getCustomizationConfig().getUtilitiesMethod(); ClassName returnType = PoetUtils.classNameFromFqcn(config.getReturnType()); MethodSpec.Builder builder = MethodSpec.methodBuilder(UtilitiesMethod.METHOD_NAME) .returns(returnType) .addModifiers(PUBLIC) .addJavadoc("Creates an instance of {@link $T} object with the " + "configuration set on this client.", returnType); return utilitiesOperationBody(builder).build(); } protected MethodSpec serviceClientConfigMethod() { return MethodSpec.methodBuilder("serviceClientConfiguration") .addAnnotation(Override.class) .addModifiers(PUBLIC, DEFAULT) .addStatement("throw new $T()", UnsupportedOperationException.class) .returns(new PoetExtension(model).getServiceConfigClass()) .build(); } protected MethodSpec.Builder utilitiesOperationBody(MethodSpec.Builder builder) { return builder.addModifiers(DEFAULT).addStatement("throw new $T()", UnsupportedOperationException.class); } protected MethodSpec waiterMethod() { MethodSpec.Builder builder = MethodSpec.methodBuilder("waiter") .addModifiers(PUBLIC) .returns(poetExtensions.getSyncWaiterInterface()) .addJavadoc(WaiterDocs.waiterMethodInClient(poetExtensions .getSyncWaiterInterface())); return waiterOperationBody(builder).build(); } protected MethodSpec.Builder waiterOperationBody(MethodSpec.Builder builder) { return builder.addModifiers(DEFAULT, PUBLIC) .addStatement("throw new $T()", UnsupportedOperationException.class); } }
3,479
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client/traits/RequestCompressionTrait.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits; import com.squareup.javapoet.CodeBlock; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.interceptor.trait.RequestCompression; /** * The logic for handling the "requestCompression" trait within the code generator. */ public class RequestCompressionTrait { private RequestCompressionTrait() { } /** * Generate a ".putExecutionAttribute(...)" code-block for the provided operation model. This should be used within the * context of initializing {@link ClientExecutionParams}. If request compression is not required by the operation, this will * return an empty code-block. */ public static CodeBlock create(OperationModel operationModel, IntermediateModel model) { if (operationModel.getRequestCompression() == null) { return CodeBlock.of(""); } // TODO : remove once: // 1) S3 checksum interceptors are moved to occur after CompressRequestStage // 2) Transfer-Encoding:chunked is supported in S3 if (model.getMetadata().getServiceName().equals("S3")) { throw new IllegalStateException("Request compression for S3 is not yet supported in the AWS SDK for Java."); } List<String> encodings = operationModel.getRequestCompression().getEncodings(); return CodeBlock.of(".putExecutionAttribute($T.REQUEST_COMPRESSION, " + "$T.builder().encodings($L).isStreaming($L).build())", SdkInternalExecutionAttribute.class, RequestCompression.class, encodings.stream().collect(Collectors.joining("\", \"", "\"", "\"")), operationModel.hasStreamingInput()); } }
3,480
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client/traits/HttpChecksumRequiredTrait.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits; import com.squareup.javapoet.CodeBlock; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.interceptor.trait.HttpChecksumRequired; /** * The logic for handling the "httpChecksumRequired" trait within the code generator. */ public class HttpChecksumRequiredTrait { private HttpChecksumRequiredTrait() { } /** * Generate a ".putExecutionAttribute(...)" code-block for the provided operation model. This should be used within the * context of initializing {@link ClientExecutionParams}. If HTTP checksums are not required by the operation, this will * return an empty code-block. */ public static CodeBlock putHttpChecksumAttribute(OperationModel operationModel) { if (operationModel.isHttpChecksumRequired()) { return CodeBlock.of(".putExecutionAttribute($T.HTTP_CHECKSUM_REQUIRED, $T.create())\n", SdkInternalExecutionAttribute.class, HttpChecksumRequired.class); } return CodeBlock.of(""); } }
3,481
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client/traits/HttpChecksumTrait.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits; import com.squareup.javapoet.CodeBlock; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.interceptor.trait.HttpChecksum; /** * The logic for handling the Flexible "httpChecksum" trait within the code generator. */ public class HttpChecksumTrait { private HttpChecksumTrait() { } /** * Generate a ".putExecutionAttribute(...)" code-block for the provided operation model. This should be used within the * context of initializing {@link ClientExecutionParams}. * If HTTP checksums are not required by the operation, this will return an empty code-block. */ public static CodeBlock create(OperationModel operationModel) { if (operationModel.getHttpChecksum() != null) { CodeBlock.Builder codeBuilder = CodeBlock.builder(); codeBuilder.add(CodeBlock.of(".putExecutionAttribute($T.HTTP_CHECKSUM, $T.builder().requestChecksumRequired($L)", SdkInternalExecutionAttribute.class, HttpChecksum.class, operationModel.getHttpChecksum().isRequestChecksumRequired())); addFluentGetterToBuilder(operationModel, codeBuilder, operationModel.getHttpChecksum().getRequestAlgorithmMember(), "requestAlgorithm"); addFluentGetterToBuilder(operationModel, codeBuilder, operationModel.getHttpChecksum().getRequestValidationModeMember(), "requestValidationMode"); // loop to get the comma separated strings \"literals\" List<String> responseAlgorithms = operationModel.getHttpChecksum().getResponseAlgorithms(); if (responseAlgorithms != null && !responseAlgorithms.isEmpty()) { codeBuilder.add(CodeBlock.of(".responseAlgorithms(")) .add( CodeBlock.of("$L", responseAlgorithms.stream().collect( Collectors.joining("\", \"", "\"", "\"")))) .add(CodeBlock.of(")")); } codeBuilder.add(CodeBlock.of(".isRequestStreaming($L)", operationModel.getInputShape().isHasStreamingMember())); return codeBuilder.add(CodeBlock.of(".build())")).build(); } else { return CodeBlock.of(""); } } private static void addFluentGetterToBuilder(OperationModel operationModel, CodeBlock.Builder codeBuilder, String requestValidationModeMemberInModel, String memberBuilderName) { if (requestValidationModeMemberInModel != null) { MemberModel requestValidationModeMember = operationModel.getInputShape().tryFindMemberModelByC2jName( requestValidationModeMemberInModel, true); if (requestValidationModeMember == null) { throw new IllegalStateException(requestValidationModeMemberInModel + " is not a member in " + operationModel.getInputShape().getShapeName()); } codeBuilder.add(".$L($N.$N())", memberBuilderName, operationModel.getInput().getVariableName(), requestValidationModeMember.getFluentGetterMethodName()); } } }
3,482
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client/traits/NoneAuthTypeRequestTrait.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits; import com.squareup.javapoet.CodeBlock; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.service.AuthType; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; /** * Trait which defines if a given request needs to be authenticated. * A request is not authenticated only if it has "auththpe" trait explicitly marked as "none" */ @SdkInternalApi public class NoneAuthTypeRequestTrait { private NoneAuthTypeRequestTrait() { } /** * Generate a ".putExecutionAttribute(...)" code-block for the provided operation model. This should be used within the * context of initializing {@link ClientExecutionParams}. If and only if "authType" trait is explicitly set as "none" the set * the execution attribute as false. */ public static CodeBlock create(OperationModel operationModel) { if (operationModel.getAuthType() == AuthType.NONE) { CodeBlock.Builder codeBuilder = CodeBlock.builder(); codeBuilder.add(CodeBlock.of(".putExecutionAttribute($T.IS_NONE_AUTH_TYPE_REQUEST, $L)", SdkInternalExecutionAttribute.class, operationModel.getAuthType() != AuthType.NONE)); return codeBuilder.build(); } else { return CodeBlock.of(""); } } }
3,483
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client/specs/QueryProtocolSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.specs; 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 java.util.Optional; import java.util.concurrent.CompletableFuture; import javax.lang.model.element.Modifier; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeSpecUtils; import software.amazon.awssdk.codegen.poet.client.traits.HttpChecksumRequiredTrait; import software.amazon.awssdk.codegen.poet.client.traits.HttpChecksumTrait; import software.amazon.awssdk.codegen.poet.client.traits.NoneAuthTypeRequestTrait; import software.amazon.awssdk.codegen.poet.client.traits.RequestCompressionTrait; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.protocols.query.AwsQueryProtocolFactory; import software.amazon.awssdk.utils.CompletableFutureUtils; public class QueryProtocolSpec implements ProtocolSpec { protected final PoetExtension poetExtensions; protected final IntermediateModel intermediateModel; protected final boolean useSraAuth; public QueryProtocolSpec(IntermediateModel intermediateModel, PoetExtension poetExtensions) { this.intermediateModel = intermediateModel; this.poetExtensions = poetExtensions; this.useSraAuth = new AuthSchemeSpecUtils(intermediateModel).useSraAuth(); } @Override public FieldSpec protocolFactory(IntermediateModel model) { return FieldSpec.builder(protocolFactoryClass(), "protocolFactory") .addModifiers(Modifier.PRIVATE, Modifier.FINAL).build(); } protected Class<?> protocolFactoryClass() { return AwsQueryProtocolFactory.class; } @Override public MethodSpec initProtocolFactory(IntermediateModel model) { MethodSpec.Builder methodSpec = MethodSpec.methodBuilder("init") .returns(protocolFactoryClass()) .addModifiers(Modifier.PRIVATE); methodSpec.addCode("return $T.builder()\n", protocolFactoryClass()); registerModeledExceptions(model, poetExtensions).forEach(methodSpec::addCode); methodSpec.addCode(".clientConfiguration(clientConfiguration)\n" + ".defaultServiceExceptionSupplier($T::builder)\n", poetExtensions.getModelClass(model.getSdkModeledExceptionBaseClassName())); methodSpec.addCode(".build();"); return methodSpec.build(); } @Override public CodeBlock responseHandler(IntermediateModel model, OperationModel opModel) { ClassName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); return CodeBlock.builder() .addStatement("\n\n$T<$T> responseHandler = protocolFactory.createResponseHandler($T::builder)", HttpResponseHandler.class, responseType, responseType) .build(); } @Override public Optional<CodeBlock> errorResponseHandler(OperationModel opModel) { return Optional.of( CodeBlock.builder() .add("\n\n$T errorResponseHandler = protocolFactory.createErrorResponseHandler();", ParameterizedTypeName.get(HttpResponseHandler.class, AwsServiceException.class)) .build()); } @Override public CodeBlock executionHandler(OperationModel opModel) { TypeName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); ClassName requestType = poetExtensions.getModelClass(opModel.getInput().getVariableType()); ClassName marshaller = poetExtensions.getTransformClass(opModel.getInputShape().getShapeName() + "Marshaller"); CodeBlock.Builder codeBlock = CodeBlock.builder() .add("\n\nreturn clientHandler.execute(new $T<$T, $T>()", ClientExecutionParams.class, requestType, responseType) .add(".withOperationName($S)\n", opModel.getOperationName()) .add(".withProtocolMetadata(protocolMetadata)\n") .add(".withResponseHandler(responseHandler)\n") .add(".withErrorResponseHandler(errorResponseHandler)\n") .add(hostPrefixExpression(opModel)) .add(discoveredEndpoint(opModel)) .add(credentialType(opModel, intermediateModel)) .add(".withRequestConfiguration(clientConfiguration)") .add(".withInput($L)", opModel.getInput().getVariableName()) .add(".withMetricCollector(apiCallMetricCollector)") .add(HttpChecksumRequiredTrait.putHttpChecksumAttribute(opModel)) .add(HttpChecksumTrait.create(opModel)); if (!useSraAuth) { codeBlock.add(NoneAuthTypeRequestTrait.create(opModel)); } codeBlock.add(RequestCompressionTrait.create(opModel, intermediateModel)); if (opModel.hasStreamingInput()) { return codeBlock.add(".withRequestBody(requestBody)") .add(".withMarshaller($L));", syncStreamingMarshaller(intermediateModel, opModel, marshaller)) .build(); } return codeBlock.add(".withMarshaller(new $T(protocolFactory)) $L);", marshaller, opModel.hasStreamingOutput() ? ", responseTransformer" : "").build(); } @Override public CodeBlock asyncExecutionHandler(IntermediateModel intermediateModel, OperationModel opModel) { ClassName pojoResponseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); ClassName requestType = poetExtensions.getModelClass(opModel.getInput().getVariableType()); ClassName marshaller = poetExtensions.getRequestTransformClass(opModel.getInputShape().getShapeName() + "Marshaller"); String asyncRequestBody = opModel.hasStreamingInput() ? ".withAsyncRequestBody(requestBody)" : ""; TypeName executeFutureValueType = executeFutureValueType(opModel, poetExtensions); CodeBlock.Builder builder = CodeBlock.builder() .add("\n\n$T<$T> executeFuture = clientHandler.execute(new $T<$T, $T>()\n", CompletableFuture.class, executeFutureValueType, ClientExecutionParams.class, requestType, pojoResponseType) .add(".withOperationName(\"$N\")\n", opModel.getOperationName()) .add(".withProtocolMetadata(protocolMetadata)\n") .add(".withMarshaller($L)\n", asyncMarshaller(intermediateModel, opModel, marshaller, "protocolFactory")) .add(".withResponseHandler(responseHandler)\n") .add(".withErrorResponseHandler(errorResponseHandler)\n") .add(credentialType(opModel, intermediateModel)) .add(".withRequestConfiguration(clientConfiguration)") .add(".withMetricCollector(apiCallMetricCollector)\n") .add(HttpChecksumRequiredTrait.putHttpChecksumAttribute(opModel)) .add(HttpChecksumTrait.create(opModel)); if (!useSraAuth) { builder.add(NoneAuthTypeRequestTrait.create(opModel)); } builder.add(RequestCompressionTrait.create(opModel, intermediateModel)); builder.add(hostPrefixExpression(opModel) + asyncRequestBody + ".withInput($L)$L);", opModel.getInput().getVariableName(), opModel.hasStreamingOutput() ? ", asyncResponseTransformer" : ""); String whenCompleteFutureName = "whenCompleteFuture"; builder.addStatement("$T $N = null", ParameterizedTypeName.get(ClassName.get(CompletableFuture.class), executeFutureValueType), whenCompleteFutureName); if (opModel.hasStreamingOutput()) { builder.addStatement("$T<$T, ReturnT> finalAsyncResponseTransformer = asyncResponseTransformer", AsyncResponseTransformer.class, pojoResponseType); builder.addStatement("$N = executeFuture$L", whenCompleteFutureName, streamingOutputWhenComplete("finalAsyncResponseTransformer")); } else { builder.addStatement("$N = executeFuture$L", whenCompleteFutureName, publishMetricsWhenComplete()); } builder.addStatement("return $T.forwardExceptionTo($N, executeFuture)", CompletableFutureUtils.class, whenCompleteFutureName); return builder.build(); } @Override public Optional<MethodSpec> createErrorResponseHandler() { return Optional.empty(); } }
3,484
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client/specs/ProtocolSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.specs; 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 com.squareup.javapoet.TypeVariableName; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import software.amazon.awssdk.awscore.client.handler.AwsSyncClientHandler; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.Protocol; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeType; import software.amazon.awssdk.codegen.model.service.AuthType; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.utils.AuthUtils; import software.amazon.awssdk.core.CredentialType; import software.amazon.awssdk.core.client.handler.SyncClientHandler; import software.amazon.awssdk.core.runtime.transform.AsyncStreamingRequestMarshaller; import software.amazon.awssdk.core.runtime.transform.StreamingRequestMarshaller; import software.amazon.awssdk.protocols.core.ExceptionMetadata; import software.amazon.awssdk.utils.StringUtils; public interface ProtocolSpec { FieldSpec protocolFactory(IntermediateModel model); MethodSpec initProtocolFactory(IntermediateModel model); CodeBlock responseHandler(IntermediateModel model, OperationModel opModel); Optional<CodeBlock> errorResponseHandler(OperationModel opModel); CodeBlock executionHandler(OperationModel opModel); /** * Execution handler invocation only differs for protocols that support streaming outputs (REST-JSON, REST-XML). */ default CodeBlock asyncExecutionHandler(IntermediateModel intermediateModel, OperationModel opModel) { return executionHandler(opModel); } default Class<? extends SyncClientHandler> getClientHandlerClass() { return AwsSyncClientHandler.class; } Optional<MethodSpec> createErrorResponseHandler(); default List<MethodSpec> additionalMethods() { return new ArrayList<>(); } default List<CodeBlock> registerModeledExceptions(IntermediateModel model, PoetExtension poetExtensions) { return model.getShapes().values().stream() .filter(s -> s.getShapeType() == ShapeType.Exception) .map(e -> CodeBlock.builder() .add(".registerModeledException($T.builder()" + ".errorCode($S)" + ".exceptionBuilderSupplier($T::builder)" + "$L" // populateHttpStatusCode + ".build())", ExceptionMetadata.class, e.getErrorCode(), poetExtensions.getModelClass(e.getShapeName()), populateHttpStatusCode(e, model)) .build()) .collect(Collectors.toList()); } default String populateHttpStatusCode(ShapeModel shapeModel, IntermediateModel model) { Integer statusCode = shapeModel.getHttpStatusCode(); if (statusCode == null && model.getMetadata().getProtocol() == Protocol.AWS_JSON) { if (shapeModel.isFault()) { statusCode = 500; } else { statusCode = 400; } } return statusCode != null ? String.format(".httpStatusCode(%d)", statusCode) : ""; } default String hostPrefixExpression(OperationModel opModel) { return opModel.getEndpointTrait() != null && !StringUtils.isEmpty(opModel.getEndpointTrait().getHostPrefix()) ? ".hostPrefixExpression(resolvedHostExpression)\n" : ""; } default String discoveredEndpoint(OperationModel opModel) { return opModel.getEndpointDiscovery() != null ? ".discoveredEndpoint(cachedEndpoint)\n" : ""; } default CodeBlock credentialType(OperationModel opModel, IntermediateModel model) { if (AuthUtils.isOpBearerAuth(model, opModel)) { return CodeBlock.of(".credentialType($T.TOKEN)\n", CredentialType.class); } else { return CodeBlock.of(""); } } /** * For sync streaming operations, wrap request marshaller in {@link StreamingRequestMarshaller} class. */ default CodeBlock syncStreamingMarshaller(IntermediateModel model, OperationModel opModel, ClassName marshaller) { return streamingMarshallerCode(model, opModel, marshaller, "protocolFactory", false); } default CodeBlock asyncMarshaller(IntermediateModel model, OperationModel opModel, ClassName marshaller, String protocolFactory) { if (opModel.hasStreamingInput()) { return streamingMarshallerCode(model, opModel, marshaller, protocolFactory, true); } else { return CodeBlock.builder().add("new $T($L)", marshaller, protocolFactory).build(); } } default CodeBlock streamingMarshallerCode(IntermediateModel model, OperationModel opModel, ClassName marshaller, String protocolFactory, boolean isAsync) { CodeBlock.Builder builder = CodeBlock .builder() .add("$T.builder().delegateMarshaller(new $T($L))", isAsync ? AsyncStreamingRequestMarshaller.class : StreamingRequestMarshaller.class, marshaller, protocolFactory) .add(".$L(requestBody)", isAsync ? "asyncRequestBody" : "requestBody"); if (opModel.hasRequiresLengthInInput()) { builder.add(".requiresLength(true)"); } if (opModel.getAuthType() == AuthType.V4_UNSIGNED_BODY) { builder.add(".transferEncoding(true)"); } if (model.getMetadata().supportsH2()) { builder.add(".useHttp2(true)"); } builder.add(".build()"); return builder.build(); } /** * Need to notify the response handler/response transformer if the future is completed exceptionally. * * @param responseHandlerName Variable name of response handler customer passed in. * @return whenComplete to append to future. */ default String streamingOutputWhenComplete(String responseHandlerName) { return String.format(".whenComplete((r, e) -> {%n" + " if (e != null) {%n" + " runAndLogError(log, \"Exception thrown in exceptionOccurred callback, ignoring\", () " + "-> %s.exceptionOccurred(e));%n" + " }%n" + " endOfStreamFuture.whenComplete((r2, e2) -> {%n" + " %s%n" + " });" + "})", responseHandlerName, publishMetrics()); } default TypeName executeFutureValueType(OperationModel opModel, PoetExtension poetExtensions) { if (opModel.hasEventStreamOutput()) { return ClassName.get(Void.class); } else if (opModel.hasStreamingOutput()) { return TypeVariableName.get("ReturnT"); } else { return getPojoResponseType(opModel, poetExtensions); } } /** * Gets the POJO response type for the operation. * * @param opModel Operation to get response type for. */ default TypeName getPojoResponseType(OperationModel opModel, PoetExtension poetExtensions) { return poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); } default String publishMetricsWhenComplete() { return String.format(".whenComplete((r, e) -> {%n" + "%s%n" + "})", publishMetrics()); } default String publishMetrics() { return "metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));"; } }
3,485
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client/specs/JsonProtocolSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.specs; import static software.amazon.awssdk.codegen.model.intermediate.Protocol.AWS_JSON; 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.TypeVariableName; import com.squareup.javapoet.WildcardTypeName; import java.util.Optional; import java.util.concurrent.CompletableFuture; import javax.lang.model.element.Modifier; import software.amazon.awssdk.awscore.eventstream.EventStreamAsyncResponseTransformer; import software.amazon.awssdk.awscore.eventstream.EventStreamTaggedUnionPojoSupplier; import software.amazon.awssdk.awscore.eventstream.RestEventStreamAsyncResponseTransformer; import software.amazon.awssdk.awscore.exception.AwsServiceException; 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.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.intermediate.Protocol; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.auth.scheme.AuthSchemeSpecUtils; import software.amazon.awssdk.codegen.poet.client.traits.HttpChecksumRequiredTrait; import software.amazon.awssdk.codegen.poet.client.traits.HttpChecksumTrait; import software.amazon.awssdk.codegen.poet.client.traits.NoneAuthTypeRequestTrait; import software.amazon.awssdk.codegen.poet.client.traits.RequestCompressionTrait; import software.amazon.awssdk.codegen.poet.eventstream.EventStreamUtils; import software.amazon.awssdk.codegen.poet.model.EventStreamSpecHelper; import software.amazon.awssdk.core.SdkPojoBuilder; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.client.handler.AttachHttpMetadataResponseHandler; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.protocols.cbor.AwsCborProtocolFactory; import software.amazon.awssdk.protocols.json.AwsJsonProtocol; import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory; import software.amazon.awssdk.protocols.json.BaseAwsJsonProtocolFactory; import software.amazon.awssdk.protocols.json.JsonOperationMetadata; import software.amazon.awssdk.utils.CompletableFutureUtils; public class JsonProtocolSpec implements ProtocolSpec { private final PoetExtension poetExtensions; private final IntermediateModel model; private final boolean useSraAuth; public JsonProtocolSpec(PoetExtension poetExtensions, IntermediateModel model) { this.poetExtensions = poetExtensions; this.model = model; this.useSraAuth = new AuthSchemeSpecUtils(model).useSraAuth(); } @Override public FieldSpec protocolFactory(IntermediateModel model) { return FieldSpec.builder(protocolFactoryClass(), "protocolFactory") .addModifiers(Modifier.PRIVATE, Modifier.FINAL).build(); } @Override public MethodSpec initProtocolFactory(IntermediateModel model) { ClassName baseException = baseExceptionClassName(model); Metadata metadata = model.getMetadata(); ParameterizedTypeName upperBound = ParameterizedTypeName.get(ClassName.get(BaseAwsJsonProtocolFactory.Builder.class), TypeVariableName.get("T")); TypeVariableName typeVariableName = TypeVariableName.get("T", upperBound); MethodSpec.Builder methodSpec = MethodSpec.methodBuilder("init") .addTypeVariable(typeVariableName) .addParameter(typeVariableName, "builder") .returns(typeVariableName) .addModifiers(Modifier.PRIVATE) .addCode("return builder\n") .addCode(".clientConfiguration(clientConfiguration)\n") .addCode(".defaultServiceExceptionSupplier($T::builder)\n", baseException) .addCode(".protocol($T.$L)\n", AwsJsonProtocol.class, protocolEnumName(metadata.getProtocol())) .addCode(".protocolVersion($S)\n", metadata.getJsonVersion()) .addCode("$L", customErrorCodeFieldName()); String contentType = Optional.ofNullable(model.getCustomizationConfig().getCustomServiceMetadata()) .map(MetadataConfig::getContentType) .orElse(metadata.getContentType()); if (contentType != null) { methodSpec.addCode(".contentType($S)", contentType); } if (metadata.getAwsQueryCompatible() != null) { methodSpec.addCode("$L", hasAwsQueryCompatible()); } registerModeledExceptions(model, poetExtensions).forEach(methodSpec::addCode); methodSpec.addCode(";"); return methodSpec.build(); } private CodeBlock customErrorCodeFieldName() { return model.getCustomizationConfig().getCustomErrorCodeFieldName() == null ? CodeBlock.builder().build() : CodeBlock.of(".customErrorCodeFieldName($S)", model.getCustomizationConfig().getCustomErrorCodeFieldName()); } private CodeBlock hasAwsQueryCompatible() { return CodeBlock.of(".hasAwsQueryCompatible($L)", model.getMetadata().getAwsQueryCompatible() != null); } private Class<?> protocolFactoryClass() { if (model.getMetadata().isCborProtocol()) { return AwsCborProtocolFactory.class; } else { return AwsJsonProtocolFactory.class; } } @Override public CodeBlock responseHandler(IntermediateModel model, OperationModel opModel) { TypeName pojoResponseType = getPojoResponseType(opModel, poetExtensions); String protocolFactory = protocolFactoryLiteral(model, opModel); CodeBlock.Builder builder = CodeBlock.builder() .add("$T operationMetadata = $T.builder()\n", JsonOperationMetadata.class, JsonOperationMetadata.class) .add(".hasStreamingSuccessResponse($L)\n", opModel.hasStreamingOutput()) .add(".isPayloadJson($L)\n", !opModel.getHasBlobMemberAsPayload() && !opModel.getHasStringMemberAsPayload()) .add(".build();"); if (opModel.hasEventStreamOutput()) { responseHandlersForEventStreaming(opModel, pojoResponseType, protocolFactory, builder); } else { builder.add("\n\n$T<$T> responseHandler = $L.createResponseHandler(operationMetadata, $T::builder);", HttpResponseHandler.class, pojoResponseType, protocolFactory, pojoResponseType); } return builder.build(); } @Override public Optional<CodeBlock> errorResponseHandler(OperationModel opModel) { String protocolFactory = protocolFactoryLiteral(model, opModel); return Optional.of( CodeBlock.builder() .add("\n\n$T<$T> errorResponseHandler = createErrorResponseHandler($L, operationMetadata);", HttpResponseHandler.class, AwsServiceException.class, protocolFactory) .build()); } @Override public CodeBlock executionHandler(OperationModel opModel) { TypeName responseType = getPojoResponseType(opModel, poetExtensions); ClassName requestType = poetExtensions.getModelClass(opModel.getInput().getVariableType()); ClassName marshaller = poetExtensions.getRequestTransformClass(opModel.getInputShape().getShapeName() + "Marshaller"); CodeBlock.Builder codeBlock = CodeBlock.builder() .add("\n\nreturn clientHandler.execute(new $T<$T, $T>()\n", ClientExecutionParams.class, requestType, responseType) .add(".withOperationName(\"$N\")\n", opModel.getOperationName()) .add(".withProtocolMetadata(protocolMetadata)\n") .add(".withResponseHandler(responseHandler)\n") .add(".withErrorResponseHandler(errorResponseHandler)\n") .add(hostPrefixExpression(opModel)) .add(discoveredEndpoint(opModel)) .add(credentialType(opModel, model)) .add(".withRequestConfiguration(clientConfiguration)") .add(".withInput($L)\n", opModel.getInput().getVariableName()) .add(".withMetricCollector(apiCallMetricCollector)") .add(HttpChecksumRequiredTrait.putHttpChecksumAttribute(opModel)) .add(HttpChecksumTrait.create(opModel)); if (!useSraAuth) { codeBlock.add(NoneAuthTypeRequestTrait.create(opModel)); } codeBlock.add(RequestCompressionTrait.create(opModel, model)); if (opModel.hasStreamingInput()) { codeBlock.add(".withRequestBody(requestBody)") .add(".withMarshaller($L)", syncStreamingMarshaller(model, opModel, marshaller)); } else { codeBlock.add(".withMarshaller(new $T(protocolFactory))", marshaller); } return codeBlock.add("$L);", opModel.hasStreamingOutput() ? ", responseTransformer" : "") .build(); } @Override public CodeBlock asyncExecutionHandler(IntermediateModel intermediateModel, OperationModel opModel) { boolean isRestJson = isRestJson(intermediateModel); TypeName pojoResponseType = getPojoResponseType(opModel, poetExtensions); ClassName requestType = poetExtensions.getModelClass(opModel.getInput().getVariableType()); ClassName marshaller = poetExtensions.getRequestTransformClass(opModel.getInputShape().getShapeName() + "Marshaller"); String asyncRequestBody = opModel.hasStreamingInput() ? ".withAsyncRequestBody(requestBody)" : ""; CodeBlock.Builder builder = CodeBlock.builder(); if (opModel.hasEventStreamOutput()) { ShapeModel shapeModel = EventStreamUtils.getEventStreamInResponse(opModel.getOutputShape()); ClassName eventStreamBaseClass = poetExtensions.getModelClassFromShape(shapeModel); ParameterizedTypeName transformerType = ParameterizedTypeName.get( ClassName.get(EventStreamAsyncResponseTransformer.class), pojoResponseType, eventStreamBaseClass); builder.add("$1T<$2T> future = new $1T<>();", ClassName.get(CompletableFuture.class), ClassName.get(Void.class)) .add("$T asyncResponseTransformer = $T.<$T, $T>builder()\n", transformerType, ClassName.get(EventStreamAsyncResponseTransformer.class), pojoResponseType, eventStreamBaseClass) .add(".eventStreamResponseHandler(asyncResponseHandler)\n") .add(".eventResponseHandler(eventResponseHandler)\n") .add(".initialResponseHandler(responseHandler)\n") .add(".exceptionResponseHandler(errorResponseHandler)\n") .add(".future(future)\n") .add(".executor(executor)\n") .add(".serviceName(serviceName())\n") .add(".build();"); if (isRestJson) { builder.add(restAsyncResponseTransformer(pojoResponseType, eventStreamBaseClass)); } } boolean isStreaming = opModel.hasStreamingOutput() || opModel.hasEventStreamOutput(); String protocolFactory = protocolFactoryLiteral(intermediateModel, opModel); TypeName responseType = opModel.hasEventStreamOutput() && !isRestJson ? ClassName.get(SdkResponse.class) : pojoResponseType; TypeName executeFutureValueType = executeFutureValueType(opModel, poetExtensions); builder.add("\n\n$T<$T> executeFuture = ", CompletableFuture.class, executeFutureValueType) .add(opModel.getEndpointDiscovery() != null ? "endpointFuture.thenCompose(cachedEndpoint -> " : "") .add("clientHandler.execute(new $T<$T, $T>()\n", ClientExecutionParams.class, requestType, responseType) .add(".withOperationName(\"$N\")\n", opModel.getOperationName()) .add(".withProtocolMetadata(protocolMetadata)\n") .add(".withMarshaller($L)\n", asyncMarshaller(model, opModel, marshaller, protocolFactory)) .add(asyncRequestBody(opModel)) .add(fullDuplex(opModel)) .add(hasInitialRequestEvent(opModel, isRestJson)) .add(".withResponseHandler($L)\n", responseHandlerName(opModel, isRestJson)) .add(".withErrorResponseHandler(errorResponseHandler)\n") .add(".withRequestConfiguration(clientConfiguration)") .add(".withMetricCollector(apiCallMetricCollector)\n") .add(hostPrefixExpression(opModel)) .add(discoveredEndpoint(opModel)) .add(credentialType(opModel, model)) .add(asyncRequestBody) .add(HttpChecksumRequiredTrait.putHttpChecksumAttribute(opModel)) .add(HttpChecksumTrait.create(opModel)); if (!useSraAuth) { builder.add(NoneAuthTypeRequestTrait.create(opModel)); } builder.add(RequestCompressionTrait.create(opModel, model)) .add(".withInput($L)$L)", opModel.getInput().getVariableName(), asyncResponseTransformerVariable(isStreaming, isRestJson, opModel)) .add(opModel.getEndpointDiscovery() != null ? ");" : ";"); if (opModel.hasStreamingOutput()) { builder.addStatement("$T<$T, ReturnT> finalAsyncResponseTransformer = asyncResponseTransformer", AsyncResponseTransformer.class, pojoResponseType); } String customerResponseHandler = opModel.hasEventStreamOutput() ? "asyncResponseHandler" : "finalAsyncResponseTransformer"; String whenComplete = whenCompleteBody(opModel, customerResponseHandler); if (!whenComplete.isEmpty()) { String whenCompletedFutureName = "whenCompleted"; builder.addStatement("$T<$T> $N = $N$L", CompletableFuture.class, executeFutureValueType, whenCompletedFutureName, "executeFuture", whenComplete); builder.addStatement("executeFuture = $T.forwardExceptionTo($N, executeFuture)", CompletableFutureUtils.class, whenCompletedFutureName); } if (opModel.hasEventStreamOutput()) { builder.addStatement("return $T.forwardExceptionTo(future, executeFuture)", CompletableFutureUtils.class); } else { builder.addStatement("return executeFuture"); } return builder.build(); } private String responseHandlerName(OperationModel opModel, boolean isRestJson) { return opModel.hasEventStreamOutput() && !isRestJson ? "voidResponseHandler" : "responseHandler"; } private CodeBlock fullDuplex(OperationModel opModel) { return opModel.hasEventStreamInput() && opModel.hasEventStreamOutput() ? CodeBlock.of(".withFullDuplex(true)") : CodeBlock.of(""); } private CodeBlock hasInitialRequestEvent(OperationModel opModel, boolean isRestJson) { return opModel.hasEventStreamInput() && !isRestJson ? CodeBlock.of(".withInitialRequestEvent(true)") : CodeBlock.of(""); } private CodeBlock asyncRequestBody(OperationModel opModel) { return opModel.hasEventStreamInput() ? CodeBlock.of(".withAsyncRequestBody($T.fromPublisher(adapted))", AsyncRequestBody.class) : CodeBlock.of(""); } private String asyncResponseTransformerVariable(boolean isStreaming, boolean isRestJson, OperationModel opModel) { if (isStreaming) { if (opModel.hasEventStreamOutput() && isRestJson) { return ", restAsyncResponseTransformer"; } else { return ", asyncResponseTransformer"; } } return ""; } /** * For Rest services, we need to use the {@link RestEventStreamAsyncResponseTransformer} instead of * {@link EventStreamAsyncResponseTransformer} class. This method has the code to create a restAsyncResponseTransformer * variable. * * @param pojoResponseType Type of operation response shape * @param eventStreamBaseClass Class name for the base class of all events in the operation */ private CodeBlock restAsyncResponseTransformer(TypeName pojoResponseType, ClassName eventStreamBaseClass) { ParameterizedTypeName restTransformerType = ParameterizedTypeName.get( ClassName.get(RestEventStreamAsyncResponseTransformer.class), pojoResponseType, eventStreamBaseClass); return CodeBlock.builder() .add("$T restAsyncResponseTransformer = $T.<$T, $T>builder()\n", restTransformerType, ClassName.get(RestEventStreamAsyncResponseTransformer.class), pojoResponseType, eventStreamBaseClass) .add(".eventStreamAsyncResponseTransformer(asyncResponseTransformer)\n") .add(".eventStreamResponseHandler(asyncResponseHandler)\n") .add(".build();") .build(); } /** * For streaming operations we need to notify the response handler or response transformer on exception so * we add a .whenComplete to the future. * * @param operationModel Op model. * @param responseHandlerName Variable name of response handler customer passed in. * @return whenComplete to append to future. */ private String whenCompleteBody(OperationModel operationModel, String responseHandlerName) { if (operationModel.hasEventStreamOutput()) { return eventStreamOutputWhenComplete(responseHandlerName); } else if (operationModel.hasStreamingOutput()) { return streamingOutputWhenComplete(responseHandlerName); } else { // Non streaming can just return the future as is return publishMetricsWhenComplete(); } } /** * For event streaming our future notification is a bit complicated. We create a different future that is not tied * to the lifecycle of the wire request. Successful completion of the future is signalled in * {@link EventStreamAsyncResponseTransformer}. Failure is notified via the normal future (the one returned by the client * handler). * * * @param responseHandlerName Variable name of response handler customer passed in. * @return whenComplete to append to future. */ private String eventStreamOutputWhenComplete(String responseHandlerName) { return String.format(".whenComplete((r, e) -> {%n" + " if (e != null) {%n" + " try {" + " %s.exceptionOccurred(e);%n" + " } finally {" + " future.completeExceptionally(e);" + " }" + " }" + "%s" + "})", responseHandlerName, publishMetrics()); } @Override public Optional<MethodSpec> createErrorResponseHandler() { ClassName httpResponseHandler = ClassName.get(HttpResponseHandler.class); ClassName sdkBaseException = ClassName.get(AwsServiceException.class); TypeName responseHandlerOfException = ParameterizedTypeName.get(httpResponseHandler, sdkBaseException); return Optional.of(MethodSpec.methodBuilder("createErrorResponseHandler") .addParameter(BaseAwsJsonProtocolFactory.class, "protocolFactory") .addParameter(JsonOperationMetadata.class, "operationMetadata") .returns(responseHandlerOfException) .addModifiers(Modifier.PRIVATE) .addStatement("return protocolFactory.createErrorResponseHandler(operationMetadata)") .build()); } private String protocolEnumName(software.amazon.awssdk.codegen.model.intermediate.Protocol protocol) { switch (protocol) { case CBOR: case AWS_JSON: return AWS_JSON.name(); default: return protocol.name(); } } private ClassName baseExceptionClassName(IntermediateModel model) { String exceptionPath = model.getSdkModeledExceptionBaseFqcn() .substring(0, model.getSdkModeledExceptionBaseFqcn().lastIndexOf('.')); return ClassName.get(exceptionPath, model.getSdkModeledExceptionBaseClassName()); } /** * Add responseHandlers for event streaming operations */ private void responseHandlersForEventStreaming(OperationModel opModel, TypeName pojoResponseType, String protocolFactory, CodeBlock.Builder builder) { builder.add("\n\n$T<$T> responseHandler = new $T($L.createResponseHandler(operationMetadata, $T::builder));", HttpResponseHandler.class, pojoResponseType, AttachHttpMetadataResponseHandler.class, protocolFactory, pojoResponseType); builder.add("\n\n$T<$T> voidResponseHandler = $L.createResponseHandler($T.builder()\n" + " .isPayloadJson(false)\n" + " .hasStreamingSuccessResponse(true)\n" + " .build(), $T::builder);", HttpResponseHandler.class, SdkResponse.class, protocolFactory, JsonOperationMetadata.class, VoidSdkResponse.class); ShapeModel eventStream = EventStreamUtils.getEventStreamInResponse(opModel.getOutputShape()); ClassName eventStreamBaseClass = poetExtensions.getModelClassFromShape(eventStream); builder .add("\n\n$T<$T> eventResponseHandler = $L.createResponseHandler($T.builder()\n" + " .isPayloadJson(true)\n" + " .hasStreamingSuccessResponse(false)\n" + " .build(), $T.builder()", HttpResponseHandler.class, WildcardTypeName.subtypeOf(eventStreamBaseClass), protocolFactory, JsonOperationMetadata.class, ClassName.get(EventStreamTaggedUnionPojoSupplier.class)); EventStreamSpecHelper eventStreamSpecHelper = new EventStreamSpecHelper(eventStream, model); EventStreamUtils.getEventMembers(eventStream) .forEach(m -> { String builderMethod = eventStreamSpecHelper.eventBuilderMethodName(m); builder.add(".putSdkPojoSupplier($S, $T::$N)", m.getC2jName(), eventStreamBaseClass, builderMethod); }); builder.add(".defaultSdkPojoSupplier(() -> new $T($T.UNKNOWN))\n" + ".build());\n", SdkPojoBuilder.class, eventStreamBaseClass); } private String protocolFactoryLiteral(IntermediateModel model, OperationModel opModel) { // TODO remove this once kinesis supports CBOR for event streaming if ("Kinesis".equals(model.getMetadata().getServiceId()) && opModel.hasEventStreamOutput()) { return "jsonProtocolFactory"; } return "protocolFactory"; } private boolean isRestJson(IntermediateModel model) { return model.getMetadata().getProtocol() == Protocol.REST_JSON; } }
3,486
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client/specs/XmlProtocolSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.specs; import static software.amazon.awssdk.codegen.poet.PoetUtils.classNameFromFqcn; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.WildcardTypeName; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.awscore.eventstream.EventStreamAsyncResponseTransformer; import software.amazon.awssdk.awscore.eventstream.EventStreamTaggedUnionPojoSupplier; import software.amazon.awssdk.awscore.eventstream.RestEventStreamAsyncResponseTransformer; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.codegen.model.config.customization.S3ArnableFieldConfig; 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.poet.PoetExtension; import software.amazon.awssdk.codegen.poet.client.traits.HttpChecksumRequiredTrait; import software.amazon.awssdk.codegen.poet.client.traits.HttpChecksumTrait; import software.amazon.awssdk.codegen.poet.client.traits.NoneAuthTypeRequestTrait; import software.amazon.awssdk.codegen.poet.client.traits.RequestCompressionTrait; import software.amazon.awssdk.codegen.poet.eventstream.EventStreamUtils; import software.amazon.awssdk.codegen.poet.model.EventStreamSpecHelper; import software.amazon.awssdk.core.SdkPojoBuilder; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.protocols.xml.AwsXmlProtocolFactory; import software.amazon.awssdk.protocols.xml.XmlOperationMetadata; import software.amazon.awssdk.utils.CompletableFutureUtils; public final class XmlProtocolSpec extends QueryProtocolSpec { private final IntermediateModel model; public XmlProtocolSpec(IntermediateModel model, PoetExtension poetExtensions) { super(model, poetExtensions); this.model = model; } @Override protected Class<?> protocolFactoryClass() { if (model.getCustomizationConfig().getCustomProtocolFactoryFqcn() != null) { try { return Class.forName(model.getCustomizationConfig().getCustomProtocolFactoryFqcn()); } catch (ClassNotFoundException e) { throw new RuntimeException("Could not find custom protocol factory class", e); } } return AwsXmlProtocolFactory.class; } @Override public CodeBlock responseHandler(IntermediateModel model, OperationModel opModel) { if (opModel.hasStreamingOutput()) { return streamingResponseHandler(opModel); } ClassName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); if (opModel.hasEventStreamOutput()) { return CodeBlock.builder() .add(eventStreamResponseHandlers(opModel, responseType)) .build(); } TypeName handlerType = ParameterizedTypeName.get( ClassName.get(HttpResponseHandler.class), ParameterizedTypeName.get(ClassName.get(software.amazon.awssdk.core.Response.class), responseType)); return CodeBlock.builder() .addStatement("\n\n$T responseHandler = protocolFactory.createCombinedResponseHandler($T::builder, " + "new $T().withHasStreamingSuccessResponse($L))", handlerType, responseType, XmlOperationMetadata.class, opModel.hasStreamingOutput()) .build(); } private CodeBlock streamingResponseHandler(OperationModel opModel) { ClassName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); return CodeBlock.builder() .addStatement("\n\n$T<$T> responseHandler = protocolFactory.createResponseHandler($T::builder, " + "new $T().withHasStreamingSuccessResponse($L))", HttpResponseHandler.class, responseType, responseType, XmlOperationMetadata.class, opModel.hasStreamingOutput()) .build(); } @Override public Optional<CodeBlock> errorResponseHandler(OperationModel opModel) { return opModel.hasStreamingOutput() ? streamingErrorResponseHandler(opModel) : Optional.empty(); } private Optional<CodeBlock> streamingErrorResponseHandler(OperationModel opModel) { return super.errorResponseHandler(opModel); } @Override public CodeBlock executionHandler(OperationModel opModel) { if (opModel.hasStreamingOutput()) { return streamingExecutionHandler(opModel); } TypeName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); ClassName requestType = poetExtensions.getModelClass(opModel.getInput().getVariableType()); ClassName marshaller = poetExtensions.getTransformClass(opModel.getInputShape().getShapeName() + "Marshaller"); CodeBlock.Builder codeBlock = CodeBlock.builder() .add("\n\nreturn clientHandler.execute(new $T<$T, $T>()\n", ClientExecutionParams.class, requestType, responseType) .add(".withOperationName($S)\n", opModel.getOperationName()) .add(".withProtocolMetadata(protocolMetadata)\n") .add(".withCombinedResponseHandler(responseHandler)\n") .add(".withMetricCollector(apiCallMetricCollector)\n" + hostPrefixExpression(opModel) + discoveredEndpoint(opModel)) .add(credentialType(opModel, model)) .add(".withRequestConfiguration(clientConfiguration)") .add(".withInput($L)", opModel.getInput().getVariableName()) .add(HttpChecksumRequiredTrait.putHttpChecksumAttribute(opModel)) .add(HttpChecksumTrait.create(opModel)); if (!useSraAuth) { codeBlock.add(NoneAuthTypeRequestTrait.create(opModel)); } codeBlock.add(RequestCompressionTrait.create(opModel, model)); s3ArnableFields(opModel, model).ifPresent(codeBlock::add); if (opModel.hasStreamingInput()) { return codeBlock.add(".withRequestBody(requestBody)") .add(".withMarshaller($L));", syncStreamingMarshaller(intermediateModel, opModel, marshaller)) .build(); } return codeBlock.add(".withMarshaller(new $T(protocolFactory)) $L);", marshaller, opModel.hasStreamingOutput() ? ", responseTransformer" : "").build(); } private Optional<CodeBlock> s3ArnableFields(OperationModel opModel, IntermediateModel model) { CodeBlock.Builder codeBlock = CodeBlock.builder(); Map<String, S3ArnableFieldConfig> s3ArnableFields = model.getCustomizationConfig().getS3ArnableFields(); String shapeName = opModel.getInputShape().getShapeName(); if (s3ArnableFields != null && s3ArnableFields.containsKey(shapeName)) { S3ArnableFieldConfig s3ArnableField = s3ArnableFields.get(shapeName); codeBlock.add(".putExecutionAttribute($T.$N, $T.builder().arn(arn).build())", classNameFromFqcn(s3ArnableField.getExecutionAttributeKeyFqcn()), "S3_ARNABLE_FIELD", classNameFromFqcn(s3ArnableField.getExecutionAttributeValueFqcn())); return Optional.of(codeBlock.build()); } return Optional.empty(); } private CodeBlock streamingExecutionHandler(OperationModel opModel) { return super.executionHandler(opModel); } @Override public CodeBlock asyncExecutionHandler(IntermediateModel intermediateModel, OperationModel opModel) { if (opModel.hasStreamingOutput()) { return asyncStreamingExecutionHandler(intermediateModel, opModel); } ClassName pojoResponseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); ClassName requestType = poetExtensions.getModelClass(opModel.getInput().getVariableType()); ClassName marshaller = poetExtensions.getRequestTransformClass(opModel.getInputShape().getShapeName() + "Marshaller"); String eventStreamTransformFutureName = "eventStreamTransformFuture"; CodeBlock.Builder builder = CodeBlock.builder(); if (opModel.hasEventStreamOutput()) { builder.add(eventStreamResponseTransformers(opModel, eventStreamTransformFutureName)); } TypeName executeFutureValueType = executeFutureValueType(opModel, poetExtensions); String executionResponseTransformerName = "asyncResponseTransformer"; if (opModel.hasEventStreamOutput()) { executionResponseTransformerName = "restAsyncResponseTransformer"; } builder.add("\n\n$T<$T> executeFuture = clientHandler.execute(new $T<$T, $T>()\n", CompletableFuture.class, executeFutureValueType, ClientExecutionParams.class, requestType, pojoResponseType) .add(".withOperationName(\"$N\")\n", opModel.getOperationName()) .add(".withRequestConfiguration(clientConfiguration)") .add(".withProtocolMetadata(protocolMetadata)\n") .add(".withMarshaller($L)\n", asyncMarshaller(intermediateModel, opModel, marshaller, "protocolFactory")); if (opModel.hasEventStreamOutput()) { builder.add(".withResponseHandler(responseHandler)") .add(".withErrorResponseHandler(errorResponseHandler)"); } else { builder.add(".withCombinedResponseHandler(responseHandler)"); } builder.add(hostPrefixExpression(opModel)) .add(credentialType(opModel, model)) .add(".withMetricCollector(apiCallMetricCollector)\n") .add(asyncRequestBody(opModel)) .add(HttpChecksumRequiredTrait.putHttpChecksumAttribute(opModel)) .add(HttpChecksumTrait.create(opModel)); if (!useSraAuth) { builder.add(NoneAuthTypeRequestTrait.create(opModel)); } builder.add(RequestCompressionTrait.create(opModel, model)); s3ArnableFields(opModel, model).ifPresent(builder::add); builder.add(".withInput($L)", opModel.getInput().getVariableName()); if (opModel.hasEventStreamOutput()) { builder.add(", $N", executionResponseTransformerName); } builder.addStatement(")"); String whenCompleteFutureName = "whenCompleteFuture"; builder.addStatement("$T $N = null", ParameterizedTypeName.get(ClassName.get(CompletableFuture.class), executeFutureValueType), whenCompleteFutureName); if (opModel.hasEventStreamOutput()) { builder.addStatement("$N = executeFuture$L", whenCompleteFutureName, whenCompleteBlock(opModel, "asyncResponseHandler", eventStreamTransformFutureName)); } else { builder.addStatement("$N = executeFuture$L", whenCompleteFutureName, publishMetricsWhenComplete()); } builder.addStatement("$T.forwardExceptionTo($N, executeFuture)", CompletableFutureUtils.class, whenCompleteFutureName); if (opModel.hasEventStreamOutput()) { builder.addStatement("return $T.forwardExceptionTo($N, executeFuture)", CompletableFutureUtils.class, eventStreamTransformFutureName); } else { builder.addStatement("return $N", whenCompleteFutureName); } return builder.build(); } private String asyncRequestBody(OperationModel opModel) { return opModel.hasStreamingInput() ? ".withAsyncRequestBody(requestBody)" : ""; } private CodeBlock asyncStreamingExecutionHandler(IntermediateModel intermediateModel, OperationModel opModel) { return super.asyncExecutionHandler(intermediateModel, opModel); } private CodeBlock eventStreamResponseHandlers(OperationModel opModel, TypeName pojoResponseType) { CodeBlock streamResponseOpMd = CodeBlock.builder() .add("$T.builder()", XmlOperationMetadata.class) .add(".hasStreamingSuccessResponse(true)") .add(".build()") .build(); CodeBlock.Builder builder = CodeBlock.builder(); // Response handler for handling the initial response from the operation. Note, this does not handle the event stream // messages, that is the job of "eventResponseHandler" below builder.addStatement("$T<$T> responseHandler = protocolFactory.createResponseHandler($T::builder, $L)", HttpResponseHandler.class, pojoResponseType, pojoResponseType, streamResponseOpMd); // Response handler responsible for errors for the API call itself, as well as errors sent over the event stream builder.addStatement("$T errorResponseHandler = protocolFactory" + ".createErrorResponseHandler()", ParameterizedTypeName.get(HttpResponseHandler.class, AwsServiceException.class)); ShapeModel eventStreamShape = EventStreamUtils.getEventStreamInResponse(opModel.getOutputShape()); ClassName eventStream = poetExtensions.getModelClassFromShape(eventStreamShape); EventStreamSpecHelper eventStreamSpecHelper = new EventStreamSpecHelper(eventStreamShape, intermediateModel); CodeBlock.Builder supplierBuilder = CodeBlock.builder() .add("$T.builder()", EventStreamTaggedUnionPojoSupplier.class); EventStreamUtils.getEvents(eventStreamShape).forEach(m -> { String builderName = eventStreamSpecHelper.eventBuilderMethodName(m); supplierBuilder.add(".putSdkPojoSupplier($S, $T::$N)", m.getName(), eventStream, builderName); }); supplierBuilder.add(".defaultSdkPojoSupplier(() -> new $T($T.UNKNOWN))", SdkPojoBuilder.class, eventStream); CodeBlock supplierCodeBlock = supplierBuilder.add(".build()").build(); CodeBlock nonStreamingOpMd = CodeBlock.builder() .add("$T.builder()", XmlOperationMetadata.class) .add(".hasStreamingSuccessResponse(false)") .add(".build()") .build(); // The response handler responsible for unmarshalling each event builder.addStatement("$T eventResponseHandler = protocolFactory.createResponseHandler($L, $L)", ParameterizedTypeName.get(ClassName.get(HttpResponseHandler.class), WildcardTypeName.subtypeOf(eventStream)), supplierCodeBlock, nonStreamingOpMd); return builder.build(); } private CodeBlock eventStreamResponseTransformers(OperationModel opModel, String eventTransformerFutureName) { ShapeModel shapeModel = EventStreamUtils.getEventStreamInResponse(opModel.getOutputShape()); ClassName pojoResponseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType()); ClassName eventStreamBaseClass = poetExtensions.getModelClassFromShape(shapeModel); CodeBlock.Builder builder = CodeBlock.builder(); ParameterizedTypeName transformerType = ParameterizedTypeName.get( ClassName.get(EventStreamAsyncResponseTransformer.class), pojoResponseType, eventStreamBaseClass); builder.addStatement("$1T<$2T> $3N = new $1T<>()", ClassName.get(CompletableFuture.class), ClassName.get(Void.class), eventTransformerFutureName) .add("$T asyncResponseTransformer = $T.<$T, $T>builder()\n", transformerType, ClassName.get(EventStreamAsyncResponseTransformer.class), pojoResponseType, eventStreamBaseClass) .add(".eventStreamResponseHandler(asyncResponseHandler)\n") .add(".eventResponseHandler(eventResponseHandler)\n") .add(".initialResponseHandler(responseHandler)\n") .add(".exceptionResponseHandler(errorResponseHandler)\n") .add(".future($N)\n", eventTransformerFutureName) .add(".executor(executor)\n") .add(".serviceName(serviceName())\n") .addStatement(".build()"); ParameterizedTypeName restTransformType = ParameterizedTypeName.get(ClassName.get(RestEventStreamAsyncResponseTransformer.class), pojoResponseType, eventStreamBaseClass); // Wrap the event transformer with this so that the caller's response handler's onResponse() method is invoked. See // docs for RestEventStreamAsyncResponseTransformer for more info on why it's needed builder.addStatement("$T restAsyncResponseTransformer = $T.<$T, $T>builder()\n" + ".eventStreamAsyncResponseTransformer(asyncResponseTransformer)\n" + ".eventStreamResponseHandler(asyncResponseHandler)\n" + ".build()", restTransformType, RestEventStreamAsyncResponseTransformer.class, pojoResponseType, eventStreamBaseClass); return builder.build(); } private CodeBlock whenCompleteBlock(OperationModel operationModel, String responseHandlerName, String eventTransformerFutureName) { CodeBlock.Builder whenComplete = CodeBlock.builder() .add(".whenComplete((r, e) -> ") .beginControlFlow("") .beginControlFlow("if (e != null)") .add("runAndLogError(log, $S, () -> $N.exceptionOccurred(e));", "Exception thrown in exceptionOccurred callback, ignoring", responseHandlerName); if (operationModel.hasEventStreamOutput()) { whenComplete.add("$N.completeExceptionally(e);", eventTransformerFutureName); } whenComplete.endControlFlow() .add(publishMetrics()) .endControlFlow() .add(")") .build(); return whenComplete.build(); } }
3,487
0
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client
Create_ds/aws-sdk-java-v2/codegen/src/main/java/software/amazon/awssdk/codegen/poet/client/specs/Ec2ProtocolSpec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.specs; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.protocols.query.AwsEc2ProtocolFactory; public class Ec2ProtocolSpec extends QueryProtocolSpec { public Ec2ProtocolSpec(IntermediateModel model, PoetExtension poetExtensions) { super(model, poetExtensions); } @Override protected Class<?> protocolFactoryClass() { return AwsEc2ProtocolFactory.class; } }
3,488
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/utils/ModelLoaderUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.io.File; import java.io.IOException; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.codegen.internal.Jackson; public final class ModelLoaderUtils { private static final Logger log = LoggerFactory.getLogger(ModelLoaderUtils.class); private ModelLoaderUtils() { } public static <T> T loadModel(Class<T> clzz, File file) { try { return Jackson.load(clzz, file); } catch (IOException e) { log.error("Failed to read the configuration file {}", file.getAbsolutePath()); throw new RuntimeException(e); } } public static <T> T loadModel(Class<T> clzz, File file, boolean failOnUnknownProperties) { try { return Jackson.load(clzz, file, failOnUnknownProperties); } catch (IOException e) { log.error("Failed to read the configuration file {}", file.getAbsolutePath()); throw new RuntimeException(e); } } public static <T> Optional<T> loadOptionalModel(Class<T> clzz, File file) { if (!file.exists()) { return Optional.empty(); } return Optional.of(loadModel(clzz, file)); } public static <T> Optional<T> loadOptionalModel(Class<T> clzz, File file, boolean failOnUnknownProperties) { if (!file.exists()) { return Optional.empty(); } return Optional.of(loadModel(clzz, file, failOnUnknownProperties)); } }
3,489
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/utils/AuthUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.service.AuthType; public final class AuthUtils { private AuthUtils() { } /** * Returns {@code true} if the service as a whole or any of its operations uses {@code bearer} auth type. */ public static boolean usesBearerAuth(IntermediateModel model) { if (isServiceBearerAuth(model)) { return true; } return model.getOperations().values().stream() .map(OperationModel::getAuthType) .anyMatch(authType -> authType == AuthType.BEARER); } public static boolean usesAwsAuth(IntermediateModel model) { if (isServiceAwsAuthType(model)) { return true; } return model.getOperations().values().stream() .map(OperationModel::getAuthType) .anyMatch(AuthUtils::isAuthTypeAws); } /** * Returns {@code true} if the operation should use bearer auth. */ public static boolean isOpBearerAuth(IntermediateModel model, OperationModel opModel) { if (opModel.getAuthType() == AuthType.BEARER) { return true; } return isServiceBearerAuth(model) && hasNoAuthType(opModel); } private static boolean isServiceBearerAuth(IntermediateModel model) { return model.getMetadata().getAuthType() == AuthType.BEARER; } private static boolean isServiceAwsAuthType(IntermediateModel model) { AuthType authType = model.getMetadata().getAuthType(); return isAuthTypeAws(authType); } private static boolean isAuthTypeAws(AuthType authType) { if (authType == null) { return false; } switch (authType) { case V4: case S3: case S3V4: return true; default: return false; } } private static boolean hasNoAuthType(OperationModel opModel) { return opModel.getAuthType() == null || opModel.getAuthType() == AuthType.NONE; } }
3,490
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/utils/PaginatorUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; public final class PaginatorUtils { private PaginatorUtils() { } /** * @param methodName Name of a method in sync client * @return the name of the auto-pagination enabled operation */ public static String getPaginatedMethodName(String methodName) { return methodName + "Paginator"; } }
3,491
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/docs/DocumentationBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.docs; import static java.util.Collections.singletonList; import static software.amazon.awssdk.codegen.internal.Constant.LF; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringUtils; /** * Builder for a Javadoc string that orders sections consistently. */ public final class DocumentationBuilder { // TODO This prefix is not suitable for paginated operations. Either remove it for paginated operations // or change the statement to something generic private static final String ASYNC_THROWS_PREFIX = "The CompletableFuture returned by this method can be completed " + "exceptionally with the following exceptions."; private String desc; private List<Pair<String, String>> params = new ArrayList<>(); private String returns; private List<Pair<String, String>> asyncThrows = new ArrayList<>(); private List<Pair<String, String>> syncThrows = new ArrayList<>(); private List<Pair<String, List<String>>> tags = new ArrayList<>(); private List<String> see = new ArrayList<>(); /** * Description of javaodc comment. I.E. what you are reading right now. * * @param docs Description string * @return This builder for method chaining. */ public DocumentationBuilder description(String docs) { this.desc = docs; return this; } /** * Adds a new param to the Javadoc. * * @param paramName Name of parameter. * @param paramDocs Documentation for parameter. * @return This builder for method chaining. */ public DocumentationBuilder param(String paramName, String paramDocs) { this.params.add(Pair.of(paramName, paramDocs)); return this; } /** * Adds a new param to the Javadoc. Uses {@link String#format(String, Object...)} using the given arguments. * * @param paramName Name of parameter. * @param paramDocs Documentation for parameter. * @param formatArgs Arguments referenced by format specifiers. * @return This builder for method chaining. */ public DocumentationBuilder param(String paramName, String paramDocs, Object... formatArgs) { return param(paramName, String.format(paramDocs, formatArgs)); } /** * Adds documentation for return value. If not set then no return tag will be added to the Javadoc string. * * @param returnsDoc Documentation for return value (if present). * @return This builder for method chaining. */ public DocumentationBuilder returns(String returnsDoc) { this.returns = returnsDoc; return this; } /** * Adds documentation for return value. If not set then no return tag will be added to the Javadoc string. Uses * {@link String#format(String, Object...)} using the given arguments. * * @param returnsDoc Documentation for return value (if present). * @param formatArgs Arguments referenced by format specifiers. * @return This builder for method chaining. */ public DocumentationBuilder returns(String returnsDoc, Object... formatArgs) { return returns(String.format(returnsDoc, formatArgs)); } /** * Async exceptions are not thrown from the method, rather the returned {@link java.util.concurrent.CompletableFuture} is * completed exceptionally ({@link java.util.concurrent.CompletableFuture#completeExceptionally(Throwable)}. Because of this * we don't add @throws to the Javadocs or method signature for async methods, we instead add a list of exceptions the future * may be completed exceptionally with in the @returns section of the Javadoc. * * @param exceptionClass Class name of thrown exception. * @param exceptionDoc Documentation for thrown exception. * @return This builder for method chaining. */ public DocumentationBuilder asyncThrows(String exceptionClass, String exceptionDoc) { return asyncThrows(singletonList(Pair.of(exceptionClass, exceptionDoc))); } /** * Adds multiple async throws to the Javadoc for each exception name / exception doc pair. * * @param exceptions Multiple pairs of exception name to exception documentation. * @return This builder for method chaining. * @see #asyncThrows(String, String) */ public DocumentationBuilder asyncThrows(Pair<String, String>... exceptions) { return asyncThrows(Arrays.asList(exceptions)); } /** * Adds multiple async throws to the Javadoc for each exception name / exception doc pair. * * @param exceptions Multiple pairs of exception name to exception documentation. * @return This builder for method chaining. * @see #asyncThrows(String, String) */ public DocumentationBuilder asyncThrows(List<Pair<String, String>> exceptions) { asyncThrows.addAll(exceptions); return this; } /** * Adds a throws tag to the Javadoc. * * @param exceptionClass Class name of thrown exception. * @param exceptionDoc Documentation for thrown exception. * @return This builder for method chaining. */ public DocumentationBuilder syncThrows(String exceptionClass, String exceptionDoc) { return syncThrows(singletonList(Pair.of(exceptionClass, exceptionDoc))); } /** * Adds multiple throws tag to the Javadoc for each exception name / exception doc pair. * * @param exceptions Multiple pairs of exception name to exception documentation. * @return This builder for method chaining. * @see #syncThrows(String, String) */ public DocumentationBuilder syncThrows(Pair<String, String>... exceptions) { return syncThrows(Arrays.asList(exceptions)); } /** * Adds multiple throws tag to the Javadoc for each exception name / exception doc pair. * * @param exceptions Multiple pairs of exception name to exception documentation. * @return This builder for method chaining. * @see #syncThrows(String, String) */ public DocumentationBuilder syncThrows(List<Pair<String, String>> exceptions) { syncThrows.addAll(exceptions); return this; } /** * Adds an arbitrary tag with values to the Javadoc. This will be added in between the throws and see sections * of the Javadoc. * * @param tagName Name of tag to add. * @param tagValues List of values associated with the same. * @return This builder for method chaining. */ public DocumentationBuilder tag(String tagName, String... tagValues) { tags.add(Pair.of(tagName, Arrays.asList(tagValues))); return this; } /** * Adds a @see reference to the Javadocs. * * @param seeLink Reference for @see. * @return This builder for method chaining. */ public DocumentationBuilder see(String seeLink) { this.see.add(seeLink); return this; } /** * Adds a @see reference to the Javadocs. Uses {@link String#format(String, Object...)} using the given arguments. * * @param seeLink Reference for @see. * @param formatArgs Arguments referenced by format specifiers. * @return This builder for method chaining. */ public DocumentationBuilder see(String seeLink, Object... formatArgs) { return see(String.format(seeLink, formatArgs)); } /** * Builds the Javadoc string with the current configuration. * * @return Formatted Javadoc string. */ public String build() { StringBuilder str = new StringBuilder(); if (StringUtils.isNotBlank(desc)) { str.append(desc).append(LF).append(LF); } params.forEach(p -> p.apply((paramName, paramDoc) -> formatParam(str, paramName, paramDoc))); if (hasReturn() || !asyncThrows.isEmpty()) { str.append("@return "); if (hasReturn()) { str.append(returns); } if (!asyncThrows.isEmpty()) { // If no docs were provided for success returns add a generic one. if (!hasReturn()) { str.append("A CompletableFuture indicating when result will be completed."); } appendAsyncThrows(str); } str.append(LF); } syncThrows.forEach(t -> t.apply((exName, exDoc) -> formatThrows(str, exName, exDoc))); tags.forEach(t -> t.apply((tagName, tagVals) -> formatTag(str, tagName, tagVals))); see.forEach(s -> str.append("@see ").append(s).append(LF)); return str.toString(); } private boolean hasReturn() { return StringUtils.isNotBlank(returns); } private void appendAsyncThrows(StringBuilder str) { str.append("<br/>").append(LF).append( asyncThrows.stream() .map(t -> t.apply((exName, exDocs) -> String.format("<li>%s %s</li>", exName, exDocs))) .collect(Collectors.joining(LF, ASYNC_THROWS_PREFIX + LF + "<ul>" + LF, LF + "</ul>"))); } private StringBuilder formatParam(StringBuilder doc, String paramName, String paramDoc) { return doc.append("@param ").append(paramName).append(" ").append(paramDoc).append(LF); } private StringBuilder formatThrows(StringBuilder str, String exName, String exDoc) { return str.append("@throws ").append(exName).append(" ").append(exDoc).append(LF); } private StringBuilder formatTag(StringBuilder str, String tagName, List<String> tagVals) { return str.append("@").append(tagName).append(" ") .append(String.join(" ", tagVals)) .append(LF); } }
3,492
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/docs/PaginationDocs.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.docs; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.TypeName; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.service.PaginatorDefinition; import software.amazon.awssdk.codegen.poet.PoetExtension; import software.amazon.awssdk.codegen.utils.PaginatorUtils; import software.amazon.awssdk.utils.async.SequentialSubscriber; public class PaginationDocs { private static final String SUBSCRIBE_METHOD_NAME = "subscribe"; private final OperationModel operationModel; private final PoetExtension poetExtensions; private final PaginatorDefinition paginatorDefinition; public PaginationDocs(IntermediateModel intermediateModel, OperationModel operationModel, PaginatorDefinition paginatorDefinition) { this.operationModel = operationModel; this.poetExtensions = new PoetExtension(intermediateModel); this.paginatorDefinition = paginatorDefinition; } /** * Constructs additional documentation on the client operation that is appended to the service documentation. * * TODO Add a link to our developer guide which will have more details and sample code. Write a blog post too. */ public String getDocsForSyncOperation() { return CodeBlock.builder() .add("<p>This is a variant of {@link #$L($T)} operation. " + "The return type is a custom iterable that can be used to iterate through all the pages. " + "SDK will internally handle making service calls for you.\n</p>", operationModel.getMethodName(), requestType()) .add("<p>\nWhen this operation is called, a custom iterable is returned but no service calls are " + "made yet. So there is no guarantee that the request is valid. As you iterate " + "through the iterable, SDK will start lazily loading response pages by making service calls until " + "there are no pages left or your iteration stops. If there are errors in your request, you will " + "see the failures only after you start iterating through the iterable.\n</p>") .add(getSyncCodeSnippets()) .build() .toString(); } /** * Constructs javadocs for the generated response classes in a paginated operation. * @param clientInterface A java poet {@link ClassName} type of the sync client interface */ public String getDocsForSyncResponseClass(ClassName clientInterface) { return CodeBlock.builder() .add("<p>Represents the output for the {@link $T#$L($T)} operation which is a paginated operation." + " This class is an iterable of {@link $T} that can be used to iterate through all the " + "response pages of the operation.</p>", clientInterface, getPaginatedMethodName(), requestType(), syncResponsePageType()) .add("<p>When the operation is called, an instance of this class is returned. At this point, " + "no service calls are made yet and so there is no guarantee that the request is valid. " + "As you iterate through the iterable, SDK will start lazily loading response pages by making " + "service calls until there are no pages left or your iteration stops. If there are errors in your " + "request, you will see the failures only after you start iterating through the iterable.</p>") .add(getSyncCodeSnippets()) .build() .toString(); } /** * Constructs additional documentation on the async client operation that is appended to the service documentation. */ public String getDocsForAsyncOperation() { return CodeBlock.builder() .add("<p>This is a variant of {@link #$L($T)} operation. " + "The return type is a custom publisher that can be subscribed to request a stream of response " + "pages. SDK will internally handle making service calls for you.\n</p>", operationModel.getMethodName(), requestType()) .add("<p>When the operation is called, an instance of this class is returned. At this point, " + "no service calls are made yet and so there is no guarantee that the request is valid. " + "If there are errors in your request, you will see the failures only after you start streaming " + "the data. The subscribe method should be called as a request to start streaming data. " + "For more info, see {@link $T#$L($T)}. Each call to the subscribe method will result in a new " + "{@link $T} i.e., a new contract to stream data from the starting request.</p>", getPublisherType(), SUBSCRIBE_METHOD_NAME, getSubscriberType(), getSubscriptionType()) .add(getAsyncCodeSnippets()) .build() .toString(); } /** * Constructs javadocs for the generated response classes of a paginated operation in Async client. * @param clientInterface A java poet {@link ClassName} type of the Async client interface */ public String getDocsForAsyncResponseClass(ClassName clientInterface) { return CodeBlock.builder() .add("<p>Represents the output for the {@link $T#$L($T)} operation which is a paginated operation." + " This class is a type of {@link $T} which can be used to provide a sequence of {@link $T} " + "response pages as per demand from the subscriber.</p>", clientInterface, getPaginatedMethodName(), requestType(), getPublisherType(), syncResponsePageType()) .add("<p>When the operation is called, an instance of this class is returned. At this point, " + "no service calls are made yet and so there is no guarantee that the request is valid. " + "If there are errors in your request, you will see the failures only after you start streaming " + "the data. The subscribe method should be called as a request to start streaming data. " + "For more info, see {@link $T#$L($T)}. Each call to the subscribe method will result in a new " + "{@link $T} i.e., a new contract to stream data from the starting request.</p>", getPublisherType(), SUBSCRIBE_METHOD_NAME, getSubscriberType(), getSubscriptionType()) .add(getAsyncCodeSnippets()) .build() .toString(); } private String getSyncCodeSnippets() { CodeBlock callOperationOnClient = CodeBlock.builder() .addStatement("$T responses = client.$L(request)", syncPaginatedResponseType(), getPaginatedMethodName()) .build(); return CodeBlock.builder() .add("\n\n<p>The following are few ways to iterate through the response pages:</p>") .add("1) Using a Stream") .add(buildCode(CodeBlock.builder() .add(callOperationOnClient) .addStatement("responses.stream().forEach(....)") .build())) .add("\n\n2) Using For loop") .add(buildCode(CodeBlock.builder() .add(callOperationOnClient) .beginControlFlow("for ($T response : responses)", syncResponsePageType()) .addStatement(" // do something") .endControlFlow() .build())) .add("\n\n3) Use iterator directly") .add(buildCode(CodeBlock.builder() .add(callOperationOnClient) .addStatement("responses.iterator().forEachRemaining(....)") .build())) .add(noteAboutLimitConfigurationMethod()) .add(noteAboutSyncNonPaginatedMethod()) .build() .toString(); } private String getAsyncCodeSnippets() { CodeBlock callOperationOnClient = CodeBlock.builder() .addStatement("$T publisher = client.$L(request)", asyncPaginatedResponseType(), getPaginatedMethodName()) .build(); return CodeBlock.builder() .add("\n\n<p>The following are few ways to use the response class:</p>") .add("1) Using the subscribe helper method", TypeName.get(SequentialSubscriber.class)) .add(buildCode(CodeBlock.builder() .add(callOperationOnClient) .add(CodeBlock.builder() .addStatement("CompletableFuture<Void> future = publisher" + ".subscribe(res -> " + "{ // Do something with the response })") .addStatement("future.get()") .build()) .build())) .add("\n\n2) Using a custom subscriber") .add(buildCode(CodeBlock.builder() .add(callOperationOnClient) .add("publisher.subscribe(new Subscriber<$T>() {\n\n", syncResponsePageType()) .addStatement("public void onSubscribe($T subscription) { //... }", getSubscriberType()) .add("\n\n") .addStatement("public void onNext($T response) { //... }", syncResponsePageType()) .add("});") .build())) .add("As the response is a publisher, it can work well with third party reactive streams implementations " + "like RxJava2.") .add(noteAboutLimitConfigurationMethod()) .add(noteAboutSyncNonPaginatedMethod()) .build() .toString(); } private CodeBlock buildCode(CodeBlock codeSnippet) { return CodeBlock.builder() .add("<pre>{@code\n") .add(codeSnippet) .add("}</pre>") .build(); } /** * @return Method name for the sync paginated operation */ private String getPaginatedMethodName() { return PaginatorUtils.getPaginatedMethodName(operationModel.getMethodName()); } /** * @return A Poet {@link ClassName} for the sync operation request type. * * Example: For ListTables operation, it will be "ListTablesRequest" class. */ private ClassName requestType() { return poetExtensions.getModelClass(operationModel.getInput().getVariableType()); } /** * @return A Poet {@link ClassName} for the return type of sync non-paginated operation. * * Example: For ListTables operation, it will be "ListTablesResponse" class. */ private ClassName syncResponsePageType() { return poetExtensions.getModelClass(operationModel.getReturnType().getReturnType()); } /** * @return A Poet {@link ClassName} for the return type of sync paginated operation. */ private ClassName syncPaginatedResponseType() { return poetExtensions.getResponseClassForPaginatedSyncOperation(operationModel.getOperationName()); } /** * @return A Poet {@link ClassName} for the return type of Async paginated operation. */ private ClassName asyncPaginatedResponseType() { return poetExtensions.getResponseClassForPaginatedAsyncOperation(operationModel.getOperationName()); } private String getPaginatorLimitKeyName() { return paginatorDefinition != null ? paginatorDefinition.getLimitKey() : ""; } private CodeBlock noteAboutLimitConfigurationMethod() { return CodeBlock.builder() .add("\n<p><b>Please notice that the configuration of $L won't limit the number of results " + "you get with the paginator. It only limits the number of results in each page.</b></p>", getPaginatorLimitKeyName()) .build(); } private CodeBlock noteAboutSyncNonPaginatedMethod() { return CodeBlock.builder() .add("\n<p><b>Note: If you prefer to have control on service calls, use the {@link #$L($T)} operation." + "</b></p>", operationModel.getMethodName(), requestType()) .build(); } /** * @return A Poet {@link ClassName} for the reactive streams {@link Publisher}. */ private ClassName getPublisherType() { return ClassName.get(Publisher.class); } /** * @return A Poet {@link ClassName} for the reactive streams {@link Subscriber}. */ private ClassName getSubscriberType() { return ClassName.get(Subscriber.class); } /** * @return A Poet {@link ClassName} for the reactive streams {@link Subscription}. */ private ClassName getSubscriptionType() { return ClassName.get(Subscription.class); } }
3,493
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/docs/SimpleMethodOverload.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.docs; import software.amazon.awssdk.codegen.docs.AsyncOperationDocProvider.AsyncFile; import software.amazon.awssdk.codegen.docs.AsyncOperationDocProvider.AsyncNoArg; import software.amazon.awssdk.codegen.docs.AsyncOperationDocProvider.AsyncPaginated; import software.amazon.awssdk.codegen.docs.AsyncOperationDocProvider.AsyncPaginatedNoArg; import software.amazon.awssdk.codegen.docs.SyncOperationDocProvider.SyncBytes; import software.amazon.awssdk.codegen.docs.SyncOperationDocProvider.SyncFile; import software.amazon.awssdk.codegen.docs.SyncOperationDocProvider.SyncInputStream; import software.amazon.awssdk.codegen.docs.SyncOperationDocProvider.SyncNoArg; import software.amazon.awssdk.codegen.docs.SyncOperationDocProvider.SyncPaginated; import software.amazon.awssdk.codegen.docs.SyncOperationDocProvider.SyncPaginatedNoArg; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.ResponseInputStream; /** * Enum describing all the convenience overloads we generate for operation methods. */ public enum SimpleMethodOverload { /** * The standard method overload. For non-streaming sync this is the method that take * in a request object and returns a response object. */ NORMAL(SyncOperationDocProvider::new, AsyncOperationDocProvider::new), /** * The standard paginated method overload that takes in a request object and returns a response object. */ PAGINATED(SyncPaginated::new, AsyncPaginated::new), /** * Simple method that takes no arguments and creates an empty request object that delegates to the {@link #NORMAL} overload. */ NO_ARG(SyncNoArg::new, AsyncNoArg::new), /** * Paginated simple method that takes no arguments and creates an empty request object. */ NO_ARG_PAGINATED(SyncPaginatedNoArg::new, AsyncPaginatedNoArg::new), /** * Simple method for streaming operations (input or output) that takes in the request object and a file to * upload from or download to. */ FILE(SyncFile::new, AsyncFile::new), /** * Simple method only for sync operations that have a streaming output. Takes a request object * and returns an unmanaged {@link ResponseInputStream} to read the response * contents. */ INPUT_STREAM(SyncInputStream::new, null), /** * Simple method only for sync operations that have a streaming output. Takes a request object and return a * {@link ResponseBytes} to give byte-buffer access and convenience methods for type conversion. */ BYTES(SyncBytes::new, null); private final Factory syncDocsFactory; private final Factory asyncDocsFactory; SimpleMethodOverload(Factory syncDocsFactory, Factory asyncDocsFactory) { this.syncDocsFactory = syncDocsFactory; this.asyncDocsFactory = asyncDocsFactory; } public OperationDocProvider syncDocsProvider(IntermediateModel model, OperationModel opModel, DocConfiguration docConfiguration) { if (syncDocsFactory == null) { throw new UnsupportedOperationException(this + " is not currently documented for sync clients."); } return syncDocsFactory.create(model, opModel, docConfiguration); } public OperationDocProvider asyncDocsProvider(IntermediateModel model, OperationModel opModel, DocConfiguration docConfiguration) { if (asyncDocsFactory == null) { throw new UnsupportedOperationException(this + " is not currently documented for async clients."); } return asyncDocsFactory.create(model, opModel, docConfiguration); } }
3,494
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/docs/OperationDocProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.docs; import static software.amazon.awssdk.codegen.internal.DocumentationUtils.createLinkToServiceDocumentation; import static software.amazon.awssdk.codegen.internal.DocumentationUtils.stripHtmlTags; import com.squareup.javapoet.ClassName; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.codegen.model.intermediate.DocumentationModel; 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.service.PaginatorDefinition; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringUtils; /** * Base class for providers of documentation for operation methods. */ abstract class OperationDocProvider { /** * Doc string for {@link java.nio.file.Path} parameter in simple method overload for streaming input operations. */ static final String SIMPLE_FILE_INPUT_DOCS = "{@link Path} to file containing data to send to the service. File will be read entirely and " + "may be read multiple times in the event of a retry. If the file does not exist or the " + "current user does not have access to read it then an exception will be thrown. "; /** * Doc string for {@link java.nio.file.Path} parameter in simple method overload for streaming output operations. */ static final String SIMPLE_FILE_OUTPUT_DOCS = "{@link Path} to file that response contents will be written to. The file must not exist or " + "this method will throw an exception. If the file is not writable by the current user then " + "an exception will be thrown. "; protected final IntermediateModel model; protected final OperationModel opModel; protected final DocConfiguration config; protected final PaginationDocs paginationDocs; OperationDocProvider(IntermediateModel model, OperationModel opModel, DocConfiguration config) { this.model = model; this.opModel = opModel; this.config = config; this.paginationDocs = new PaginationDocs(model, opModel, getPaginatorDefinition()); } /** * @return Constructs the Javadoc for this operation method overload. */ String getDocs() { DocumentationBuilder docBuilder = new DocumentationBuilder(); String description = StringUtils.isNotBlank(opModel.getDocumentation()) ? opModel.getDocumentation() : getDefaultServiceDocs(); String appendedDescription = appendToDescription(); if (config.isConsumerBuilder()) { appendedDescription += getConsumerBuilderDocs(); } docBuilder.description(StringUtils.isNotBlank(appendedDescription) ? description + "<br/>" + appendedDescription : description); applyParams(docBuilder); applyReturns(docBuilder); applyThrows(docBuilder); docBuilder.tag("sample", getInterfaceName() + "." + opModel.getOperationName()); String crosslink = createLinkToServiceDocumentation(model.getMetadata(), opModel.getOperationName()); if (!crosslink.isEmpty()) { docBuilder.see(crosslink); } return docBuilder.build().replace("$", "&#36"); } /** * @return A string that will be appended to the standard description. */ protected String appendToDescription() { return ""; } /** * @return Documentation describing the streaming input parameter. Uses documentation for the streaming member in the model. */ final String getStreamingInputDocs() { return String.format("The service documentation for the request content is as follows '%s'", getStreamingMemberDocs(opModel.getInputShape())); } /** * @return Documentation describing the streaming output parameter. Uses documentation for the streaming member in the model. */ final String getStreamingOutputDocs() { return String.format("The service documentation for the response content is as follows '%s'.", getStreamingMemberDocs(opModel.getOutputShape())); } /** * @return Documentation describing the consumer-builder variant of a method. */ private String getConsumerBuilderDocs() { return "<p>This is a convenience which creates an instance of the {@link " + opModel.getInput().getSimpleType() + ".Builder} avoiding the need to create one manually via {@link " + opModel.getInput().getSimpleType() + "#builder()}</p>"; } /** * Gets the member documentation (as defined in the C2J model) for the streaming member of a shape. * * @param streamingShape Shape containing streaming member. * @return Documentation for the streaming member in the given Shape. * @throws IllegalStateException if shape does not have streaming member. */ private String getStreamingMemberDocs(ShapeModel streamingShape) { return streamingShape.getMembers().stream() .filter(m -> m.getHttp().getIsStreaming()) .map(DocumentationModel::getDocumentation) .findFirst() .orElseThrow(() -> new IllegalStateException( "Streaming member not found in " + streamingShape.getShapeName())); } /** * @return List of thrown exceptions for the given operation. Includes both modeled exceptions and SDK base exceptions. */ final List<Pair<String, String>> getThrows() { List<Pair<String, String>> throwsDocs = opModel.getExceptions().stream() .map(exception -> Pair.of(exception.getExceptionName(), stripHtmlTags(exception.getDocumentation()))) .collect(Collectors.toList()); String baseServiceException = model.getMetadata().getBaseExceptionName(); Collections.addAll(throwsDocs, Pair.of("SdkException ", "Base class for all exceptions that can be thrown by the SDK " + "(both service and client). Can be used for catch all scenarios."), Pair.of("SdkClientException ", "If any client side error occurs such as an IO related failure, " + "failure to get credentials, etc."), Pair.of(baseServiceException, "Base class for all service exceptions. Unknown exceptions will be " + "thrown as an instance of this type.")); return throwsDocs; } /** * Emits documentation for the request object to the {@link DocumentationBuilder}. * * @param docBuilder {@link DocumentationBuilder} to emit param to. */ final void emitRequestParm(DocumentationBuilder docBuilder) { String parameterDocs = stripHtmlTags(opModel.getInput().getDocumentation()); String shapeName = opModel.getInputShape().getShapeName(); ClassName fcqn = ClassName.get(model.getMetadata().getFullModelPackageName(), shapeName); if (config.isConsumerBuilder()) { docBuilder.param(opModel.getInput().getVariableName(), "A {@link Consumer} that will call methods on {@link %s.Builder} to create a request. %s", fcqn.toString(), parameterDocs); } else { docBuilder.param(opModel.getInput().getVariableName(), parameterDocs); } } private PaginatorDefinition getPaginatorDefinition() { return model.getPaginators().get(opModel.getOperationName()); } /** * @return The interface name of the client. Will differ per {@link ClientType}. */ protected abstract String getInterfaceName(); /** * @return Default documentation to put in {@link DocumentationBuilder#description(String)} when no service docs are present. * Will differ per {@link ClientType}. */ protected abstract String getDefaultServiceDocs(); /** * Add any relevant params to the {@link DocumentationBuilder}. Depends on {@link ClientType} and which overload we are * generating documentation for. * * @param docBuilder {@link DocumentationBuilder} to add params to. */ protected abstract void applyParams(DocumentationBuilder docBuilder); /** * Add documentation describing the return value (if any). * * @param docBuilder {@link DocumentationBuilder} to add return documentation for. */ protected abstract void applyReturns(DocumentationBuilder docBuilder); /** * Adds documentation describing the thrown exceptions (if any). * * @param docBuilder {@link DocumentationBuilder} to add throws documentation for. */ protected abstract void applyThrows(DocumentationBuilder docBuilder); }
3,495
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/docs/Factory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.docs; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; /** * Factory interface for creating an instance of {@link OperationDocProvider}. */ @FunctionalInterface interface Factory { OperationDocProvider create(IntermediateModel model, OperationModel opModel, DocConfiguration config); }
3,496
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/docs/DocConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.docs; /** * Configuration for generation in a {@link OperationDocProvider}. */ public class DocConfiguration { /** * Whether the documentation should be generated for a consumer builder method. */ private boolean isConsumerBuilder = false; public DocConfiguration isConsumerBuilder(boolean isConsumerBuilder) { this.isConsumerBuilder = isConsumerBuilder; return this; } public boolean isConsumerBuilder() { return isConsumerBuilder; } }
3,497
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/docs/WaiterDocs.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.docs; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import software.amazon.awssdk.codegen.model.intermediate.OperationModel; import software.amazon.awssdk.codegen.model.service.WaiterDefinition; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; public final class WaiterDocs { private WaiterDocs() { } public static String waiterInterfaceJavadoc() { return "Waiter utility class that polls a resource until a desired state is reached or until it is " + "determined that the resource will never enter into the desired state. This can be" + " created using the static {@link #builder()} method"; } public static CodeBlock waiterOperationJavadoc(ClassName className, Map.Entry<String, WaiterDefinition> waiterDefinition, OperationModel operationModel) { String returnStatement = "WaiterResponse containing either a response or an exception that has matched with the waiter " + "success condition"; String asyncReturnStatement = "CompletableFuture containing the WaiterResponse. It completes successfully when the " + "resource enters into a desired state or exceptionally when it is determined that the " + "resource will never enter into the desired state."; String javadocs = new DocumentationBuilder().description("Polls {@link $T#$N} API until the desired condition " + "{@code $N} is met, " + "or until it is determined that the resource will never " + "enter into the desired state") .param(operationModel.getInput().getVariableName(), "the request to be used" + " for polling") .returns(className.simpleName().contains("Async") ? asyncReturnStatement : returnStatement) .build(); return CodeBlock.builder() .add(javadocs, className, operationModel.getMethodName(), waiterDefinition.getKey()) .build(); } public static CodeBlock waiterOperationConsumerBuilderJavadoc(ClassName clientClassName, ClassName requestClassName, Map.Entry<String, WaiterDefinition> waiterDefinition, OperationModel operationModel) { String javadocs = new DocumentationBuilder().description("Polls {@link $T#$N} API until the desired condition " + "{@code $N} is met, " + "or until it is determined that the resource will never " + "enter into the desired state. \n " + "<p>This is a convenience method to create an instance of " + "the request builder without the need " + "to create one manually using {@link $T#builder()} ") .param(operationModel.getInput().getVariableName(), "The consumer that will" + " configure the " + "request to be used" + " for polling") .returns(clientClassName.simpleName().contains("Async") ? "CompletableFuture of the WaiterResponse containing either a " + "response or an exception that has matched with the waiter " + "success condition" : "WaiterResponse containing either a response or an exception that" + " has matched with the waiter success condition") .build(); return CodeBlock.builder() .add(javadocs, clientClassName, operationModel.getMethodName(), waiterDefinition.getKey(), requestClassName) .build(); } public static CodeBlock waiterBuilderMethodJavadoc(ClassName className) { String javadocs = new DocumentationBuilder() .description("Create a builder that can be used to configure and create a {@link $T}.") .returns("a builder") .build(); return CodeBlock.builder() .add(javadocs, className) .build(); } public static CodeBlock waiterCreateMethodJavadoc(ClassName waiterClassName, ClassName clientClassName) { String javadocs = new DocumentationBuilder() .description("Create an instance of {@link $T} with the default configuration. \n" + "<p><b>A default {@link $T} will be created to poll resources. It is recommended " + "to share a single instance of the waiter created via this method. If it is not desirable " + "to share a waiter instance, invoke {@link #close()} to release the resources once the waiter" + " is not needed.</b>") .returns("an instance of {@link $T}") .build(); return CodeBlock.builder() .add(javadocs, waiterClassName, clientClassName, waiterClassName) .build(); } public static CodeBlock waiterBuilderPollingStrategy() { String javadocs = new DocumentationBuilder() .description("Defines overrides to the default SDK waiter configuration that should be used for waiters created " + "from this builder") .param("overrideConfiguration", "the override configuration to set") .returns("a reference to this object so that method calls can be chained together.") .build(); return CodeBlock.builder() .add(javadocs) .build(); } public static CodeBlock waiterBuilderPollingStrategyConsumerBuilder() { String javadocs = new DocumentationBuilder() .description("This is a convenient method to pass the override configuration without the need to " + "create an instance manually via {@link $T#builder()}") .param("overrideConfiguration", "The consumer that will configure the overrideConfiguration") .see("#overrideConfiguration(WaiterOverrideConfiguration)") .returns("a reference to this object so that method calls can be chained together.") .build(); return CodeBlock.builder() .add(javadocs, ClassName.get(WaiterOverrideConfiguration.class)) .build(); } public static CodeBlock waiterBuilderScheduledExecutorServiceJavadoc() { String javadocs = new DocumentationBuilder() .description("Sets a custom {@link $T} that will be used to schedule async polling attempts \n " + "<p> This executorService must be closed by the caller when it is ready to be disposed. The" + " SDK will not close the executorService when the waiter is closed") .param("executorService", "the executorService to set") .returns("a reference to this object so that method calls can be chained together.") .build(); return CodeBlock.builder() .add(javadocs, ClassName.get(ScheduledExecutorService.class)) .build(); } public static CodeBlock waiterBuilderClientJavadoc(ClassName className) { String javadocs = new DocumentationBuilder() .description("Defines the {@link $T} to use when polling a resource") .description("Sets a custom {@link $T} that will be used to poll the resource \n " + "<p> This SDK client must be closed by the caller when it is ready to be disposed. The" + " SDK will not close the client when the waiter is closed") .param("client", "the client to send the request") .returns("a reference to this object so that method calls can be chained together.") .build(); return CodeBlock.builder() .add(javadocs, className) .build(); } public static CodeBlock waiterBuilderBuildJavadoc(ClassName className) { String javadocs = new DocumentationBuilder() .description("Builds an instance of {@link $T} based on the configurations supplied to this builder ") .returns("An initialized {@link $T}") .build(); return CodeBlock.builder() .add(javadocs, className, className) .build(); } public static CodeBlock waiterOperationWithOverrideConfigConsumerBuilder(ClassName clientClassName, ClassName requestClassName, Map.Entry<String, WaiterDefinition> waiterDefinition, OperationModel opModel) { String javadocs = new DocumentationBuilder().description("Polls {@link $T#$N} API until the desired condition " + "{@code $N} is met, " + "or until it is determined that the resource will never " + "enter into the desired state. \n " + "<p>This is a convenience method to create an instance of " + "the request builder and instance of the override config " + "builder") .param(opModel.getInput().getVariableName(), "The consumer that will configure the request to be used for polling") .param("overrideConfig", "The consumer that will configure the per request override " + "configuration for waiters") .returns("WaiterResponse containing either a response or an exception that " + "has matched with the waiter success condition") .build(); return CodeBlock.builder() .add(javadocs, clientClassName, opModel.getMethodName(), waiterDefinition.getKey()) .build(); } public static CodeBlock waiterOperationWithOverrideConfig(ClassName clientClassName, Map.Entry<String, WaiterDefinition> waiterDefinition, OperationModel opModel) { String javadocs = new DocumentationBuilder().description("Polls {@link $T#$N} API until the desired condition " + "{@code $N} is met, " + "or until it is determined that the resource will never " + "enter into the desired state") .param(opModel.getInput().getVariableName(), "The request to be" + " used" + " for polling") .param("overrideConfig", "Per request " + "override configuration for waiters") .returns("WaiterResponse containing either a response or an exception that " + "has matched with the waiter success condition") .build(); return CodeBlock.builder() .add(javadocs, clientClassName, opModel.getMethodName(), waiterDefinition.getKey()) .build(); } public static CodeBlock waiterMethodInClient(ClassName waiterClassName) { String javadocs = new DocumentationBuilder() .description("Create an instance of {@link $T} using this client. \n" + "<p>Waiters created via this method are managed by the SDK and resources will be released " + "when the service client is closed.") .returns("an instance of {@link $T}") .build(); return CodeBlock.builder() .add(javadocs, waiterClassName, waiterClassName) .build(); } }
3,498
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/docs/ClientType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.docs; /** * Enum that identifies the generated client type. Used for doc generation. */ public enum ClientType { /** * Synchronous/blocking client */ SYNC, /** * Asynchronous/non-blocking client */ ASYNC }
3,499