Search in sources :

Example 11 with ValueExpr

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

the class AbstractServiceClientClassComposer method createNestedRpcPageClass.

private static ClassDefinition createNestedRpcPageClass(Method method, TypeNode repeatedResponseType, Map<String, Message> messageTypes, TypeStore typeStore) {
    Preconditions.checkState(method.isPaged(), String.format("Expected method %s to be paged", method.name()));
    String upperJavaMethodName = JavaStyle.toUpperCamelCase(method.name());
    String className = String.format("%sPage", upperJavaMethodName);
    TypeNode classType = typeStore.get(className);
    TypeNode classExtendsType = TypeNode.withReference(ConcreteReference.builder().setClazz(AbstractPage.class).setGenerics(Arrays.asList(method.inputType(), method.outputType(), repeatedResponseType, classType).stream().map(t -> t.reference()).collect(Collectors.toList())).build());
    // Private constructor.
    VariableExpr contextVarExpr = VariableExpr.withVariable(Variable.builder().setName("context").setType(TypeNode.withReference(ConcreteReference.builder().setClazz(PageContext.class).setGenerics(Arrays.asList(method.inputType(), method.outputType(), repeatedResponseType).stream().map(t -> t.reference()).collect(Collectors.toList())).build())).build());
    VariableExpr responseVarExpr = VariableExpr.withVariable(Variable.builder().setName("response").setType(method.outputType()).build());
    MethodDefinition privateCtor = MethodDefinition.constructorBuilder().setScope(ScopeNode.PRIVATE).setReturnType(classType).setArguments(Arrays.asList(contextVarExpr, responseVarExpr).stream().map(e -> e.toBuilder().setIsDecl(true).build()).collect(Collectors.toList())).setBody(Arrays.asList(ExprStatement.withExpr(ReferenceConstructorExpr.superBuilder().setType(classExtendsType).setArguments(contextVarExpr, responseVarExpr).build()))).build();
    // createEmptyPage method.
    ValueExpr nullExpr = ValueExpr.createNullExpr();
    MethodDefinition createEmptyPageMethod = MethodDefinition.builder().setScope(ScopeNode.PRIVATE).setIsStatic(true).setReturnType(classType).setName("createEmptyPage").setReturnExpr(NewObjectExpr.builder().setType(classType).setArguments(nullExpr, nullExpr).build()).build();
    // createPage method.
    MethodDefinition createPageMethod = MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PROTECTED).setReturnType(classType).setName("createPage").setArguments(Arrays.asList(contextVarExpr, responseVarExpr).stream().map(e -> e.toBuilder().setIsDecl(true).build()).collect(Collectors.toList())).setReturnExpr(NewObjectExpr.builder().setType(classType).setArguments(contextVarExpr, responseVarExpr).build()).build();
    // createPageAsync method.
    Function<TypeNode, TypeNode> futureTypeFn = t -> TypeNode.withReference(ConcreteReference.builder().setClazz(ApiFuture.class).setGenerics(Arrays.asList(t.reference())).build());
    VariableExpr futureResponseVarExpr = VariableExpr.withVariable(Variable.builder().setName("futureResponse").setType(futureTypeFn.apply(method.outputType())).build());
    TypeNode futurePageType = futureTypeFn.apply(classType);
    MethodDefinition createPageAsyncMethod = MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(futurePageType).setName("createPageAsync").setArguments(Arrays.asList(contextVarExpr, futureResponseVarExpr).stream().map(e -> e.toBuilder().setIsDecl(true).build()).collect(Collectors.toList())).setReturnExpr(MethodInvocationExpr.builder().setExprReferenceExpr(ValueExpr.withValue(SuperObjectValue.withType(classExtendsType))).setMethodName("createPageAsync").setArguments(contextVarExpr, futureResponseVarExpr).setReturnType(futurePageType).build()).build();
    // Build the class.
    List<MethodDefinition> javaMethods = new ArrayList<>();
    javaMethods.add(privateCtor);
    javaMethods.add(createEmptyPageMethod);
    javaMethods.add(createPageMethod);
    javaMethods.add(createPageAsyncMethod);
    return ClassDefinition.builder().setIsNested(true).setScope(ScopeNode.PUBLIC).setIsStatic(true).setExtendsType(classExtendsType).setName(className).setMethods(javaMethods).build();
}
Also used : Arrays(java.util.Arrays) ServiceClientHeaderSampleComposer(com.google.api.generator.gapic.composer.samplecode.ServiceClientHeaderSampleComposer) OperationFuture(com.google.api.gax.longrunning.OperationFuture) BiFunction(java.util.function.BiFunction) Reference(com.google.api.generator.engine.ast.Reference) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) ThisObjectValue(com.google.api.generator.engine.ast.ThisObjectValue) Variable(com.google.api.generator.engine.ast.Variable) BackgroundResource(com.google.api.gax.core.BackgroundResource) Field(com.google.api.generator.gapic.model.Field) Generated(javax.annotation.Generated) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) Method(com.google.api.generator.gapic.model.Method) MethodArgument(com.google.api.generator.gapic.model.MethodArgument) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) LongrunningOperation(com.google.api.generator.gapic.model.LongrunningOperation) Stream(com.google.api.generator.gapic.model.Method.Stream) Map(java.util.Map) ServiceClientMethodSampleComposer(com.google.api.generator.gapic.composer.samplecode.ServiceClientMethodSampleComposer) ServerStreamingCallable(com.google.api.gax.rpc.ServerStreamingCallable) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) ApiFutures(com.google.api.core.ApiFutures) PageContext(com.google.api.gax.rpc.PageContext) Status(com.google.rpc.Status) Set(java.util.Set) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) ServiceClientCommentComposer(com.google.api.generator.gapic.composer.comment.ServiceClientCommentComposer) Collectors(java.util.stream.Collectors) ApiFuture(com.google.api.core.ApiFuture) Objects(java.util.Objects) ClassNames(com.google.api.generator.gapic.composer.utils.ClassNames) List(java.util.List) ServiceClientCallableMethodSampleComposer(com.google.api.generator.gapic.composer.samplecode.ServiceClientCallableMethodSampleComposer) SampleCodeWriter(com.google.api.generator.gapic.composer.samplecode.SampleCodeWriter) Optional(java.util.Optional) GapicContext(com.google.api.generator.gapic.model.GapicContext) ApiFunction(com.google.api.core.ApiFunction) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) BetaApi(com.google.api.core.BetaApi) TypeNode(com.google.api.generator.engine.ast.TypeNode) BidiStreamingCallable(com.google.api.gax.rpc.BidiStreamingCallable) Kind(com.google.api.generator.gapic.model.GapicClass.Kind) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) PackageChecker(com.google.api.generator.gapic.composer.utils.PackageChecker) HashMap(java.util.HashMap) GapicMetadata(com.google.gapic.metadata.GapicMetadata) Operation(com.google.longrunning.Operation) Function(java.util.function.Function) ArrayList(java.util.ArrayList) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Strings(com.google.common.base.Strings) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) ClientStreamingCallable(com.google.api.gax.rpc.ClientStreamingCallable) TriFunction(com.google.api.generator.util.TriFunction) AbstractFixedSizeCollection(com.google.api.gax.paging.AbstractFixedSizeCollection) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) Iterator(java.util.Iterator) AbstractPage(com.google.api.gax.paging.AbstractPage) CastExpr(com.google.api.generator.engine.ast.CastExpr) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) IOException(java.io.IOException) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) Sample(com.google.api.generator.gapic.model.Sample) GapicClass(com.google.api.generator.gapic.model.GapicClass) ResourceName(com.google.api.generator.gapic.model.ResourceName) Trie(com.google.api.generator.util.Trie) TimeUnit(java.util.concurrent.TimeUnit) OperationCallable(com.google.api.gax.rpc.OperationCallable) UnaryCallable(com.google.api.gax.rpc.UnaryCallable) Statement(com.google.api.generator.engine.ast.Statement) Service(com.google.api.generator.gapic.model.Service) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) SuperObjectValue(com.google.api.generator.engine.ast.SuperObjectValue) SampleComposerUtil(com.google.api.generator.gapic.composer.samplecode.SampleComposerUtil) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Message(com.google.api.generator.gapic.model.Message) Collections(java.util.Collections) AbstractPagedListResponse(com.google.api.gax.paging.AbstractPagedListResponse) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ApiFuture(com.google.api.core.ApiFuture) AbstractPage(com.google.api.gax.paging.AbstractPage) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) ArrayList(java.util.ArrayList) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 12 with ValueExpr

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

the class ResourceNameHelperClassComposer method createParseMethod.

private static MethodDefinition createParseMethod(TypeNode thisClassType, List<VariableExpr> templateFinalVarExprs, List<List<String>> tokenHierarchies, TypeStore typeStore) {
    String formattedStringArgName = "formattedString";
    VariableExpr formattedStringArgExpr = VariableExpr.withVariable(Variable.builder().setName(formattedStringArgName).setType(TypeNode.STRING).build());
    String exceptionMessageString = String.format("%s.parse: %s not in valid format", thisClassType.reference().name(), formattedStringArgName);
    ValueExpr exceptionMessageExpr = ValueExpr.withValue(StringObjectValue.withValue(exceptionMessageString));
    TypeNode mapStringType = TypeNode.withReference(ConcreteReference.builder().setClazz(Map.class).setGenerics(Arrays.asList(ConcreteReference.withClazz(String.class), ConcreteReference.withClazz(String.class))).build());
    VariableExpr matchMapVarExpr = VariableExpr.withVariable(Variable.builder().setName("matchMap").setType(mapStringType).build());
    List<Statement> body = new ArrayList<>();
    body.add(IfStatement.builder().setConditionExpr(MethodInvocationExpr.builder().setExprReferenceExpr(formattedStringArgExpr).setMethodName("isEmpty").setReturnType(TypeNode.BOOLEAN).build()).setBody(Arrays.asList(ExprStatement.withExpr(ReturnExpr.withExpr(ValueExpr.createNullExpr())))).build());
    List<Expr> formattedStringArgList = Arrays.asList(formattedStringArgExpr);
    List<VariableExpr> formattedStringArgDeclList = Arrays.asList(formattedStringArgExpr.toBuilder().setIsDecl(true).build());
    boolean hasVariants = tokenHierarchies.size() > 1;
    if (!hasVariants) {
        List<Expr> methodArgs = Arrays.asList(formattedStringArgExpr, exceptionMessageExpr);
        MethodInvocationExpr validatedMatchExpr = MethodInvocationExpr.builder().setExprReferenceExpr(templateFinalVarExprs.get(0)).setMethodName("validatedMatch").setArguments(methodArgs).setReturnType(mapStringType).build();
        AssignmentExpr matchMapAssignExpr = AssignmentExpr.builder().setVariableExpr(matchMapVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(validatedMatchExpr).build();
        body.add(ExprStatement.withExpr(matchMapAssignExpr));
        List<Expr> ofMethodArgExprs = tokenHierarchies.get(0).stream().map(t -> MethodInvocationExpr.builder().setExprReferenceExpr(matchMapVarExpr).setMethodName("get").setArguments(Arrays.asList(ValueExpr.withValue(StringObjectValue.withValue(t)))).build()).collect(Collectors.toList());
        MethodInvocationExpr ofMethodExpr = MethodInvocationExpr.builder().setMethodName("of").setArguments(ofMethodArgExprs).setReturnType(thisClassType).build();
        return MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setIsStatic(true).setReturnType(thisClassType).setName("parse").setArguments(formattedStringArgDeclList).setBody(body).setReturnExpr(ofMethodExpr).build();
    }
    IfStatement.Builder ifStatementBuilder = IfStatement.builder();
    String ofMethodNamePattern = "of%sName";
    for (int i = 0; i < tokenHierarchies.size(); i++) {
        // PubSub special-case handling for the "_deleted-topic_" pattern.
        boolean isDeletedTopicPattern = tokenHierarchies.get(i).contains(ResourceNameConstants.DELETED_TOPIC_LITERAL);
        VariableExpr templateVarExpr = templateFinalVarExprs.get(i);
        MethodInvocationExpr conditionExpr = MethodInvocationExpr.builder().setExprReferenceExpr(templateVarExpr).setMethodName(isDeletedTopicPattern ? "equals" : "matches").setArguments(formattedStringArgList).setReturnType(TypeNode.BOOLEAN).build();
        MethodInvocationExpr matchValueExpr = MethodInvocationExpr.builder().setExprReferenceExpr(templateVarExpr).setMethodName("match").setArguments(formattedStringArgList).setReturnType(mapStringType).build();
        AssignmentExpr matchMapAssignExpr = AssignmentExpr.builder().setVariableExpr(matchMapVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(matchValueExpr).build();
        List<String> tokens = tokenHierarchies.get(i);
        MethodInvocationExpr ofMethodExpr = MethodInvocationExpr.builder().setMethodName(String.format(ofMethodNamePattern, concatToUpperCamelCaseName(tokens))).setArguments(tokens.stream().map(t -> MethodInvocationExpr.builder().setExprReferenceExpr(matchMapVarExpr).setMethodName("get").setArguments(Arrays.asList(ValueExpr.withValue(StringObjectValue.withValue(t)))).build()).collect(Collectors.toList())).setReturnType(thisClassType).build();
        ReturnExpr subReturnExpr = ReturnExpr.withExpr(ofMethodExpr);
        List<Statement> ifStatements = Arrays.asList(matchMapAssignExpr, subReturnExpr).stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
        if (i == 0) {
            ifStatementBuilder = ifStatementBuilder.setConditionExpr(conditionExpr).setBody(ifStatements);
        } else {
            // _deleted-topic_.
            if (isDeletedTopicPattern) {
                ifStatements.clear();
                ifStatements.add(ExprStatement.withExpr(ReturnExpr.withExpr(NewObjectExpr.builder().setType(thisClassType).setArguments(ValueExpr.withValue(StringObjectValue.withValue(ResourceNameConstants.DELETED_TOPIC_LITERAL))).build())));
            }
            ifStatementBuilder = ifStatementBuilder.addElseIf(conditionExpr, ifStatements);
        }
    }
    body.add(ifStatementBuilder.build());
    body.add(ExprStatement.withExpr(ThrowExpr.builder().setType(FIXED_TYPESTORE.get("ValidationException")).setMessageExpr(exceptionMessageString).build()));
    return MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setIsStatic(true).setReturnType(thisClassType).setName("parse").setArguments(formattedStringArgDeclList).setBody(body).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) IfStatement(com.google.api.generator.engine.ast.IfStatement) 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) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 13 with ValueExpr

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

the class HttpJsonServiceStubClassComposer method appendField.

// Generates: [nameVar].append(":").append([requestVar].get[FieldName]());
private ExprStatement appendField(VariableExpr nameVar, VariableExpr requestVar, String fieldName) {
    BiFunction<String, List<Expr>, Function<MethodInvocationExpr, MethodInvocationExpr>> methodMaker = getMethodMaker();
    ValueExpr colonValueExpr = ValueExpr.builder().setValue(StringObjectValue.builder().setValue(":").build()).build();
    MethodInvocationExpr opNameAppendColonExpr = MethodInvocationExpr.builder().setMethodName("append").setArguments(colonValueExpr).setExprReferenceExpr(nameVar).build();
    MethodInvocationExpr getField = MethodInvocationExpr.builder().setExprReferenceExpr(requestVar).setMethodName(getMethodFormat(fieldName)).build();
    opNameAppendColonExpr = methodMaker.apply("append", Collections.singletonList(getField)).apply(opNameAppendColonExpr);
    return ExprStatement.withExpr(opNameAppendColonExpr);
}
Also used : BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList)

Example 14 with ValueExpr

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

the class BatchingDescriptorComposer method createSplitResponseMethod.

private static MethodDefinition createSplitResponseMethod(Method method, GapicBatchingSettings batchingSettings, Map<String, Message> messageTypes) {
    VariableExpr batchResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.outputType()).setName("batchResponse").build());
    TypeNode batchedRequestIssuerType = toType(BATCHED_REQUEST_ISSUER_REF, method.outputType());
    TypeNode batchVarType = TypeNode.withReference(ConcreteReference.builder().setClazz(Collection.class).setGenerics(Arrays.asList(ConcreteReference.wildcardWithUpperBound(batchedRequestIssuerType.reference()))).build());
    VariableExpr batchVarExpr = VariableExpr.withVariable(Variable.builder().setType(batchVarType).setName("batch").build());
    VariableExpr responderVarExpr = VariableExpr.withVariable(Variable.builder().setType(batchedRequestIssuerType).setName("responder").build());
    VariableExpr batchMessageIndexVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.INT).setName("batchMessageIndex").build());
    VariableExpr subresponseElementsVarExpr = null;
    boolean hasSubresponseField = batchingSettings.subresponseFieldName() != null;
    List<Statement> outerForBody = new ArrayList<>();
    if (hasSubresponseField) {
        Message outputMessage = messageTypes.get(method.outputType().reference().fullName());
        Preconditions.checkNotNull(outputMessage, String.format("Output message not found for RPC %s", method.name()));
        Field subresponseElementField = outputMessage.fieldMap().get(batchingSettings.subresponseFieldName());
        Preconditions.checkNotNull(subresponseElementField, String.format("Subresponse field %s not found in message %s", batchingSettings.subresponseFieldName(), outputMessage.name()));
        TypeNode subresponseElementType = subresponseElementField.type();
        subresponseElementsVarExpr = VariableExpr.withVariable(Variable.builder().setType(subresponseElementType).setName("subresponseElements").build());
        VariableExpr subresponseCountVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.LONG).setName("subresponseCount").build());
        outerForBody.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(subresponseElementsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(TypeNode.withReference(ConcreteReference.withClazz(ArrayList.class))).setIsGeneric(true).build()).build()));
        String getFooCountMethodName = "getMessageCount";
        outerForBody.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(subresponseCountVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(responderVarExpr).setMethodName(getFooCountMethodName).setReturnType(subresponseCountVarExpr.type()).build()).build()));
        List<Expr> innerSubresponseForExprs = new ArrayList<>();
        String getSubresponseFieldMethodName = String.format("get%s", JavaStyle.toUpperCamelCase(batchingSettings.subresponseFieldName()));
        Expr addMethodArgExpr = MethodInvocationExpr.builder().setExprReferenceExpr(batchResponseVarExpr).setMethodName(getSubresponseFieldMethodName).setArguments(UnaryOperationExpr.postfixIncrementWithExpr(batchMessageIndexVarExpr)).build();
        innerSubresponseForExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(subresponseElementsVarExpr).setMethodName("add").setArguments(addMethodArgExpr).build());
        // TODO(miraleung): Increment batchMessageIndexVarExpr.
        VariableExpr forIndexVarExpr = VariableExpr.builder().setIsDecl(true).setVariable(Variable.builder().setType(TypeNode.INT).setName("i").build()).build();
        ValueExpr initValueExpr = ValueExpr.withValue(PrimitiveValue.builder().setValue("0").setType(TypeNode.INT).build());
        GeneralForStatement innerSubresponseForStatement = GeneralForStatement.incrementWith(forIndexVarExpr, initValueExpr, subresponseCountVarExpr, innerSubresponseForExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
        outerForBody.add(innerSubresponseForStatement);
    }
    TypeNode responseType = method.outputType();
    Expr responseBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(responseType).setMethodName("newBuilder").build();
    if (hasSubresponseField) {
        Preconditions.checkNotNull(subresponseElementsVarExpr, String.format("subresponseElements variable should not be null for method %s", method.name()));
        responseBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseBuilderExpr).setMethodName(String.format("addAll%s", JavaStyle.toUpperCamelCase(batchingSettings.subresponseFieldName()))).setArguments(subresponseElementsVarExpr).build();
    }
    responseBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseBuilderExpr).setMethodName("build").setReturnType(responseType).build();
    VariableExpr responseVarExpr = VariableExpr.withVariable(Variable.builder().setType(responseType).setName("response").build());
    outerForBody.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(responseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(responseBuilderExpr).build()));
    outerForBody.add(ExprStatement.withExpr(MethodInvocationExpr.builder().setExprReferenceExpr(responderVarExpr).setMethodName("setResponse").setArguments(responseVarExpr).build()));
    ForStatement outerForStatement = ForStatement.builder().setLocalVariableExpr(responderVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(batchVarExpr).setBody(outerForBody).build();
    List<Statement> bodyStatements = new ArrayList<>();
    if (hasSubresponseField) {
        bodyStatements.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(batchMessageIndexVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build())).build()));
    }
    bodyStatements.add(outerForStatement);
    return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName("splitResponse").setArguments(Arrays.asList(batchResponseVarExpr, batchVarExpr).stream().map(v -> v.toBuilder().setIsDecl(true).build()).collect(Collectors.toList())).setBody(bodyStatements).build();
}
Also used : ValueExpr(com.google.api.generator.engine.ast.ValueExpr) Message(com.google.api.generator.gapic.model.Message) IfStatement(com.google.api.generator.engine.ast.IfStatement) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) ArrayList(java.util.ArrayList) Field(com.google.api.generator.gapic.model.Field) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) UnaryOperationExpr(com.google.api.generator.engine.ast.UnaryOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) Collection(java.util.Collection) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement)

Example 15 with ValueExpr

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

the class RetrySettingsComposer method createLroSettingsBuilderExpr.

public static Expr createLroSettingsBuilderExpr(Service service, GapicServiceConfig serviceConfig, Method method, VariableExpr builderVarExpr, VariableExpr retryableCodeDefsVarExpr, VariableExpr retryParamDefsVarExpr, TypeNode operationResponseTransformer, TypeNode operationMetadataTransformer) {
    Preconditions.checkState(method.hasLro(), String.format("Tried to create LRO settings initialization for non-LRO method %s", method.name()));
    String codeName = serviceConfig.getRetryCodeName(service, method);
    String retryParamName = serviceConfig.getRetryParamsName(service, method);
    String settingsGetterMethodName = String.format("%sOperationSettings", JavaStyle.toLowerCamelCase(method.name()));
    Function<String, ValueExpr> strValExprFn = s -> ValueExpr.withValue(StringObjectValue.withValue(s));
    // Argument for setInitialCallSettings.
    Expr unaryCallSettingsExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("UnaryCallSettings")).setGenerics(Arrays.asList(method.inputType().reference(), FIXED_TYPESTORE.get("OperationSnapshot").reference())).setMethodName("newUnaryCallSettingsBuilder").build();
    unaryCallSettingsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(unaryCallSettingsExpr).setMethodName("setRetryableCodes").setArguments(MethodInvocationExpr.builder().setExprReferenceExpr(retryableCodeDefsVarExpr).setMethodName("get").setArguments(strValExprFn.apply(codeName)).build()).build();
    unaryCallSettingsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(unaryCallSettingsExpr).setMethodName("setRetrySettings").setArguments(MethodInvocationExpr.builder().setExprReferenceExpr(retryParamDefsVarExpr).setMethodName("get").setArguments(strValExprFn.apply(retryParamName)).build()).build();
    unaryCallSettingsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(unaryCallSettingsExpr).setMethodName("build").build();
    Expr builderSettingsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(builderVarExpr).setMethodName(settingsGetterMethodName).build();
    builderSettingsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(builderSettingsExpr).setMethodName("setInitialCallSettings").setArguments(unaryCallSettingsExpr).build();
    Function<TypeNode, VariableExpr> classFieldRefFn = t -> VariableExpr.builder().setVariable(Variable.builder().setType(TypeNode.CLASS_OBJECT).setName("class").build()).setStaticReferenceType(t).build();
    builderSettingsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(builderSettingsExpr).setMethodName("setResponseTransformer").setArguments(MethodInvocationExpr.builder().setStaticReferenceType(operationResponseTransformer).setMethodName("create").setArguments(classFieldRefFn.apply(method.lro().responseType())).build()).build();
    builderSettingsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(builderSettingsExpr).setMethodName("setMetadataTransformer").setArguments(MethodInvocationExpr.builder().setStaticReferenceType(operationMetadataTransformer).setMethodName("create").setArguments(classFieldRefFn.apply(method.lro().metadataType())).build()).build();
    Expr lroRetrySettingsExpr = createLroRetrySettingsExpr(service, method, serviceConfig);
    Expr pollAlgoExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("OperationTimedPollAlgorithm")).setMethodName("create").setArguments(lroRetrySettingsExpr).build();
    builderSettingsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(builderSettingsExpr).setMethodName("setPollingAlgorithm").setArguments(pollAlgoExpr).build();
    return builderSettingsExpr;
}
Also used : BlockStatement(com.google.api.generator.engine.ast.BlockStatement) Arrays(java.util.Arrays) TypeNode(com.google.api.generator.engine.ast.TypeNode) GapicLroRetrySettings(com.google.api.generator.gapic.model.GapicLroRetrySettings) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) ProtoOperationTransformers(com.google.api.gax.grpc.ProtoOperationTransformers) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) FlowControlSettings(com.google.api.gax.batching.FlowControlSettings) FlowController(com.google.api.gax.batching.FlowController) RetryPolicy(io.grpc.serviceconfig.MethodConfig.RetryPolicy) Variable(com.google.api.generator.engine.ast.Variable) Function(java.util.function.Function) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) Durations(com.google.protobuf.util.Durations) ArrayList(java.util.ArrayList) RetrySettings(com.google.api.gax.retrying.RetrySettings) UnaryCallSettings(com.google.api.gax.rpc.UnaryCallSettings) Expr(com.google.api.generator.engine.ast.Expr) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) Method(com.google.api.generator.gapic.model.Method) Lists(com.google.common.collect.Lists) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) Map(java.util.Map) Code(com.google.rpc.Code) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) BatchingSettings(com.google.api.gax.batching.BatchingSettings) OperationSnapshot(com.google.api.gax.longrunning.OperationSnapshot) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) GapicBatchingSettings(com.google.api.generator.gapic.model.GapicBatchingSettings) Collectors(java.util.stream.Collectors) GapicRetrySettings(com.google.api.generator.gapic.model.GapicRetrySettings) Service(com.google.api.generator.gapic.model.Service) Duration(com.google.protobuf.Duration) List(java.util.List) OperationTimedPollAlgorithm(com.google.api.gax.longrunning.OperationTimedPollAlgorithm) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) Optional(java.util.Optional) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Preconditions(com.google.common.base.Preconditions) StatusCode(com.google.api.gax.rpc.StatusCode) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) Expr(com.google.api.generator.engine.ast.Expr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Aggregations

ValueExpr (com.google.api.generator.engine.ast.ValueExpr)32 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)27 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)24 MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)24 Expr (com.google.api.generator.engine.ast.Expr)19 RelationalOperationExpr (com.google.api.generator.engine.ast.RelationalOperationExpr)18 Test (org.junit.Test)18 NewObjectExpr (com.google.api.generator.engine.ast.NewObjectExpr)17 Variable (com.google.api.generator.engine.ast.Variable)16 LogicalOperationExpr (com.google.api.generator.engine.ast.LogicalOperationExpr)15 PrimitiveValue (com.google.api.generator.engine.ast.PrimitiveValue)15 TernaryExpr (com.google.api.generator.engine.ast.TernaryExpr)15 AssignmentOperationExpr (com.google.api.generator.engine.ast.AssignmentOperationExpr)14 CastExpr (com.google.api.generator.engine.ast.CastExpr)14 ReturnExpr (com.google.api.generator.engine.ast.ReturnExpr)14 StringObjectValue (com.google.api.generator.engine.ast.StringObjectValue)14 ThisObjectValue (com.google.api.generator.engine.ast.ThisObjectValue)14 ThrowExpr (com.google.api.generator.engine.ast.ThrowExpr)14 TypeNode (com.google.api.generator.engine.ast.TypeNode)14 ExprStatement (com.google.api.generator.engine.ast.ExprStatement)13