Search in sources :

Example 6 with MethodArgument

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

the class ServiceClientHeaderSampleComposerTest method valid_composeShowcaseMethodSample_lroRpcWithReturnResponseType.

@Test
public void valid_composeShowcaseMethodSample_lroRpcWithReturnResponseType() {
    Descriptors.FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor();
    Map<String, ResourceName> resourceNames = Parser.parseResourceNames(echoFileDescriptor);
    Map<String, Message> messageTypes = Parser.parseMessages(echoFileDescriptor);
    TypeNode clientType = TypeNode.withReference(VaporReference.builder().setName("EchoClient").setPakkage(SHOWCASE_PACKAGE_NAME).build());
    TypeNode inputType = TypeNode.withReference(VaporReference.builder().setName("WaitRequest").setPakkage(SHOWCASE_PACKAGE_NAME).build());
    TypeNode outputType = TypeNode.withReference(VaporReference.builder().setName("Operation").setPakkage(LRO_PACKAGE_NAME).build());
    TypeNode responseType = TypeNode.withReference(VaporReference.builder().setName("WaitResponse").setPakkage(SHOWCASE_PACKAGE_NAME).build());
    TypeNode metadataType = TypeNode.withReference(VaporReference.builder().setName("WaitMetadata").setPakkage(SHOWCASE_PACKAGE_NAME).build());
    LongrunningOperation lro = LongrunningOperation.builder().setResponseType(responseType).setMetadataType(metadataType).build();
    TypeNode ttlTypeNode = TypeNode.withReference(VaporReference.builder().setName("Duration").setPakkage(PROTO_PACKAGE_NAME).build());
    MethodArgument ttl = MethodArgument.builder().setName("ttl").setType(ttlTypeNode).setField(Field.builder().setName("ttl").setType(ttlTypeNode).setIsMessage(true).setIsContainedInOneof(true).build()).build();
    List<MethodArgument> arguments = Arrays.asList(ttl);
    Method method = Method.builder().setName("Wait").setInputType(inputType).setOutputType(outputType).setLro(lro).setMethodSignatures(Arrays.asList(arguments)).build();
    String results = writeStatements(ServiceClientHeaderSampleComposer.composeShowcaseMethodSample(method, clientType, arguments, resourceNames, messageTypes));
    String expected = LineFormatter.lines("try (EchoClient echoClient = EchoClient.create()) {\n", "  Duration ttl = Duration.newBuilder().build();\n", "  WaitResponse response = echoClient.waitAsync(ttl).get();\n", "}");
    Assert.assertEquals(results, expected);
}
Also used : LongrunningOperation(com.google.api.generator.gapic.model.LongrunningOperation) Message(com.google.api.generator.gapic.model.Message) MethodArgument(com.google.api.generator.gapic.model.MethodArgument) ResourceName(com.google.api.generator.gapic.model.ResourceName) Descriptors(com.google.protobuf.Descriptors) TypeNode(com.google.api.generator.engine.ast.TypeNode) Method(com.google.api.generator.gapic.model.Method) Test(org.junit.Test)

Example 7 with MethodArgument

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

the class ServiceClientHeaderSampleComposerTest method valid_composeShowcaseMethodSample_pagedRpcWithMultipleMethodArguments.

/*Testing composeShowcaseMethodSample*/
@Test
public void valid_composeShowcaseMethodSample_pagedRpcWithMultipleMethodArguments() {
    Descriptors.FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor();
    Map<String, ResourceName> resourceNames = Parser.parseResourceNames(echoFileDescriptor);
    Map<String, Message> messageTypes = Parser.parseMessages(echoFileDescriptor);
    TypeNode clientType = TypeNode.withReference(VaporReference.builder().setName("EchoClient").setPakkage(SHOWCASE_PACKAGE_NAME).build());
    TypeNode inputType = TypeNode.withReference(VaporReference.builder().setName("ListContentRequest").setPakkage(SHOWCASE_PACKAGE_NAME).build());
    TypeNode outputType = TypeNode.withReference(VaporReference.builder().setName("ListContentResponse").setPakkage(SHOWCASE_PACKAGE_NAME).build());
    TypeNode resourceNameType = TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(ConcreteReference.withClazz(String.class)).build());
    List<MethodArgument> arguments = Arrays.asList(MethodArgument.builder().setName("resourceName").setType(resourceNameType).setField(Field.builder().setName("resourceName").setType(resourceNameType).setIsRepeated(true).build()).build(), MethodArgument.builder().setName("filter").setType(TypeNode.STRING).setField(Field.builder().setName("filter").setType(TypeNode.STRING).build()).build());
    Method method = Method.builder().setName("ListContent").setMethodSignatures(Arrays.asList(arguments)).setInputType(inputType).setOutputType(outputType).setPageSizeFieldName(PAGINATED_FIELD_NAME).build();
    Reference repeatedResponseReference = VaporReference.builder().setName("Content").setPakkage(SHOWCASE_PACKAGE_NAME).build();
    Field repeatedField = Field.builder().setName("responses").setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(repeatedResponseReference).build())).setIsMessage(true).setIsRepeated(true).build();
    Field nextPagedTokenField = Field.builder().setName("next_page_token").setType(TypeNode.STRING).build();
    Message listContentResponseMessage = Message.builder().setName("ListContentResponse").setFullProtoName("google.showcase.v1beta1.ListContentResponse").setType(outputType).setFields(Arrays.asList(repeatedField, nextPagedTokenField)).build();
    messageTypes.put("com.google.showcase.v1beta1.ListContentResponse", listContentResponseMessage);
    String results = writeStatements(ServiceClientHeaderSampleComposer.composeShowcaseMethodSample(method, clientType, arguments, resourceNames, messageTypes));
    String expected = LineFormatter.lines("try (EchoClient echoClient = EchoClient.create()) {\n", "  List<String> resourceName = new ArrayList<>();\n", "  String filter = \"filter-1274492040\";\n", "  for (Content element : echoClient.listContent(resourceName, filter).iterateAll())" + " {\n", "    // doThingsWith(element);\n", "  }\n", "}");
    Assert.assertEquals(results, expected);
}
Also used : Message(com.google.api.generator.gapic.model.Message) MethodArgument(com.google.api.generator.gapic.model.MethodArgument) ResourceName(com.google.api.generator.gapic.model.ResourceName) VaporReference(com.google.api.generator.engine.ast.VaporReference) Reference(com.google.api.generator.engine.ast.Reference) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) Method(com.google.api.generator.gapic.model.Method) Field(com.google.api.generator.gapic.model.Field) List(java.util.List) Descriptors(com.google.protobuf.Descriptors) TypeNode(com.google.api.generator.engine.ast.TypeNode) Test(org.junit.Test)

Example 8 with MethodArgument

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

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

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

the class MethodSignatureParser method flattenMethodSignatureVariants.

private static List<List<MethodArgument>> flattenMethodSignatureVariants(List<String> argumentNames, Map<String, List<MethodArgument>> argumentNameToOverloads, int depth) {
    List<List<MethodArgument>> methodArgs = new ArrayList<>();
    if (depth >= argumentNames.size() - 1) {
        for (MethodArgument methodArg : argumentNameToOverloads.get(argumentNames.get(depth))) {
            methodArgs.add(Lists.newArrayList(methodArg));
        }
        return methodArgs;
    }
    List<List<MethodArgument>> subsequentArgs = flattenMethodSignatureVariants(argumentNames, argumentNameToOverloads, depth + 1);
    for (MethodArgument methodArg : argumentNameToOverloads.get(argumentNames.get(depth))) {
        for (List<MethodArgument> subsequentArg : subsequentArgs) {
            // Use a new list to avoid appending all subsequent elements (in upcoming loop iterations)
            // to the same list.
            List<MethodArgument> appendedArgs = new ArrayList<>(subsequentArg);
            appendedArgs.add(0, methodArg);
            methodArgs.add(appendedArgs);
        }
    }
    return methodArgs;
}
Also used : MethodArgument(com.google.api.generator.gapic.model.MethodArgument) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

MethodArgument (com.google.api.generator.gapic.model.MethodArgument)19 TypeNode (com.google.api.generator.engine.ast.TypeNode)17 List (java.util.List)14 Message (com.google.api.generator.gapic.model.Message)13 Test (org.junit.Test)13 Field (com.google.api.generator.gapic.model.Field)12 ResourceName (com.google.api.generator.gapic.model.ResourceName)12 Method (com.google.api.generator.gapic.model.Method)10 Map (java.util.Map)8 Collectors (java.util.stream.Collectors)8 VaporReference (com.google.api.generator.engine.ast.VaporReference)7 Descriptors (com.google.protobuf.Descriptors)7 ArrayList (java.util.ArrayList)7 Arrays (java.util.Arrays)7 Function (java.util.function.Function)7 CommentStatement (com.google.api.generator.engine.ast.CommentStatement)5 LongrunningOperation (com.google.api.generator.gapic.model.LongrunningOperation)5 HashMap (java.util.HashMap)5 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)4 ConcreteReference (com.google.api.generator.engine.ast.ConcreteReference)4