Search in sources :

Example 6 with Message

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

the class AbstractServiceClientClassComposer method createServiceMethods.

private static List<MethodDefinition> createServiceMethods(Service service, Map<String, Message> messageTypes, TypeStore typeStore, Map<String, ResourceName> resourceNames, Map<String, List<String>> grpcRpcToJavaMethodMetadata, List<Sample> samples) {
    List<MethodDefinition> javaMethods = new ArrayList<>();
    Function<MethodDefinition, String> javaMethodNameFn = m -> m.methodIdentifier().name();
    for (Method method : service.methods()) {
        if (!grpcRpcToJavaMethodMetadata.containsKey(method.name())) {
            grpcRpcToJavaMethodMetadata.put(method.name(), new ArrayList<>());
        }
        if (method.stream().equals(Stream.NONE)) {
            List<MethodDefinition> generatedMethods = createMethodVariants(method, ClassNames.getServiceClientClassName(service), messageTypes, typeStore, resourceNames, samples);
            // Collect data for gapic_metadata.json.
            grpcRpcToJavaMethodMetadata.get(method.name()).addAll(generatedMethods.stream().map(m -> javaMethodNameFn.apply(m)).collect(Collectors.toList()));
            javaMethods.addAll(generatedMethods);
            MethodDefinition generatedMethod = createMethodDefaultMethod(method, ClassNames.getServiceClientClassName(service), messageTypes, typeStore, resourceNames, samples);
            // Collect data for gapic_metadata.json.
            grpcRpcToJavaMethodMetadata.get(method.name()).add(javaMethodNameFn.apply(generatedMethod));
            javaMethods.add(generatedMethod);
        }
        if (method.hasLro()) {
            MethodDefinition generatedMethod = createLroCallableMethod(service, method, typeStore, messageTypes, resourceNames, samples);
            // Collect data for gapic_metadata.json.
            grpcRpcToJavaMethodMetadata.get(method.name()).add(javaMethodNameFn.apply(generatedMethod));
            javaMethods.add(generatedMethod);
        }
        if (method.isPaged()) {
            MethodDefinition generatedMethod = createPagedCallableMethod(service, method, typeStore, messageTypes, resourceNames, samples);
            // Collect data for gapic_metadata.json.
            grpcRpcToJavaMethodMetadata.get(method.name()).add(javaMethodNameFn.apply(generatedMethod));
            javaMethods.add(generatedMethod);
        }
        MethodDefinition generatedMethod = createCallableMethod(service, method, typeStore, messageTypes, resourceNames, samples);
        // Collect data for the gapic_metadata.json file.
        grpcRpcToJavaMethodMetadata.get(method.name()).add(javaMethodNameFn.apply(generatedMethod));
        javaMethods.add(generatedMethod);
    }
    return javaMethods;
}
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) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) ArrayList(java.util.ArrayList) Method(com.google.api.generator.gapic.model.Method)

Example 7 with Message

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

the class AbstractServiceClientTestClassComposer method createRpcExceptionTestStatements.

protected List<Statement> createRpcExceptionTestStatements(Method method, List<MethodArgument> methodSignature, Map<String, VariableExpr> classMemberVarExprs, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
    List<VariableExpr> argVarExprs = new ArrayList<>();
    List<Expr> tryBodyExprs = new ArrayList<>();
    if (methodSignature.isEmpty()) {
        // Construct the actual request.
        VariableExpr varExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
        argVarExprs.add(varExpr);
        Message requestMessage = messageTypes.get(method.inputType().reference().fullName());
        Preconditions.checkNotNull(requestMessage);
        Map<String, String> valuePatterns = Collections.emptyMap();
        if (getTransportContext().useValuePatterns() && method.hasHttpBindings()) {
            valuePatterns = method.httpBindings().getPathParametersValuePatterns();
        }
        Expr valExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes, valuePatterns);
        tryBodyExprs.add(AssignmentExpr.builder().setVariableExpr(varExpr.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());
            argVarExprs.add(varExpr);
            Expr valExpr = DefaultValueComposer.createMethodArgValue(methodArg, resourceNames, messageTypes, valuePatterns);
            tryBodyExprs.add(AssignmentExpr.builder().setVariableExpr(varExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
        }
    }
    String rpcJavaName = JavaStyle.toLowerCamelCase(method.name());
    if (method.hasLro()) {
        rpcJavaName += "Async";
    }
    MethodInvocationExpr rpcJavaMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get("client")).setMethodName(rpcJavaName).setArguments(argVarExprs.stream().map(e -> (Expr) e).collect(Collectors.toList())).build();
    if (method.hasLro()) {
        rpcJavaMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(rpcJavaMethodInvocationExpr).setMethodName("get").build();
    }
    tryBodyExprs.add(rpcJavaMethodInvocationExpr);
    VariableExpr catchExceptionVarExpr = VariableExpr.builder().setVariable(Variable.builder().setType(TypeNode.withExceptionClazz(method.hasLro() ? ExecutionException.class : InvalidArgumentException.class)).setName("e").build()).build();
    List<Statement> catchBody = method.hasLro() ? createRpcLroExceptionTestCatchBody(catchExceptionVarExpr, false) : Arrays.asList(CommentStatement.withComment(LineComment.withComment("Expected exception.")));
    // Assert a failure if no exception was raised.
    tryBodyExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("fail").setArguments(ValueExpr.withValue(StringObjectValue.withValue("No exception raised"))).build());
    TryCatchStatement tryCatchBlock = TryCatchStatement.builder().setTryBody(tryBodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).addCatch(catchExceptionVarExpr.toBuilder().setIsDecl(true).build(), catchBody).build();
    return Arrays.asList(EMPTY_LINE_STATEMENT, tryCatchBlock);
}
Also used : Arrays(java.util.Arrays) Reference(com.google.api.generator.engine.ast.Reference) Variable(com.google.api.generator.engine.ast.Variable) NoCredentialsProvider(com.google.api.gax.core.NoCredentialsProvider) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) DefaultValueComposer(com.google.api.generator.gapic.composer.defaultvalue.DefaultValueComposer) 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) Map(java.util.Map) After(org.junit.After) ServerStreamingCallable(com.google.api.gax.rpc.ServerStreamingCallable) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) AfterClass(org.junit.AfterClass) ApiClientHeaderProvider(com.google.api.gax.rpc.ApiClientHeaderProvider) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) UUID(java.util.UUID) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) Collectors(java.util.stream.Collectors) ApiStreamObserver(com.google.api.gax.rpc.ApiStreamObserver) ClassNames(com.google.api.generator.gapic.composer.utils.ClassNames) List(java.util.List) Optional(java.util.Optional) Any(com.google.protobuf.Any) GapicContext(com.google.api.generator.gapic.model.GapicContext) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) VaporReference(com.google.api.generator.engine.ast.VaporReference) TypeNode(com.google.api.generator.engine.ast.TypeNode) BeforeClass(org.junit.BeforeClass) BidiStreamingCallable(com.google.api.gax.rpc.BidiStreamingCallable) Kind(com.google.api.generator.gapic.model.GapicClass.Kind) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) Operation(com.google.longrunning.Operation) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Expr(com.google.api.generator.engine.ast.Expr) Lists(com.google.common.collect.Lists) ClientStreamingCallable(com.google.api.gax.rpc.ClientStreamingCallable) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) LineComment(com.google.api.generator.engine.ast.LineComment) Before(org.junit.Before) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) AbstractMessage(com.google.protobuf.AbstractMessage) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) IOException(java.io.IOException) Test(org.junit.Test) 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) ExecutionException(java.util.concurrent.ExecutionException) Statement(com.google.api.generator.engine.ast.Statement) Service(com.google.api.generator.gapic.model.Service) InvalidArgumentException(com.google.api.gax.rpc.InvalidArgumentException) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Preconditions(com.google.common.base.Preconditions) StatusCode(com.google.api.gax.rpc.StatusCode) Assert(org.junit.Assert) Message(com.google.api.generator.gapic.model.Message) Collections(java.util.Collections) 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) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) 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) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr)

Example 8 with Message

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

the class AbstractServiceStubClassComposer method createTypes.

private static TypeStore createTypes(Service service, Map<String, Message> messageTypes) {
    List<Class<?>> concreteClazzes = Arrays.asList(BackgroundResource.class, BetaApi.class, BidiStreamingCallable.class, ClientStreamingCallable.class, Generated.class, Operation.class, OperationCallable.class, ServerStreamingCallable.class, UnaryCallable.class, UnsupportedOperationException.class);
    TypeStore typeStore = new TypeStore(concreteClazzes);
    typeStore.put("com.google.longrunning.stub", "OperationsStub");
    // Pagination types.
    typeStore.putAll(service.pakkage(), service.methods().stream().filter(m -> m.isPaged()).map(m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())).collect(Collectors.toList()), true, ClassNames.getServiceClientClassName(service));
    return typeStore;
}
Also used : Arrays(java.util.Arrays) 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) Reference(com.google.api.generator.engine.ast.Reference) PackageChecker(com.google.api.generator.gapic.composer.utils.PackageChecker) Operation(com.google.longrunning.Operation) ArrayList(java.util.ArrayList) BackgroundResource(com.google.api.gax.core.BackgroundResource) StubCommentComposer(com.google.api.generator.gapic.composer.comment.StubCommentComposer) 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) ImmutableList(com.google.common.collect.ImmutableList) ClientStreamingCallable(com.google.api.gax.rpc.ClientStreamingCallable) Map(java.util.Map) ServerStreamingCallable(com.google.api.gax.rpc.ServerStreamingCallable) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) Iterator(java.util.Iterator) LongRunningClient(com.google.api.gax.rpc.LongRunningClient) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) Collectors(java.util.stream.Collectors) GapicClass(com.google.api.generator.gapic.model.GapicClass) OperationCallable(com.google.api.gax.rpc.OperationCallable) UnaryCallable(com.google.api.gax.rpc.UnaryCallable) ClassNames(com.google.api.generator.gapic.composer.utils.ClassNames) Service(com.google.api.generator.gapic.model.Service) List(java.util.List) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) GapicContext(com.google.api.generator.gapic.model.GapicContext) Message(com.google.api.generator.gapic.model.Message) Collections(java.util.Collections) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) GapicClass(com.google.api.generator.gapic.model.GapicClass)

Example 9 with Message

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

the class AbstractServiceClientClassComposer method createNestedPagingClasses.

private static List<ClassDefinition> createNestedPagingClasses(Service service, Map<String, Message> messageTypes, TypeStore typeStore) {
    List<ClassDefinition> nestedClasses = new ArrayList<>();
    for (Method method : service.methods()) {
        if (!method.isPaged()) {
            continue;
        }
        // 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();
        nestedClasses.add(createNestedRpcPagedResponseClass(method, repeatedResponseType, messageTypes, typeStore));
        nestedClasses.add(createNestedRpcPageClass(method, repeatedResponseType, messageTypes, typeStore));
        nestedClasses.add(createNestedRpcFixedSizeCollectionClass(method, repeatedResponseType, messageTypes, typeStore));
    }
    return nestedClasses;
}
Also used : Field(com.google.api.generator.gapic.model.Field) Message(com.google.api.generator.gapic.model.Message) ArrayList(java.util.ArrayList) Method(com.google.api.generator.gapic.model.Method) TypeNode(com.google.api.generator.engine.ast.TypeNode) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition)

Example 10 with Message

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

the class ServiceClientTestClassComposer method constructRpcTestCheckerLogic.

@Override
protected List<Statement> constructRpcTestCheckerLogic(Method method, Service service, boolean isRequestArg, Map<String, VariableExpr> classMemberVarExprs, VariableExpr requestVarExpr, Message requestMessage, List<VariableExpr> argExprs) {
    List<Expr> methodExprs = new ArrayList<>();
    List<Statement> methodStatements = new ArrayList<>();
    // Construct the request checker logic.
    VariableExpr actualRequestsVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(ConcreteReference.withClazz(AbstractMessage.class))).build())).setName("actualRequests").build());
    methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualRequestsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(getMockServiceVarName(service))).setMethodName("getRequests").setReturnType(actualRequestsVarExpr.type()).build()).build());
    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(actualRequestsVarExpr).setMethodName("size").build()).build());
    VariableExpr actualRequestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("actualRequest").build());
    Expr getFirstRequestExpr = MethodInvocationExpr.builder().setExprReferenceExpr(actualRequestsVarExpr).setMethodName("get").setArguments(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build())).setReturnType(FIXED_TYPESTORE.get("AbstractMessage")).build();
    getFirstRequestExpr = CastExpr.builder().setType(method.inputType()).setExpr(getFirstRequestExpr).build();
    methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualRequestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(getFirstRequestExpr).build());
    methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    methodExprs.clear();
    methodStatements.add(EMPTY_LINE_STATEMENT);
    // Assert field equality.
    if (isRequestArg) {
        // TODO(miraleung): Replace these with a simple request object equals?
        Preconditions.checkNotNull(requestVarExpr);
        Preconditions.checkNotNull(requestMessage);
        for (Field field : requestMessage.fields()) {
            String fieldGetterMethodNamePatternTemp = "get%s";
            if (field.isRepeated()) {
                fieldGetterMethodNamePatternTemp = field.isMap() ? "get%sMap" : "get%sList";
            }
            final String fieldGetterMethodNamePattern = fieldGetterMethodNamePatternTemp;
            Function<VariableExpr, Expr> checkExprFn = v -> MethodInvocationExpr.builder().setExprReferenceExpr(v).setMethodName(String.format(fieldGetterMethodNamePattern, JavaStyle.toUpperCamelCase(field.name()))).build();
            Expr expectedFieldExpr = checkExprFn.apply(requestVarExpr);
            Expr actualFieldExpr = checkExprFn.apply(actualRequestVarExpr);
            List<Expr> assertEqualsArguments = new ArrayList<>();
            assertEqualsArguments.add(expectedFieldExpr);
            assertEqualsArguments.add(actualFieldExpr);
            if (TypeNode.isFloatingPointType(field.type())) {
                boolean isFloat = field.type().equals(TypeNode.FLOAT);
                assertEqualsArguments.add(ValueExpr.withValue(PrimitiveValue.builder().setType(isFloat ? TypeNode.FLOAT : TypeNode.DOUBLE).setValue(String.format("0.0001%s", isFloat ? "f" : "")).build()));
            }
            methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(assertEqualsArguments).build());
        }
    } else {
        for (VariableExpr argVarExpr : argExprs) {
            Variable variable = argVarExpr.variable();
            String fieldGetterMethodNamePattern = "get%s";
            if (LIST_TYPE.isSupertypeOrEquals(variable.type())) {
                fieldGetterMethodNamePattern = "get%sList";
            } else if (MAP_TYPE.isSupertypeOrEquals(variable.type())) {
                fieldGetterMethodNamePattern = "get%sMap";
            }
            Expr actualFieldExpr = MethodInvocationExpr.builder().setExprReferenceExpr(actualRequestVarExpr).setMethodName(String.format(fieldGetterMethodNamePattern, JavaStyle.toUpperCamelCase(variable.identifier().name()))).build();
            Expr expectedFieldExpr = argVarExpr;
            if (RESOURCE_NAME_TYPE.isSupertypeOrEquals(argVarExpr.type())) {
                expectedFieldExpr = MethodInvocationExpr.builder().setExprReferenceExpr(argVarExpr).setMethodName("toString").build();
            }
            methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(expectedFieldExpr, actualFieldExpr).build());
        }
    }
    // Assert header equality.
    Expr headerKeyExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ApiClientHeaderProvider")).setMethodName("getDefaultApiClientHeaderKey").build();
    Expr headerPatternExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_GRPC_TYPESTORE.get("GaxGrpcProperties")).setMethodName("getDefaultApiClientHeaderPattern").build();
    Expr headerSentExpr = MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get("channelProvider")).setMethodName("isHeaderSent").setArguments(headerKeyExpr, headerPatternExpr).build();
    methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertTrue").setArguments(headerSentExpr).build());
    methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    methodExprs.clear();
    return methodStatements;
}
Also used : LocalChannelProvider(com.google.api.gax.grpc.testing.LocalChannelProvider) Arrays(java.util.Arrays) BiFunction(java.util.function.BiFunction) Variable(com.google.api.generator.engine.ast.Variable) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) GaxGrpcProperties(com.google.api.gax.grpc.GaxGrpcProperties) DefaultValueComposer(com.google.api.generator.gapic.composer.defaultvalue.DefaultValueComposer) Field(com.google.api.generator.gapic.model.Field) 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) Map(java.util.Map) MockServiceHelper(com.google.api.gax.grpc.testing.MockServiceHelper) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) Collectors(java.util.stream.Collectors) ClassNames(com.google.api.generator.gapic.composer.utils.ClassNames) List(java.util.List) GapicContext(com.google.api.generator.gapic.model.GapicContext) MockGrpcService(com.google.api.gax.grpc.testing.MockGrpcService) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) AbstractServiceClientTestClassComposer(com.google.api.generator.gapic.composer.common.AbstractServiceClientTestClassComposer) Function(java.util.function.Function) MockStreamObserver(com.google.api.gax.grpc.testing.MockStreamObserver) ArrayList(java.util.ArrayList) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) InstanceofExpr(com.google.api.generator.engine.ast.InstanceofExpr) AbstractMessage(com.google.protobuf.AbstractMessage) CastExpr(com.google.api.generator.engine.ast.CastExpr) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) ResourceName(com.google.api.generator.gapic.model.ResourceName) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) Statement(com.google.api.generator.engine.ast.Statement) Service(com.google.api.generator.gapic.model.Service) TreeMap(java.util.TreeMap) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Preconditions(com.google.common.base.Preconditions) StatusCode(com.google.api.gax.rpc.StatusCode) Message(com.google.api.generator.gapic.model.Message) Variable(com.google.api.generator.engine.ast.Variable) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) 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) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) InstanceofExpr(com.google.api.generator.engine.ast.InstanceofExpr) CastExpr(com.google.api.generator.engine.ast.CastExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) List(java.util.List) ArrayList(java.util.ArrayList)

Aggregations

Message (com.google.api.generator.gapic.model.Message)123 ResourceName (com.google.api.generator.gapic.model.ResourceName)85 TypeNode (com.google.api.generator.engine.ast.TypeNode)74 Test (org.junit.Test)68 Method (com.google.api.generator.gapic.model.Method)60 FileDescriptor (com.google.protobuf.Descriptors.FileDescriptor)44 HashSet (java.util.HashSet)39 ArrayList (java.util.ArrayList)36 Service (com.google.api.generator.gapic.model.Service)35 List (java.util.List)34 Expr (com.google.api.generator.engine.ast.Expr)32 Field (com.google.api.generator.gapic.model.Field)31 Descriptors (com.google.protobuf.Descriptors)30 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)29 MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)26 ServiceDescriptor (com.google.protobuf.Descriptors.ServiceDescriptor)26 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)25 ExprStatement (com.google.api.generator.engine.ast.ExprStatement)25 Statement (com.google.api.generator.engine.ast.Statement)24 HashMap (java.util.HashMap)23