Search in sources :

Example 46 with Statement

use of com.google.api.generator.engine.ast.Statement 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)

Example 47 with Statement

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

the class HttpJsonServiceStubClassComposer method createBodyFieldsExtractorClassInstance.

private Expr createBodyFieldsExtractorClassInstance(Method method, TypeNode extractorReturnType, Set<HttpBinding> httpBindingFieldNames, String serializerMethodName, boolean asteriskBody) {
    List<Statement> bodyStatements = new ArrayList<>();
    Expr returnExpr = null;
    Expr serializerExpr = MethodInvocationExpr.builder().setMethodName("create").setStaticReferenceType(FIXED_REST_TYPESTORE.get(ProtoRestSerializer.class.getSimpleName())).build();
    VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
    Expr bodyRequestExpr = requestVarExpr;
    String requestMethodPrefix = "get";
    String bodyParamName = null;
    if (asteriskBody) {
        bodyRequestExpr = MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr).setMethodName("toBuilder").build();
        // In case of `body: "*"` case we send the whole request message as a body, minus the fields
        // in the path, therefore the "clear" prefix here.
        requestMethodPrefix = "clear";
    }
    Expr prevExpr = bodyRequestExpr;
    for (HttpBinding httpBindingFieldName : httpBindingFieldNames) {
        // Handle foo.bar cases by descending into the subfields.
        MethodInvocationExpr.Builder requestFieldMethodExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(prevExpr);
        bodyParamName = JavaStyle.toLowerCamelCase(httpBindingFieldName.name());
        String[] descendantFields = httpBindingFieldName.name().split("\\.");
        if (asteriskBody && descendantFields.length > 1) {
            // well-defined case, and it is generally safer to send more than less in such case.
            continue;
        }
        for (int i = 0; i < descendantFields.length; i++) {
            String currFieldName = descendantFields[i];
            String bindingFieldMethodName = String.format("%s%s", requestMethodPrefix, JavaStyle.toUpperCamelCase(currFieldName));
            requestFieldMethodExprBuilder = requestFieldMethodExprBuilder.setMethodName(bindingFieldMethodName);
            if (i < descendantFields.length - 1) {
                requestFieldMethodExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(requestFieldMethodExprBuilder.build());
            }
        }
        prevExpr = requestFieldMethodExprBuilder.build();
    }
    if (httpBindingFieldNames.isEmpty() && !asteriskBody) {
        returnExpr = ValueExpr.createNullExpr();
    } else {
        ImmutableList.Builder<Expr> paramsPutArgs = ImmutableList.builder();
        if (asteriskBody) {
            prevExpr = MethodInvocationExpr.builder().setExprReferenceExpr(prevExpr).setMethodName("build").build();
            bodyParamName = "*";
        }
        paramsPutArgs.add(ValueExpr.withValue(StringObjectValue.withValue(bodyParamName)));
        paramsPutArgs.add(prevExpr);
        returnExpr = MethodInvocationExpr.builder().setExprReferenceExpr(serializerExpr).setMethodName(serializerMethodName).setArguments(paramsPutArgs.build()).setReturnType(extractorReturnType).build();
    }
    // (https://github.com/googleapis/gax-java/blob/12b18ee255d3fabe13bb3969df40753b29f830d5/gax-httpjson/src/main/java/com/google/api/gax/httpjson/FieldsExtractor.java).
    return LambdaExpr.builder().setArguments(requestVarExpr.toBuilder().setIsDecl(true).build()).setBody(bodyStatements).setReturnExpr(returnExpr).build();
}
Also used : ProtoRestSerializer(com.google.api.gax.httpjson.ProtoRestSerializer) IfStatement(com.google.api.generator.engine.ast.IfStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) ImmutableList(com.google.common.collect.ImmutableList) ArrayList(java.util.ArrayList) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) HttpBinding(com.google.api.generator.gapic.model.HttpBindings.HttpBinding) VariableExpr(com.google.api.generator.engine.ast.VariableExpr)

Example 48 with Statement

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

the class HttpJsonServiceStubClassComposer method createFieldsExtractorClassInstance.

private Expr createFieldsExtractorClassInstance(Method method, TypeNode extractorReturnType, Set<HttpBinding> httpBindingFieldNames, String serializerMethodName) {
    List<Statement> bodyStatements = new ArrayList<>();
    VariableExpr fieldsVarExpr = VariableExpr.withVariable(Variable.builder().setName("fields").setType(extractorReturnType).build());
    Expr fieldsAssignExpr = AssignmentExpr.builder().setVariableExpr(fieldsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(FIXED_REST_TYPESTORE.get(HashMap.class.getSimpleName())).setIsGeneric(true).build()).build();
    bodyStatements.add(ExprStatement.withExpr(fieldsAssignExpr));
    TypeNode serializerVarType = TypeNode.withReference(ConcreteReference.builder().setClazz(ProtoRestSerializer.class).setGenerics(method.inputType().reference()).build());
    VariableExpr serializerVarExpr = VariableExpr.withVariable(Variable.builder().setName("serializer").setType(serializerVarType).build());
    Expr serializerAssignExpr = AssignmentExpr.builder().setVariableExpr(serializerVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_REST_TYPESTORE.get(ProtoRestSerializer.class.getSimpleName())).setMethodName("create").setReturnType(serializerVarType).build()).build();
    bodyStatements.add(ExprStatement.withExpr(serializerAssignExpr));
    VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
    for (HttpBinding httpBindingFieldName : httpBindingFieldNames) {
        // Handle foo.bar cases by descending into the subfields.
        MethodInvocationExpr.Builder requestFieldGetterExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr);
        MethodInvocationExpr.Builder requestFieldHasExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr);
        String[] descendantFields = httpBindingFieldName.name().split("\\.");
        for (int i = 0; i < descendantFields.length; i++) {
            String currFieldName = descendantFields[i];
            String bindingFieldMethodName = String.format("get%s", JavaStyle.toUpperCamelCase(currFieldName));
            requestFieldGetterExprBuilder = requestFieldGetterExprBuilder.setMethodName(bindingFieldMethodName);
            String bindingFieldHasMethodName = (i < descendantFields.length - 1) ? bindingFieldMethodName : String.format("has%s", JavaStyle.toUpperCamelCase(currFieldName));
            requestFieldHasExprBuilder = requestFieldHasExprBuilder.setMethodName(bindingFieldHasMethodName).setReturnType(TypeNode.BOOLEAN);
            if (i < descendantFields.length - 1) {
                requestFieldGetterExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(requestFieldGetterExprBuilder.build());
                requestFieldHasExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(requestFieldHasExprBuilder.build());
            }
        }
        MethodInvocationExpr requestBuilderExpr = requestFieldGetterExprBuilder.build();
        MethodInvocationExpr requestHasExpr = requestFieldHasExprBuilder.build();
        ImmutableList.Builder<Expr> paramsPutArgs = ImmutableList.builder();
        paramsPutArgs.add(fieldsVarExpr);
        paramsPutArgs.add(ValueExpr.withValue(StringObjectValue.withValue(JavaStyle.toLowerCamelCase(httpBindingFieldName.name()))));
        paramsPutArgs.add(requestBuilderExpr);
        Expr paramsPutExpr = MethodInvocationExpr.builder().setExprReferenceExpr(serializerVarExpr).setMethodName(serializerMethodName).setArguments(paramsPutArgs.build()).setReturnType(extractorReturnType).build();
        if (httpBindingFieldName.isOptional()) {
            bodyStatements.add(IfStatement.builder().setConditionExpr(requestHasExpr).setBody(Arrays.asList(ExprStatement.withExpr(paramsPutExpr))).build());
        } else {
            bodyStatements.add(ExprStatement.withExpr(paramsPutExpr));
        }
    }
    // (https://github.com/googleapis/gax-java/blob/12b18ee255d3fabe13bb3969df40753b29f830d5/gax-httpjson/src/main/java/com/google/api/gax/httpjson/FieldsExtractor.java).
    return LambdaExpr.builder().setArguments(requestVarExpr.toBuilder().setIsDecl(true).build()).setBody(bodyStatements).setReturnExpr(fieldsVarExpr).build();
}
Also used : ProtoRestSerializer(com.google.api.gax.httpjson.ProtoRestSerializer) IfStatement(com.google.api.generator.engine.ast.IfStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) ImmutableList(com.google.common.collect.ImmutableList) ArrayList(java.util.ArrayList) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) HttpBinding(com.google.api.generator.gapic.model.HttpBindings.HttpBinding) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 49 with Statement

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

the class HttpJsonServiceStubClassComposer method setOperationSnapshotFactoryExpr.

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

Example 50 with Statement

use of com.google.api.generator.engine.ast.Statement 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) {
    VariableExpr actualRequestsVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(TypeNode.STRING.reference())).build())).setName("actualRequests").build());
    List<Expr> methodExprs = new ArrayList<>();
    methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualRequestsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(getMockServiceVarName(service))).setMethodName("getRequestPaths").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());
    List<Statement> methodStatements = new ArrayList<>();
    methodStatements.addAll(methodExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
    methodExprs.clear();
    methodStatements.add(EMPTY_LINE_STATEMENT);
    VariableExpr apiClientHeaderKeyVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.STRING).setName("apiClientHeaderKey").build());
    AssignmentExpr apiClientHeaderKeyAssignExpr = AssignmentExpr.builder().setVariableExpr(apiClientHeaderKeyVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setMethodName("next").setReturnType(apiClientHeaderKeyVarExpr.type()).setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("iterator").setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("get").setArguments(MethodInvocationExpr.builder().setMethodName("getDefaultApiClientHeaderKey").setStaticReferenceType(FIXED_REST_TYPESTORE.get("ApiClientHeaderProvider")).build()).setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("getRequestHeaders").setExprReferenceExpr(classMemberVarExprs.get(getMockServiceVarName(service))).build()).build()).build()).build()).build();
    methodExprs.add(apiClientHeaderKeyAssignExpr);
    methodExprs.add(MethodInvocationExpr.builder().setMethodName("assertTrue").setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setArguments(MethodInvocationExpr.builder().setMethodName("matches").setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("matcher").setArguments(apiClientHeaderKeyVarExpr).setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("getDefaultApiClientHeaderPattern").setStaticReferenceType(FIXED_REST_TYPESTORE.get("GaxHttpJsonProperties")).build()).build()).build()).build());
    methodStatements.addAll(methodExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
    methodExprs.clear();
    return methodStatements;
}
Also used : 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) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) ArrayList(java.util.ArrayList) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr)

Aggregations

ExprStatement (com.google.api.generator.engine.ast.ExprStatement)69 Statement (com.google.api.generator.engine.ast.Statement)69 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)65 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)58 MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)53 Expr (com.google.api.generator.engine.ast.Expr)48 ArrayList (java.util.ArrayList)46 ValueExpr (com.google.api.generator.engine.ast.ValueExpr)44 IfStatement (com.google.api.generator.engine.ast.IfStatement)43 TypeNode (com.google.api.generator.engine.ast.TypeNode)42 CommentStatement (com.google.api.generator.engine.ast.CommentStatement)41 TryCatchStatement (com.google.api.generator.engine.ast.TryCatchStatement)36 NewObjectExpr (com.google.api.generator.engine.ast.NewObjectExpr)32 List (java.util.List)30 ForStatement (com.google.api.generator.engine.ast.ForStatement)29 Message (com.google.api.generator.gapic.model.Message)25 Variable (com.google.api.generator.engine.ast.Variable)24 CastExpr (com.google.api.generator.engine.ast.CastExpr)23 ConcreteReference (com.google.api.generator.engine.ast.ConcreteReference)23 EmptyLineStatement (com.google.api.generator.engine.ast.EmptyLineStatement)23