Search in sources :

Example 16 with Field

use of com.google.api.generator.gapic.model.Field in project gapic-generator-java by googleapis.

the class AbstractServiceClientTestClassComposer method createRpcTestMethod.

/**
 * Creates a test method for a given RPC, e.g. createAssetTest.
 *
 * @param method the RPC for which this test method is created.
 * @param apiService the host service under test.
 * @param rpcService the service that {@code method} belongs to. This is not equal to {@code
 *     apiService} only when {@code method} is a mixin, in which case {@code rpcService} is the
 *     mixed-in service. If {@code apiService} and {@code rpcService} are different, they will be
 *     used only for pagination. Otherwise, {@code rpcService} subsumes {@code apiService}.
 * @param methodSignature the method signature of the RPC under test.
 * @param variantIndex the nth variant of the RPC under test. This applies when we have
 *     polymorphism due to the presence of several method signature annotations in the proto.
 * @param isRequestArg whether the RPC variant under test take only the request proto message.
 * @param classMemberVarExprs the class members in the generated test class.
 * @param resourceNames the resource names available for use.
 * @param messageTypes the proto message types available for use.
 */
private MethodDefinition createRpcTestMethod(Method method, Service apiService, Service rpcService, List<MethodArgument> methodSignature, int variantIndex, boolean isRequestArg, Map<String, VariableExpr> classMemberVarExprs, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
    if (!method.stream().equals(Method.Stream.NONE)) {
        return createStreamingRpcTestMethod(rpcService, method, classMemberVarExprs, resourceNames, messageTypes);
    }
    // Construct the expected response.
    TypeNode methodOutputType = method.hasLro() ? method.lro().responseType() : method.outputType();
    List<Expr> methodExprs = new ArrayList<>();
    TypeNode repeatedResponseType = null;
    VariableExpr responsesElementVarExpr = null;
    String mockServiceVarName = getMockServiceVarName(rpcService);
    if (method.isPaged()) {
        Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
        Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
        Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated field found for paged method %s with output message type %s", method.name(), methodOutputMessage.name()));
        if (repeatedPagedResultsField.isMap()) {
            repeatedResponseType = TypeNode.withReference(repeatedPagedResultsField.type().reference().generics().get(1));
        } else {
            // Must be a non-repeated type.
            repeatedResponseType = repeatedPagedResultsField.type();
        }
        responsesElementVarExpr = VariableExpr.withVariable(Variable.builder().setType(repeatedResponseType).setName("responsesElement").build());
        methodExprs.add(AssignmentExpr.builder().setVariableExpr(responsesElementVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(DefaultValueComposer.createValue(Field.builder().setType(repeatedResponseType).setName("responsesElement").setIsMessage(!repeatedResponseType.isProtoPrimitiveType()).build())).build());
    }
    VariableExpr expectedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(methodOutputType).setName("expectedResponse").build());
    Expr expectedResponseValExpr = null;
    if (method.isPaged()) {
        Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
        Field firstRepeatedField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
        Preconditions.checkNotNull(firstRepeatedField, String.format("Expected paged RPC %s to have a repeated field in the response %s but found none", method.name(), methodOutputMessage.name()));
        expectedResponseValExpr = DefaultValueComposer.createSimplePagedResponseValue(method.outputType(), firstRepeatedField.name(), responsesElementVarExpr, firstRepeatedField.isMap());
    } else {
        if (messageTypes.containsKey(methodOutputType.reference().fullName())) {
            expectedResponseValExpr = DefaultValueComposer.createSimpleMessageBuilderValue(messageTypes.get(methodOutputType.reference().fullName()), resourceNames, messageTypes);
        } else {
            // Wrap this in a field so we don't have to split the helper into lots of different methods,
            // or duplicate it for VariableExpr.
            expectedResponseValExpr = DefaultValueComposer.createValue(Field.builder().setType(methodOutputType).setIsMessage(true).setName("expectedResponse").build());
        }
    }
    methodExprs.add(AssignmentExpr.builder().setVariableExpr(expectedResponseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(expectedResponseValExpr).build());
    if (method.hasLro() && (method.lro().operationServiceStubType() == null || !method.lro().responseType().equals(method.outputType()))) {
        VariableExpr resultOperationVarExpr = VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("Operation")).setName("resultOperation").build());
        methodExprs.add(AssignmentExpr.builder().setVariableExpr(resultOperationVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(DefaultValueComposer.createSimpleOperationBuilderValue(String.format("%sTest", JavaStyle.toLowerCamelCase(method.name())), expectedResponseVarExpr)).build());
        methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(mockServiceVarName)).setMethodName("addResponse").setArguments(resultOperationVarExpr).build());
    } else {
        methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(mockServiceVarName)).setMethodName("addResponse").setArguments(expectedResponseVarExpr).build());
    }
    List<Statement> methodStatements = new ArrayList<>();
    methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    methodExprs.clear();
    methodStatements.add(EMPTY_LINE_STATEMENT);
    // Construct the request or method arguments.
    VariableExpr requestVarExpr = null;
    Message requestMessage = null;
    List<VariableExpr> argExprs = new ArrayList<>();
    if (isRequestArg) {
        requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
        argExprs.add(requestVarExpr);
        requestMessage = messageTypes.get(method.inputType().reference().fullName());
        Preconditions.checkNotNull(requestMessage);
        Map<String, String> pathParamValuePatterns = Collections.emptyMap();
        if (getTransportContext().useValuePatterns() && method.hasHttpBindings()) {
            pathParamValuePatterns = method.httpBindings().getPathParametersValuePatterns();
        }
        Expr valExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes, pathParamValuePatterns);
        methodExprs.add(AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
    } else {
        Map<String, String> valuePatterns = Collections.emptyMap();
        if (getTransportContext().useValuePatterns() && method.hasHttpBindings()) {
            valuePatterns = method.httpBindings().getPathParametersValuePatterns();
        }
        for (MethodArgument methodArg : methodSignature) {
            String methodArgName = JavaStyle.toLowerCamelCase(methodArg.name());
            VariableExpr varExpr = VariableExpr.withVariable(Variable.builder().setType(methodArg.type()).setName(methodArgName).build());
            argExprs.add(varExpr);
            Expr valExpr = DefaultValueComposer.createMethodArgValue(methodArg, resourceNames, messageTypes, valuePatterns);
            methodExprs.add(AssignmentExpr.builder().setVariableExpr(varExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
        }
    }
    methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    methodExprs.clear();
    methodStatements.add(EMPTY_LINE_STATEMENT);
    // Call the RPC Java method.
    VariableExpr actualResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(!method.isPaged() ? methodOutputType : // does not have a client.
    getPagedResponseType(method, method.isMixin() ? apiService : rpcService)).setName(method.isPaged() ? "pagedListResponse" : "actualResponse").build());
    Expr rpcJavaMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get("client")).setMethodName(JavaStyle.toLowerCamelCase(method.name()) + (method.hasLro() ? "Async" : "")).setArguments(argExprs.stream().map(e -> (Expr) e).collect(Collectors.toList())).setReturnType(actualResponseVarExpr.type()).build();
    if (method.hasLro()) {
        rpcJavaMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(rpcJavaMethodInvocationExpr).setMethodName("get").setReturnType(rpcJavaMethodInvocationExpr.type()).build();
    }
    boolean returnsVoid = isProtoEmptyType(methodOutputType);
    if (returnsVoid) {
        methodExprs.add(rpcJavaMethodInvocationExpr);
    } else {
        methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualResponseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(rpcJavaMethodInvocationExpr).build());
    }
    if (method.isPaged()) {
        Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
        Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
        // Assign the resources variable.
        VariableExpr resourcesVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(repeatedPagedResultsField.type().reference())).build())).setName("resources").build());
        Expr iterateAllExpr = MethodInvocationExpr.builder().setExprReferenceExpr(actualResponseVarExpr).setMethodName("iterateAll").build();
        Expr resourcesValExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Lists")).setMethodName("newArrayList").setArguments(iterateAllExpr).setReturnType(resourcesVarExpr.type()).build();
        methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
        methodExprs.clear();
        methodStatements.add(EMPTY_LINE_STATEMENT);
        methodStatements.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(resourcesVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(resourcesValExpr).build()));
        methodStatements.add(EMPTY_LINE_STATEMENT);
        // Assert the size is equivalent.
        methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("1").build()), MethodInvocationExpr.builder().setExprReferenceExpr(resourcesVarExpr).setMethodName("size").setReturnType(TypeNode.INT).build()).build());
        // Assert the responses are equivalent.
        Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated field found for paged method %s with output message type %s", method.name(), methodOutputMessage.name()));
        Expr zeroExpr = ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build());
        // Generated code:
        // Assert.assertEquals(
        // expectedResponse.getItemsMap().entrySet().iterator().next(), resources.get(0));
        // )
        Expr expectedPagedResponseExpr;
        if (repeatedPagedResultsField.isMap()) {
            expectedPagedResponseExpr = MethodInvocationExpr.builder().setMethodName("next").setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("iterator").setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("entrySet").setExprReferenceExpr(MethodInvocationExpr.builder().setExprReferenceExpr(expectedResponseVarExpr).setMethodName(String.format("get%sMap", JavaStyle.toUpperCamelCase(repeatedPagedResultsField.name()))).build()).build()).build()).build();
        } else {
            // Generated code:
            // Assert.assertEquals(expectedResponse.getItemsList().get(0), resources.get(0));
            expectedPagedResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(expectedResponseVarExpr).setMethodName(String.format("get%sList", JavaStyle.toUpperCamelCase(repeatedPagedResultsField.name()))).build();
            expectedPagedResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(expectedPagedResponseExpr).setMethodName("get").setArguments(zeroExpr).build();
        }
        Expr actualPagedResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(resourcesVarExpr).setMethodName("get").setArguments(zeroExpr).build();
        methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(expectedPagedResponseExpr, actualPagedResponseExpr).build());
    } else if (!returnsVoid) {
        methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(expectedResponseVarExpr, actualResponseVarExpr).build());
    }
    methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    methodExprs.clear();
    methodStatements.add(EMPTY_LINE_STATEMENT);
    methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    methodExprs.clear();
    methodStatements.addAll(constructRpcTestCheckerLogic(method, rpcService, isRequestArg, classMemberVarExprs, requestVarExpr, requestMessage, argExprs));
    String testMethodName = String.format("%sTest%s", JavaStyle.toLowerCamelCase(method.name()), variantIndex > 0 ? variantIndex + 1 : "");
    return MethodDefinition.builder().setAnnotations(Arrays.asList(TEST_ANNOTATION)).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName(testMethodName).setThrowsExceptions(Arrays.asList(TypeNode.withExceptionClazz(Exception.class))).setBody(methodStatements).build();
}
Also used : AbstractMessage(com.google.protobuf.AbstractMessage) Message(com.google.api.generator.gapic.model.Message) MethodArgument(com.google.api.generator.gapic.model.MethodArgument) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) 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) Field(com.google.api.generator.gapic.model.Field) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) 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) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) List(java.util.List) ArrayList(java.util.ArrayList) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 17 with Field

use of com.google.api.generator.gapic.model.Field in project gapic-generator-java by googleapis.

the class AbstractServiceStubSettingsClassComposer method createPagingStaticAssignExprs.

private static List<Expr> createPagingStaticAssignExprs(Service service, GapicServiceConfig serviceConfig, Map<String, Message> messageTypes, TypeStore typeStore) {
    List<Expr> descExprs = new ArrayList<>();
    List<Expr> factoryExprs = new ArrayList<>();
    for (Method method : service.methods()) {
        if (!method.isPaged()) {
            continue;
        }
        // Find the repeated type.
        String pagedResponseMessageKey = method.outputType().reference().fullName();
        if (method.hasLro()) {
            pagedResponseMessageKey = method.lro().responseType().reference().fullName();
        }
        Message pagedResponseMessage = messageTypes.get(pagedResponseMessageKey);
        Preconditions.checkNotNull(pagedResponseMessage, String.format("No method found for message type %s for method %s among %s", pagedResponseMessageKey, method.name(), messageTypes.keySet()));
        Field repeatedPagedResultsField = pagedResponseMessage.findAndUnwrapPaginatedRepeatedField();
        Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated type found for paged reesponse %s for method %s", method.outputType().reference().name(), method.name()));
        TypeNode repeatedResponseType = repeatedPagedResultsField.type();
        String repeatedFieldName = repeatedPagedResultsField.name();
        // Create the PAGE_STR_DESC variable.
        TypeNode pagedListDescType = TypeNode.withReference(ConcreteReference.builder().setClazz(PagedListDescriptor.class).setGenerics(Arrays.asList(method.inputType(), method.outputType(), repeatedResponseType).stream().map(t -> t.reference()).collect(Collectors.toList())).build());
        String pageStrDescVarName = String.format(PAGE_STR_DESC_PATTERN, JavaStyle.toUpperSnakeCase(method.name()));
        VariableExpr pagedListDescVarExpr = VariableExpr.withVariable(Variable.builder().setType(pagedListDescType).setName(pageStrDescVarName).build());
        descExprs.add(createPagedListDescriptorAssignExpr(pagedListDescVarExpr, method, repeatedResponseType, repeatedFieldName, messageTypes, typeStore));
        factoryExprs.add(createPagedListResponseFactoryAssignExpr(pagedListDescVarExpr, method, repeatedResponseType, typeStore));
    }
    descExprs.addAll(factoryExprs);
    return descExprs;
}
Also used : Field(com.google.api.generator.gapic.model.Field) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) 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) CastExpr(com.google.api.generator.engine.ast.CastExpr) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) 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) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) Message(com.google.api.generator.gapic.model.Message) ArrayList(java.util.ArrayList) PagedListDescriptor(com.google.api.gax.rpc.PagedListDescriptor) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) Method(com.google.api.generator.gapic.model.Method) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 18 with Field

use of com.google.api.generator.gapic.model.Field in project gapic-generator-java by googleapis.

the class AbstractServiceClientClassComposer method createRequestBuilderExpr.

@VisibleForTesting
static Expr createRequestBuilderExpr(Method method, List<MethodArgument> signature, TypeStore typeStore) {
    TypeNode methodInputType = method.inputType();
    Expr newBuilderExpr = MethodInvocationExpr.builder().setMethodName("newBuilder").setStaticReferenceType(methodInputType).build();
    // Maintain the args' order of appearance for better determinism.
    List<Field> rootFields = new ArrayList<>();
    Map<Field, Trie<Field>> rootFieldToTrie = new HashMap<>();
    for (MethodArgument arg : signature) {
        Field rootField = arg.nestedFields().isEmpty() ? arg.field() : arg.nestedFields().get(0);
        if (!rootFields.contains(rootField)) {
            rootFields.add(rootField);
        }
        Trie<Field> updatedTrie = rootFieldToTrie.containsKey(rootField) ? rootFieldToTrie.get(rootField) : new Trie<>();
        List<Field> nestedFieldsWithChild = new ArrayList<>(arg.nestedFields());
        nestedFieldsWithChild.add(arg.field());
        updatedTrie.insert(nestedFieldsWithChild);
        rootFieldToTrie.put(rootField, updatedTrie);
    }
    Function<Field, Expr> parentPreprocFn = field -> (Expr) MethodInvocationExpr.builder().setStaticReferenceType(field.type()).setMethodName("newBuilder").build();
    TriFunction<Field, Expr, Expr, Expr> parentPostprocFn = (field, baseRefExpr, leafProcessedExpr) -> {
        boolean isRootNode = field == null;
        return isRootNode ? leafProcessedExpr : MethodInvocationExpr.builder().setExprReferenceExpr(baseRefExpr).setMethodName(String.format("set%s", JavaStyle.toUpperCamelCase(field.name()))).setArguments(MethodInvocationExpr.builder().setExprReferenceExpr(leafProcessedExpr).setMethodName("build").build()).build();
    };
    final Map<Field, MethodArgument> fieldToMethodArg = signature.stream().collect(Collectors.toMap(a -> a.field(), a -> a));
    BiFunction<Field, Expr, Expr> leafProcFn = (field, parentBaseRefExpr) -> (Expr) buildNestedSetterInvocationExpr(fieldToMethodArg.get(field), parentBaseRefExpr);
    for (Field rootField : rootFields) {
        newBuilderExpr = rootFieldToTrie.get(rootField).dfsTraverseAndReduce(parentPreprocFn, parentPostprocFn, leafProcFn, newBuilderExpr);
    }
    return MethodInvocationExpr.builder().setExprReferenceExpr(newBuilderExpr).setMethodName("build").setReturnType(methodInputType).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) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MethodArgument(com.google.api.generator.gapic.model.MethodArgument) ArrayList(java.util.ArrayList) Field(com.google.api.generator.gapic.model.Field) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) 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) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) Trie(com.google.api.generator.util.Trie) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 19 with Field

use of com.google.api.generator.gapic.model.Field 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 20 with Field

use of com.google.api.generator.gapic.model.Field in project gapic-generator-java by googleapis.

the class ServiceClientCallableMethodSampleComposer method composePagedCallableMethod.

// Compose sample code for the method where it is CallableMethodKind.PAGED.
public static Sample composePagedCallableMethod(Method method, TypeNode clientType, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
    VariableExpr clientVarExpr = VariableExpr.withVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(clientType.reference().name())).setType(clientType).build());
    // Assign method's request variable with the default value.
    VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setName("request").setType(method.inputType()).build());
    Message requestMessage = messageTypes.get(method.inputType().reference().fullName());
    Preconditions.checkNotNull(requestMessage, String.format("Could not find the message type %s.", method.inputType().reference().fullName()));
    Expr requestBuilderExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes);
    AssignmentExpr requestAssignmentExpr = AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(requestBuilderExpr).build();
    List<Expr> bodyExprs = new ArrayList<>();
    bodyExprs.add(requestAssignmentExpr);
    // Find the repeated field.
    Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
    Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
    Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated field found on message %s for method %s", methodOutputMessage.name(), method.name()));
    TypeNode repeatedResponseType = repeatedPagedResultsField.type();
    // Create ApiFuture Variable Expression with assign value by invoking client paged callable
    // method.
    // e.g. ApiFuture<ListExclusionsPagedResponse> future =
    // configServiceV2Client.listExclusionsPagedCallable().futureCall(request);
    TypeNode apiFutureType = TypeNode.withReference(ConcreteReference.builder().setClazz(ApiFuture.class).setGenerics(repeatedResponseType.reference()).build());
    VariableExpr apiFutureVarExpr = VariableExpr.withVariable(Variable.builder().setName("future").setType(apiFutureType).build());
    MethodInvocationExpr pagedCallableFutureMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(String.format("%sPagedCallable", JavaStyle.toLowerCamelCase(method.name()))).build();
    pagedCallableFutureMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(pagedCallableFutureMethodExpr).setMethodName("futureCall").setArguments(requestVarExpr).setReturnType(apiFutureType).build();
    AssignmentExpr apiFutureAssignmentExpr = AssignmentExpr.builder().setVariableExpr(apiFutureVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(pagedCallableFutureMethodExpr).build();
    bodyExprs.add(apiFutureAssignmentExpr);
    List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
    bodyExprs.clear();
    // Add line comment
    bodyStatements.add(CommentStatement.withComment(LineComment.withComment("Do something.")));
    // For-loop on repeated response element
    // e.g. for (ListExclusionsResponse element : future.get().iterateAll()) {
    // // doThingsWith(element);
    // }
    VariableExpr repeatedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setName("element").setType(repeatedResponseType).build());
    MethodInvocationExpr futureGetIterateAllMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(apiFutureVarExpr).setMethodName("get").build();
    futureGetIterateAllMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(futureGetIterateAllMethodExpr).setMethodName("iterateAll").setReturnType(repeatedResponseType).build();
    CommentStatement lineCommentStatement = CommentStatement.withComment(LineComment.withComment("doThingsWith(element);"));
    ForStatement repeatedResponseForStatement = ForStatement.builder().setLocalVariableExpr(repeatedResponseVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(futureGetIterateAllMethodExpr).setBody(Arrays.asList(lineCommentStatement)).build();
    bodyStatements.add(repeatedResponseForStatement);
    List<Statement> body = Arrays.asList(TryCatchStatement.builder().setTryResourceExpr(SampleComposerUtil.assignClientVariableWithCreateMethodExpr(clientVarExpr)).setTryBody(bodyStatements).setIsSampleCode(true).build());
    RegionTag regionTag = RegionTag.builder().setServiceName(clientType.reference().name()).setRpcName(method.name()).setIsAsynchronous(true).build();
    return Sample.builder().setBody(body).setRegionTag(regionTag).build();
}
Also used : IfStatement(com.google.api.generator.engine.ast.IfStatement) Arrays(java.util.Arrays) TypeNode(com.google.api.generator.engine.ast.TypeNode) OperationFuture(com.google.api.gax.longrunning.OperationFuture) BreakStatement(com.google.api.generator.engine.ast.BreakStatement) Operation(com.google.longrunning.Operation) Variable(com.google.api.generator.engine.ast.Variable) RegionTag(com.google.api.generator.gapic.model.RegionTag) ArrayList(java.util.ArrayList) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) DefaultValueComposer(com.google.api.generator.gapic.composer.defaultvalue.DefaultValueComposer) Strings(com.google.common.base.Strings) Expr(com.google.api.generator.engine.ast.Expr) Field(com.google.api.generator.gapic.model.Field) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) Method(com.google.api.generator.gapic.model.Method) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) Map(java.util.Map) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) ServerStream(com.google.api.gax.rpc.ServerStream) LineComment(com.google.api.generator.engine.ast.LineComment) UnaryOperationExpr(com.google.api.generator.engine.ast.UnaryOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) ForStatement(com.google.api.generator.engine.ast.ForStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) Sample(com.google.api.generator.gapic.model.Sample) Collectors(java.util.stream.Collectors) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) ResourceName(com.google.api.generator.gapic.model.ResourceName) ApiFuture(com.google.api.core.ApiFuture) ApiStreamObserver(com.google.api.gax.rpc.ApiStreamObserver) Statement(com.google.api.generator.engine.ast.Statement) List(java.util.List) BidiStream(com.google.api.gax.rpc.BidiStream) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Preconditions(com.google.common.base.Preconditions) Message(com.google.api.generator.gapic.model.Message) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) Message(com.google.api.generator.gapic.model.Message) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) IfStatement(com.google.api.generator.engine.ast.IfStatement) BreakStatement(com.google.api.generator.engine.ast.BreakStatement) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) RegionTag(com.google.api.generator.gapic.model.RegionTag) ArrayList(java.util.ArrayList) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) Field(com.google.api.generator.gapic.model.Field) ApiFuture(com.google.api.core.ApiFuture) Expr(com.google.api.generator.engine.ast.Expr) 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) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) ForStatement(com.google.api.generator.engine.ast.ForStatement)

Aggregations

Field (com.google.api.generator.gapic.model.Field)34 Message (com.google.api.generator.gapic.model.Message)23 TypeNode (com.google.api.generator.engine.ast.TypeNode)21 Expr (com.google.api.generator.engine.ast.Expr)17 Test (org.junit.Test)16 Method (com.google.api.generator.gapic.model.Method)14 ResourceName (com.google.api.generator.gapic.model.ResourceName)14 ArrayList (java.util.ArrayList)13 List (java.util.List)12 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)9 MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)9 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)9 ValueExpr (com.google.api.generator.engine.ast.ValueExpr)8 Preconditions (com.google.common.base.Preconditions)8 Map (java.util.Map)8 Collectors (java.util.stream.Collectors)8 ExprStatement (com.google.api.generator.engine.ast.ExprStatement)7 Statement (com.google.api.generator.engine.ast.Statement)7 MethodArgument (com.google.api.generator.gapic.model.MethodArgument)7 Strings (com.google.common.base.Strings)7