Search in sources :

Example 76 with MethodInvocationExpr

use of com.google.api.generator.engine.ast.MethodInvocationExpr in project gapic-generator-java by googleapis.

the class HttpJsonServiceStubClassComposer method setOperationSnapshotFactoryExpr.

private List<Expr> setOperationSnapshotFactoryExpr(Method protoMethod, Map<String, Message> messageTypes) {
    // Generate input variables for create()
    VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(protoMethod.inputType()).setName("request").build());
    VariableExpr responseVarExpr = VariableExpr.withVariable(Variable.builder().setType(protoMethod.outputType()).setName("response").build());
    MethodInvocationExpr buildExpr;
    List<Statement> createBody = new ArrayList<>(4);
    TypeNode httpJsonOperationSnapshotType = FIXED_REST_TYPESTORE.get(HttpJsonOperationSnapshot.class.getSimpleName());
    TypeNode operationSnapshotType = FIXED_TYPESTORE.get(OperationSnapshot.class.getSimpleName());
    Message inputOperationMessage = messageTypes.get(protoMethod.inputType().reference().fullName());
    Message outputOperationMessage = messageTypes.get(protoMethod.outputType().reference().fullName());
    OperationResponse operationResponse = outputOperationMessage.operationResponse();
    if (operationResponse == null) {
        // AIP-151 LRO
        // HttpJsonOperationSnapshot.create(response)
        buildExpr = MethodInvocationExpr.builder().setStaticReferenceType(httpJsonOperationSnapshotType).setMethodName("create").setArguments(responseVarExpr).setReturnType(operationSnapshotType).build();
    } else {
        BiFunction<String, List<Expr>, Function<MethodInvocationExpr, MethodInvocationExpr>> methodMaker = getMethodMaker();
        // Generate opName
        TypeNode stringBuilderType = TypeNode.withReference(ConcreteReference.withClazz(StringBuilder.class));
        VariableExpr opNameVarExpr = VariableExpr.withVariable(Variable.builder().setType(stringBuilderType).setName("opName").build());
        MethodInvocationExpr getId = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.nameFieldName())).build();
        Expr opNameObjectExpr = NewObjectExpr.builder().setType(stringBuilderType).setArguments(getId).build();
        AssignmentExpr opNameAssignExpr = AssignmentExpr.builder().setVariableExpr(opNameVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(opNameObjectExpr).build();
        createBody.add(ExprStatement.withExpr(opNameAssignExpr));
        // Generate compound operation name
        if (!protoMethod.isOperationPollingMethod()) {
            // TODO: Change to ordered map
            Map<String, String> requestFields = inputOperationMessage.operationRequestFields();
            List<String> fieldAnnotationNames = new ArrayList<>(requestFields.keySet());
            Collections.sort(fieldAnnotationNames);
            for (String fieldName : fieldAnnotationNames) {
                createBody.add(appendField(opNameVarExpr, requestVarExpr, requestFields.get(fieldName)));
            }
        }
        // Generate check for status == done
        MethodInvocationExpr getStatusExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.statusFieldName())).build();
        String statusTypeName = operationResponse.statusFieldTypeName();
        String statusClassName = statusTypeName.substring(statusTypeName.lastIndexOf('.') + 1);
        TypeNode opType = protoMethod.hasLro() ? protoMethod.lro().responseType() : protoMethod.outputType();
        TypeNode statusType = TypeNode.withReference(VaporReference.builder().setName(statusClassName).setPakkage(opType.reference().fullName()).setIsStaticImport(false).build());
        VariableExpr statusDoneExpr = VariableExpr.builder().setVariable(Variable.builder().setName("DONE").setType(TypeNode.INT).build()).setStaticReferenceType(statusType).build();
        MethodInvocationExpr statusEqualsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(statusDoneExpr).setMethodName("equals").setArguments(getStatusExpr).build();
        // Generate return statement
        // Generate getter methods from annotations
        MethodInvocationExpr opNameToStringExpr = MethodInvocationExpr.builder().setExprReferenceExpr(opNameVarExpr).setMethodName("toString").build();
        MethodInvocationExpr getHttpErrorStatusCodeExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.errorCodeFieldName())).build();
        MethodInvocationExpr getHttpErrorMessageExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.errorMessageFieldName())).build();
        MethodInvocationExpr newBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(httpJsonOperationSnapshotType).setMethodName("newBuilder").build();
        newBuilderExpr = methodMaker.apply("setName", Collections.singletonList(opNameToStringExpr)).apply(newBuilderExpr);
        newBuilderExpr = methodMaker.apply("setMetadata", Collections.singletonList(responseVarExpr)).apply(newBuilderExpr);
        newBuilderExpr = methodMaker.apply("setDone", Collections.singletonList(statusEqualsExpr)).apply(newBuilderExpr);
        newBuilderExpr = methodMaker.apply("setResponse", Collections.singletonList(responseVarExpr)).apply(newBuilderExpr);
        newBuilderExpr = methodMaker.apply("setError", Arrays.asList(getHttpErrorStatusCodeExpr, getHttpErrorMessageExpr)).apply(newBuilderExpr);
        buildExpr = MethodInvocationExpr.builder().setExprReferenceExpr(newBuilderExpr).setMethodName("build").setReturnType(operationSnapshotType).build();
    }
    // Generate lambda anonymous class
    return Collections.singletonList(LambdaExpr.builder().setArguments(requestVarExpr.toBuilder().setIsDecl(true).build(), responseVarExpr.toBuilder().setIsDecl(true).build()).setBody(createBody).setReturnExpr(buildExpr).build());
}
Also used : Message(com.google.api.generator.gapic.model.Message) IfStatement(com.google.api.generator.engine.ast.IfStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) ArrayList(java.util.ArrayList) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) HttpJsonOperationSnapshot(com.google.api.gax.httpjson.HttpJsonOperationSnapshot) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) TypeNode(com.google.api.generator.engine.ast.TypeNode) OperationSnapshot(com.google.api.gax.longrunning.OperationSnapshot) HttpJsonOperationSnapshot(com.google.api.gax.httpjson.HttpJsonOperationSnapshot) OperationResponse(com.google.api.generator.gapic.model.OperationResponse)

Example 77 with MethodInvocationExpr

use of com.google.api.generator.engine.ast.MethodInvocationExpr in project gapic-generator-java by googleapis.

the class ServiceStubSettingsClassComposer method createDefaultCredentialsProviderBuilderMethod.

@Override
protected MethodDefinition createDefaultCredentialsProviderBuilderMethod() {
    TypeNode returnType = TypeNode.withReference(ConcreteReference.withClazz(GoogleCredentialsProvider.Builder.class));
    MethodInvocationExpr credsProviderBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("GoogleCredentialsProvider")).setMethodName("newBuilder").build();
    credsProviderBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(credsProviderBuilderExpr).setMethodName("setScopesToApply").setArguments(DEFAULT_SERVICE_SCOPES_VAR_EXPR).setReturnType(returnType).build();
    // This section is specific to GAPIC clients. It sets UseJwtAccessWithScope value to true to
    // enable self signed JWT feature.
    credsProviderBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(credsProviderBuilderExpr).setMethodName("setUseJwtAccessWithScope").setArguments(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.BOOLEAN).setValue("true").build())).setReturnType(returnType).build();
    return MethodDefinition.builder().setHeaderCommentStatements(SettingsCommentComposer.DEFAULT_CREDENTIALS_PROVIDER_BUILDER_METHOD_COMMENT).setScope(ScopeNode.PUBLIC).setIsStatic(true).setReturnType(returnType).setName("defaultCredentialsProviderBuilder").setReturnExpr(credsProviderBuilderExpr).build();
}
Also used : MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 78 with MethodInvocationExpr

use of com.google.api.generator.engine.ast.MethodInvocationExpr in project gapic-generator-java by googleapis.

the class ResourceNameHelperClassComposer method createConstructorMethods.

private static List<MethodDefinition> createConstructorMethods(ResourceName resourceName, List<VariableExpr> templateFinalVarExprs, Map<String, VariableExpr> patternTokenVarExprs, List<List<String>> tokenHierarchies, TypeStore typeStore) {
    String thisClassName = getThisClassName(resourceName);
    TypeNode thisClassType = typeStore.get(thisClassName);
    boolean hasVariants = tokenHierarchies.size() > 1;
    List<MethodDefinition> javaMethods = new ArrayList<>();
    final ValueExpr nullExpr = ValueExpr.createNullExpr();
    Function<String, AssignmentExpr> assignTokenToNullExpr = t -> AssignmentExpr.builder().setVariableExpr(patternTokenVarExprs.get(t)).setValueExpr(nullExpr).build();
    // Special-cased PubSub handling.
    List<List<String>> processedTokenHierarchies = tokenHierarchies.stream().filter(tokens -> !tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)).collect(Collectors.toList());
    boolean hasDeletedTopicPattern = tokenHierarchies.size() > processedTokenHierarchies.size();
    // First deprecated constructor.
    javaMethods.add(MethodDefinition.constructorBuilder().setAnnotations(Arrays.asList(AnnotationNode.withType(TypeNode.withReference(ConcreteReference.withClazz(Deprecated.class))))).setScope(ScopeNode.PROTECTED).setReturnType(thisClassType).setBody(getTokenSet(processedTokenHierarchies).stream().map(t -> ExprStatement.withExpr(assignTokenToNullExpr.apply(t))).collect(Collectors.toList())).build());
    for (int i = 0; i < processedTokenHierarchies.size(); i++) {
        List<String> tokens = processedTokenHierarchies.get(i);
        List<Expr> bodyExprs = new ArrayList<>();
        TypeNode argType = getBuilderType(typeStore, processedTokenHierarchies, i);
        VariableExpr builderArgExpr = VariableExpr.withVariable(Variable.builder().setName("builder").setType(argType).build());
        for (String token : tokens) {
            MethodInvocationExpr checkNotNullExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Preconditions")).setMethodName("checkNotNull").setReturnType(TypeNode.STRING).setArguments(Arrays.asList(MethodInvocationExpr.builder().setExprReferenceExpr(builderArgExpr).setMethodName(String.format("get%s", JavaStyle.toUpperCamelCase(token))).build())).build();
            bodyExprs.add(AssignmentExpr.builder().setVariableExpr(patternTokenVarExprs.get(token)).setValueExpr(checkNotNullExpr).build());
        }
        // Initialize the rest to null.
        for (String token : getTokenSet(processedTokenHierarchies)) {
            if (tokens.contains(token)) {
                continue;
            }
            bodyExprs.add(assignTokenToNullExpr.apply(token));
        }
        if (hasVariants) {
            AssignmentExpr pathTemplateAssignExpr = AssignmentExpr.builder().setVariableExpr(FIXED_CLASS_VARS.get("pathTemplate")).setValueExpr(templateFinalVarExprs.get(i)).build();
            bodyExprs.add(pathTemplateAssignExpr);
        }
        // Private constructor.
        javaMethods.add(MethodDefinition.constructorBuilder().setScope(ScopeNode.PRIVATE).setReturnType(thisClassType).setArguments(Arrays.asList(builderArgExpr.toBuilder().setIsDecl(true).build())).setBody(bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build());
    }
    if (hasDeletedTopicPattern) {
        Expr thisExpr = ValueExpr.withValue(ThisObjectValue.withType(thisClassType));
        // PubSub special-case handling for the _deleted-topic_ pattern - add an extra constructor.
        // private TopicName(String fixedValue) {
        // this.fixedValue = fixedValue;
        // fieldValuesMap = ImmutableMap.of("", fixedValue);
        // }
        VariableExpr fixedValueVarExpr = VariableExpr.withVariable(Variable.builder().setName("fixedValue").setType(TypeNode.STRING).build());
        List<Expr> specialCtorBodyExprs = new ArrayList<>();
        specialCtorBodyExprs.add(AssignmentExpr.builder().setVariableExpr(VariableExpr.builder().setExprReferenceExpr(thisExpr).setVariable(fixedValueVarExpr.variable()).build()).setValueExpr(fixedValueVarExpr).build());
        specialCtorBodyExprs.add(AssignmentExpr.builder().setVariableExpr(FIXED_CLASS_VARS.get("fieldValuesMap")).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")).setMethodName("of").setArguments(ValueExpr.withValue(StringObjectValue.withValue("")), fixedValueVarExpr).setReturnType(FIXED_TYPESTORE.get("ImmutableMap")).build()).build());
        specialCtorBodyExprs.addAll(getTokenSet(processedTokenHierarchies).stream().map(t -> assignTokenToNullExpr.apply(t)).collect(Collectors.toList()));
        javaMethods.add(MethodDefinition.constructorBuilder().setScope(ScopeNode.PRIVATE).setReturnType(thisClassType).setArguments(Arrays.asList(fixedValueVarExpr.toBuilder().setIsDecl(true).build())).setBody(specialCtorBodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build());
    }
    return javaMethods;
}
Also used : Arrays(java.util.Arrays) Reference(com.google.api.generator.engine.ast.Reference) PathTemplate(com.google.api.pathtemplate.PathTemplate) ThisObjectValue(com.google.api.generator.engine.ast.ThisObjectValue) Variable(com.google.api.generator.engine.ast.Variable) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) Generated(javax.annotation.Generated) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) CommentComposer(com.google.api.generator.gapic.composer.comment.CommentComposer) Map(java.util.Map) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) ImmutableMap(com.google.common.collect.ImmutableMap) ForStatement(com.google.api.generator.engine.ast.ForStatement) Set(java.util.Set) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ResourceNameConstants(com.google.api.generator.gapic.utils.ResourceNameConstants) List(java.util.List) GapicContext(com.google.api.generator.gapic.model.GapicContext) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) IfStatement(com.google.api.generator.engine.ast.IfStatement) BetaApi(com.google.api.core.BetaApi) TypeNode(com.google.api.generator.engine.ast.TypeNode) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) HashMap(java.util.HashMap) JavaDocComment(com.google.api.generator.engine.ast.JavaDocComment) Function(java.util.function.Function) ArrayList(java.util.ArrayList) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) ValidationException(com.google.api.pathtemplate.ValidationException) LinkedHashSet(java.util.LinkedHashSet) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) Iterator(java.util.Iterator) CastExpr(com.google.api.generator.engine.ast.CastExpr) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) GapicClass(com.google.api.generator.gapic.model.GapicClass) ResourceName(com.google.api.generator.gapic.model.ResourceName) Statement(com.google.api.generator.engine.ast.Statement) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ArrayList(java.util.ArrayList) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) CastExpr(com.google.api.generator.engine.ast.CastExpr) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) List(java.util.List) ArrayList(java.util.ArrayList) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 79 with MethodInvocationExpr

use of com.google.api.generator.engine.ast.MethodInvocationExpr in project gapic-generator-java by googleapis.

the class ResourceNameHelperClassComposer method createNestedBuilderClass.

private static ClassDefinition createNestedBuilderClass(TypeNode outerClassType, List<String> tokens, VariableExpr templateFinalVarExpr, String resourceNamePattern, TypeStore typeStore, boolean hasVariants, boolean isDefaultClass) {
    String className = isDefaultClass ? "Builder" : getBuilderTypeName(tokens);
    // Class member declarations.
    List<VariableExpr> classMemberVarExprs = tokens.stream().map(t -> VariableExpr.withVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(t)).setType(TypeNode.STRING).build())).collect(Collectors.toList());
    List<Statement> classMemberDecls = classMemberVarExprs.stream().map(v -> ExprStatement.withExpr(v.toBuilder().setIsDecl(true).setScope(ScopeNode.PRIVATE).build())).collect(Collectors.toList());
    // Constructor.
    List<MethodDefinition> nestedClassMethods = new ArrayList<>();
    TypeNode thisClassType = typeStore.get(className);
    MethodDefinition ctor = MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(thisClassType).build();
    nestedClassMethods.add(ctor);
    // Getters and setters.
    List<MethodDefinition> getterMethods = new ArrayList<>();
    List<MethodDefinition> setterMethods = new ArrayList<>();
    ValueExpr thisExpr = ValueExpr.withValue(ThisObjectValue.withType(thisClassType));
    for (int i = 0; i < tokens.size(); i++) {
        String token = tokens.get(i);
        String upperCamelTokenName = JavaStyle.toUpperCamelCase(token);
        VariableExpr currClassTokenVarExpr = classMemberVarExprs.get(i);
        // Getter.
        MethodDefinition getterMethod = MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.STRING).setName(String.format("get%s", upperCamelTokenName)).setReturnExpr(currClassTokenVarExpr).build();
        getterMethods.add(getterMethod);
        // Setter.
        VariableExpr tokenArgVarExpr = currClassTokenVarExpr;
        AssignmentExpr fieldAssignExpr = AssignmentExpr.builder().setVariableExpr(currClassTokenVarExpr.toBuilder().setExprReferenceExpr(thisExpr).build()).setValueExpr(tokenArgVarExpr).build();
        MethodDefinition setterMethod = MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setReturnType(thisClassType).setName(String.format("set%s", upperCamelTokenName)).setArguments(classMemberVarExprs.get(i).toBuilder().setIsDecl(true).build()).setBody(Arrays.asList(ExprStatement.withExpr(fieldAssignExpr))).setReturnExpr(thisExpr).build();
        setterMethods.add(setterMethod);
    }
    nestedClassMethods.addAll(getterMethods);
    nestedClassMethods.addAll(setterMethods);
    // Private builder constructor method.
    if (isDefaultClass) {
        VariableExpr outerClassVarExpr = VariableExpr.withVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(outerClassType.reference().name())).setType(outerClassType).build());
        List<Expr> builderCtorBodyExprs = new ArrayList<>();
        if (hasVariants) {
            // TODO(miraleung): Use eq operator instead.
            MethodInvocationExpr equalsCheckExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Objects")).setMethodName("equals").setArguments(FIXED_CLASS_VARS.get("pathTemplate").toBuilder().setExprReferenceExpr(outerClassVarExpr).build(), templateFinalVarExpr).build();
            builderCtorBodyExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Preconditions")).setMethodName("checkArgument").setArguments(equalsCheckExpr, ValueExpr.withValue(StringObjectValue.withValue(String.format("toBuilder is only supported when %s has the pattern of %s", outerClassType.reference().name(), resourceNamePattern)))).build());
        }
        for (VariableExpr memberVarExpr : classMemberVarExprs) {
            VariableExpr currClassTokenVarExpr = memberVarExpr.toBuilder().setExprReferenceExpr(thisExpr).build();
            builderCtorBodyExprs.add(AssignmentExpr.builder().setVariableExpr(currClassTokenVarExpr).setValueExpr(currClassTokenVarExpr.toBuilder().setExprReferenceExpr(outerClassVarExpr).build()).build());
        }
        MethodDefinition fromOuterTypeCtor = MethodDefinition.constructorBuilder().setScope(ScopeNode.PRIVATE).setReturnType(thisClassType).setArguments(outerClassVarExpr.toBuilder().setIsDecl(true).build()).setBody(builderCtorBodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build();
        nestedClassMethods.add(fromOuterTypeCtor);
    }
    // Last build() method.
    MethodDefinition buildMethod = MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setReturnType(outerClassType).setName("build").setReturnExpr(NewObjectExpr.builder().setType(outerClassType).setArguments(thisExpr).build()).build();
    nestedClassMethods.add(buildMethod);
    // Return the class.
    AnnotationNode betaAnnotation = AnnotationNode.builder().setType(FIXED_TYPESTORE.get("BetaApi")).setDescription("The per-pattern Builders are not stable yet and may be changed in the future.").build();
    List<AnnotationNode> classAnnotations = isDefaultClass ? Collections.emptyList() : Arrays.asList(betaAnnotation);
    return ClassDefinition.builder().setHeaderCommentStatements(CommentStatement.withComment(JavaDocComment.withComment(String.format(BUILDER_CLASS_HEADER_PATTERN, resourceNamePattern)))).setAnnotations(classAnnotations).setIsNested(true).setScope(ScopeNode.PUBLIC).setIsStatic(true).setName(className).setStatements(classMemberDecls).setMethods(nestedClassMethods).build();
}
Also used : Arrays(java.util.Arrays) Reference(com.google.api.generator.engine.ast.Reference) PathTemplate(com.google.api.pathtemplate.PathTemplate) ThisObjectValue(com.google.api.generator.engine.ast.ThisObjectValue) Variable(com.google.api.generator.engine.ast.Variable) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) Generated(javax.annotation.Generated) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) CommentComposer(com.google.api.generator.gapic.composer.comment.CommentComposer) Map(java.util.Map) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) ImmutableMap(com.google.common.collect.ImmutableMap) ForStatement(com.google.api.generator.engine.ast.ForStatement) Set(java.util.Set) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ResourceNameConstants(com.google.api.generator.gapic.utils.ResourceNameConstants) List(java.util.List) GapicContext(com.google.api.generator.gapic.model.GapicContext) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) IfStatement(com.google.api.generator.engine.ast.IfStatement) BetaApi(com.google.api.core.BetaApi) TypeNode(com.google.api.generator.engine.ast.TypeNode) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) HashMap(java.util.HashMap) JavaDocComment(com.google.api.generator.engine.ast.JavaDocComment) Function(java.util.function.Function) ArrayList(java.util.ArrayList) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) ValidationException(com.google.api.pathtemplate.ValidationException) LinkedHashSet(java.util.LinkedHashSet) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) Iterator(java.util.Iterator) CastExpr(com.google.api.generator.engine.ast.CastExpr) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) GapicClass(com.google.api.generator.gapic.model.GapicClass) ResourceName(com.google.api.generator.gapic.model.ResourceName) Statement(com.google.api.generator.engine.ast.Statement) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ForStatement(com.google.api.generator.engine.ast.ForStatement) IfStatement(com.google.api.generator.engine.ast.IfStatement) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) ArrayList(java.util.ArrayList) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) CastExpr(com.google.api.generator.engine.ast.CastExpr) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 80 with MethodInvocationExpr

use of com.google.api.generator.engine.ast.MethodInvocationExpr in project gapic-generator-java by googleapis.

the class ResourceNameHelperClassComposer method createToStringMethod.

private static MethodDefinition createToStringMethod(List<VariableExpr> templateFinalVarExprs, Map<String, VariableExpr> patternTokenVarExprs, List<List<String>> tokenHierarchies) {
    boolean hasVariants = tokenHierarchies.size() > 1;
    if (!hasVariants) {
        List<Expr> instantiateArgExprs = new ArrayList<>();
        List<String> tokens = getTokenSet(tokenHierarchies).stream().collect(Collectors.toList());
        for (String token : tokens) {
            Preconditions.checkNotNull(patternTokenVarExprs.get(token), String.format("No expression found for token %s amongst values %s", token, patternTokenVarExprs.toString()));
            instantiateArgExprs.add(ValueExpr.withValue(StringObjectValue.withValue(token)));
            instantiateArgExprs.add(patternTokenVarExprs.get(token));
        }
        MethodInvocationExpr returnInstantiateExpr = MethodInvocationExpr.builder().setExprReferenceExpr(templateFinalVarExprs.get(0)).setMethodName("instantiate").setArguments(instantiateArgExprs).setReturnType(TypeNode.STRING).build();
        return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.STRING).setName("toString").setReturnExpr(returnInstantiateExpr).build();
    }
    VariableExpr fixedValueVarExpr = FIXED_CLASS_VARS.get("fixedValue");
    // Code:  return fixedValue != null ? fixedValue : pathTemplate.instantiate(getFieldValuesMap())
    Expr fixedValueNullCheck = RelationalOperationExpr.notEqualToWithExprs(fixedValueVarExpr, ValueExpr.createNullExpr());
    MethodInvocationExpr instantiateExpr = MethodInvocationExpr.builder().setExprReferenceExpr(FIXED_CLASS_VARS.get("pathTemplate")).setMethodName("instantiate").setArguments(MethodInvocationExpr.builder().setMethodName("getFieldValuesMap").build()).setReturnType(TypeNode.STRING).build();
    TernaryExpr returnExpr = TernaryExpr.builder().setConditionExpr(fixedValueNullCheck).setElseExpr(instantiateExpr).setThenExpr(fixedValueVarExpr).build();
    return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.STRING).setName("toString").setReturnExpr(returnExpr).build();
}
Also used : LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) CastExpr(com.google.api.generator.engine.ast.CastExpr) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ArrayList(java.util.ArrayList) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr)

Aggregations

MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)103 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)76 TypeNode (com.google.api.generator.engine.ast.TypeNode)72 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)59 Expr (com.google.api.generator.engine.ast.Expr)50 ValueExpr (com.google.api.generator.engine.ast.ValueExpr)48 ArrayList (java.util.ArrayList)41 Variable (com.google.api.generator.engine.ast.Variable)39 NewObjectExpr (com.google.api.generator.engine.ast.NewObjectExpr)38 ExprStatement (com.google.api.generator.engine.ast.ExprStatement)36 Statement (com.google.api.generator.engine.ast.Statement)33 List (java.util.List)31 ConcreteReference (com.google.api.generator.engine.ast.ConcreteReference)29 Test (org.junit.Test)29 RelationalOperationExpr (com.google.api.generator.engine.ast.RelationalOperationExpr)27 MethodDefinition (com.google.api.generator.engine.ast.MethodDefinition)26 Arrays (java.util.Arrays)26 JavaStyle (com.google.api.generator.gapic.utils.JavaStyle)25 Map (java.util.Map)25 Function (java.util.function.Function)24