Search in sources :

Example 31 with TypeNode

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

the class JavaWriterVisitor method visit.

@Override
public void visit(VariableExpr variableExpr) {
    Variable variable = variableExpr.variable();
    TypeNode type = variable.type();
    ScopeNode scope = variableExpr.scope();
    // VariableExpr will handle isDecl and exprReferenceExpr edge cases.
    if (variableExpr.isDecl()) {
        if (!scope.equals(ScopeNode.LOCAL)) {
            scope.accept(this);
            space();
        }
        if (variableExpr.isStatic()) {
            buffer.append(STATIC);
            space();
        }
        if (variableExpr.isFinal()) {
            buffer.append(FINAL);
            space();
        }
        if (variableExpr.isVolatile()) {
            buffer.append(VOLATILE);
            space();
        }
        type.accept(this);
        if (!variableExpr.templateNodes().isEmpty()) {
            leftAngle();
            IntStream.range(0, variableExpr.templateNodes().size()).forEach(i -> {
                variableExpr.templateNodes().get(i).accept(this);
                if (i < variableExpr.templateNodes().size() - 1) {
                    buffer.append(COMMA);
                    space();
                }
            });
            rightAngle();
        }
        space();
    } else {
        // Expression or static reference.
        if (variableExpr.exprReferenceExpr() != null) {
            variableExpr.exprReferenceExpr().accept(this);
            buffer.append(DOT);
        } else if (variableExpr.staticReferenceType() != null) {
            variableExpr.staticReferenceType().accept(this);
            buffer.append(DOT);
        }
    }
    variable.identifier().accept(this);
}
Also used : Variable(com.google.api.generator.engine.ast.Variable) TypeNode(com.google.api.generator.engine.ast.TypeNode) ScopeNode(com.google.api.generator.engine.ast.ScopeNode)

Example 32 with TypeNode

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

the class JavaWriterVisitor method visit.

/**
 * =============================== OTHER ===============================
 */
@Override
public void visit(MethodDefinition methodDefinition) {
    // Header comments, if any.
    statements(methodDefinition.headerCommentStatements().stream().collect(Collectors.toList()));
    // Annotations, if any.
    annotations(methodDefinition.annotations());
    // Method scope.
    methodDefinition.scope().accept(this);
    space();
    // Templates, if any.
    if (!methodDefinition.templateIdentifiers().isEmpty()) {
        leftAngle();
        IntStream.range(0, methodDefinition.templateIdentifiers().size()).forEach(i -> {
            methodDefinition.templateIdentifiers().get(i).accept(this);
            if (i < methodDefinition.templateIdentifiers().size() - 1) {
                buffer.append(COMMA);
                space();
            }
        });
        rightAngle();
        space();
    }
    // Modifiers.
    if (methodDefinition.isAbstract()) {
        buffer.append(ABSTRACT);
        space();
    }
    if (methodDefinition.isStatic()) {
        buffer.append(STATIC);
        space();
    }
    if (methodDefinition.isFinal()) {
        buffer.append(FINAL);
        space();
    }
    if (!methodDefinition.isConstructor()) {
        methodDefinition.returnType().accept(this);
        if (!methodDefinition.returnTemplateIdentifiers().isEmpty()) {
            leftAngle();
            IntStream.range(0, methodDefinition.returnTemplateIdentifiers().size()).forEach(i -> {
                methodDefinition.returnTemplateIdentifiers().get(i).accept(this);
                if (i < methodDefinition.returnTemplateIdentifiers().size() - 1) {
                    buffer.append(COMMA);
                    space();
                }
            });
            rightAngle();
        }
        space();
    }
    // Method name.
    methodDefinition.methodIdentifier().accept(this);
    leftParen();
    // Arguments, if any.
    int numArguments = methodDefinition.arguments().size();
    for (int i = 0; i < numArguments; i++) {
        methodDefinition.arguments().get(i).accept(this);
        if (i < numArguments - 1) {
            buffer.append(COMMA);
            space();
        }
    }
    rightParen();
    // Thrown exceptions.
    if (!methodDefinition.throwsExceptions().isEmpty()) {
        space();
        buffer.append(THROWS);
        space();
        Iterator<TypeNode> exceptionIter = methodDefinition.throwsExceptions().iterator();
        while (exceptionIter.hasNext()) {
            TypeNode exceptionType = exceptionIter.next();
            exceptionType.accept(this);
            if (exceptionIter.hasNext()) {
                buffer.append(COMMA);
                space();
            }
        }
    }
    if (methodDefinition.isAbstract() && methodDefinition.body().isEmpty()) {
        semicolon();
        newline();
        return;
    }
    // Method body.
    space();
    leftBrace();
    newline();
    statements(methodDefinition.body());
    if (methodDefinition.returnExpr() != null) {
        ExprStatement.withExpr(methodDefinition.returnExpr()).accept(this);
    }
    rightBrace();
    newline();
    newline();
}
Also used : TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 33 with TypeNode

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

the class ClientLibraryPackageInfoComposer method createPackageInfoJavadoc.

private static CommentStatement createPackageInfoJavadoc(GapicContext context) {
    JavaDocComment.Builder javaDocCommentBuilder = JavaDocComment.builder();
    if (context.hasServiceYamlProto() && !Strings.isNullOrEmpty(context.serviceYamlProto().getTitle())) {
        javaDocCommentBuilder = javaDocCommentBuilder.addComment(String.format(PACKAGE_INFO_TITLE_PATTERN, context.serviceYamlProto().getTitle()));
    }
    javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(PACKAGE_INFO_DESCRIPTION);
    for (Service service : context.services()) {
        String javaClientName = ClassNames.getServiceClientClassName(service);
        javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(String.format("%s %s %s", DIVIDER, javaClientName, DIVIDER));
        // TODO(miraleung): Replace this with a comment converter when we support CommonMark.
        if (service.hasDescription()) {
            String[] descriptionParagraphs = service.description().split("\\n\\n");
            for (int i = 0; i < descriptionParagraphs.length; i++) {
                boolean startsWithItemizedList = descriptionParagraphs[i].startsWith(" * ");
                // Split by listed items, then join newlines.
                List<String> listItems = Stream.of(descriptionParagraphs[i].split("\\n \\*")).map(s -> s.replace("\n", "")).collect(Collectors.toList());
                if (startsWithItemizedList) {
                    // Remove the first asterisk.
                    listItems.set(0, listItems.get(0).substring(2));
                }
                if (!startsWithItemizedList) {
                    if (i == 0) {
                        javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(String.format(SERVICE_DESCRIPTION_HEADER_PATTERN, listItems.get(0)));
                    } else {
                        javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(listItems.get(0));
                    }
                }
                if (listItems.size() > 1 || startsWithItemizedList) {
                    javaDocCommentBuilder = javaDocCommentBuilder.addUnorderedList(listItems.subList(startsWithItemizedList ? 0 : 1, listItems.size()));
                }
            }
        }
        javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(String.format(SAMPLE_CODE_HEADER_PATTERN, javaClientName));
        TypeNode clientType = TypeNode.withReference(VaporReference.builder().setPakkage(service.pakkage()).setName(ClassNames.getServiceClientClassName(service)).build());
        Sample packageInfoSampleCode = ServiceClientHeaderSampleComposer.composeClassHeaderSample(service, clientType, context.resourceNames(), context.messages());
        javaDocCommentBuilder.addSampleCode(SampleCodeWriter.writeInlineSample(packageInfoSampleCode.body()));
    }
    return CommentStatement.withComment(javaDocCommentBuilder.build());
}
Also used : ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) VaporReference(com.google.api.generator.engine.ast.VaporReference) TypeNode(com.google.api.generator.engine.ast.TypeNode) ServiceClientHeaderSampleComposer(com.google.api.generator.gapic.composer.samplecode.ServiceClientHeaderSampleComposer) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) JavaDocComment(com.google.api.generator.engine.ast.JavaDocComment) Sample(com.google.api.generator.gapic.model.Sample) Collectors(java.util.stream.Collectors) Strings(com.google.common.base.Strings) ClassNames(com.google.api.generator.gapic.composer.utils.ClassNames) Service(com.google.api.generator.gapic.model.Service) List(java.util.List) Generated(javax.annotation.Generated) Stream(java.util.stream.Stream) SampleCodeWriter(com.google.api.generator.gapic.composer.samplecode.SampleCodeWriter) GapicPackageInfo(com.google.api.generator.gapic.model.GapicPackageInfo) PackageInfoDefinition(com.google.api.generator.engine.ast.PackageInfoDefinition) Preconditions(com.google.common.base.Preconditions) GapicContext(com.google.api.generator.gapic.model.GapicContext) JavaDocComment(com.google.api.generator.engine.ast.JavaDocComment) Sample(com.google.api.generator.gapic.model.Sample) Service(com.google.api.generator.gapic.model.Service) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 34 with TypeNode

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

the class MockServiceImplClassComposer method createHandleObjectStatement.

private static Statement createHandleObjectStatement(Method protoMethod, VariableExpr requestArgVarExpr, VariableExpr responseObserverVarExpr, VariableExpr localResponseVarExpr) {
    List<Expr> ifBodyExprs = new ArrayList<>();
    boolean isAnonymousClass = requestArgVarExpr == null;
    if (!isAnonymousClass) {
        ifBodyExprs.add(MethodInvocationExpr.builder().setMethodName("add").setArguments(Arrays.asList(requestArgVarExpr)).setExprReferenceExpr(requestsVarExpr).build());
    }
    ifBodyExprs.add(MethodInvocationExpr.builder().setMethodName("onNext").setArguments(Arrays.asList(CastExpr.builder().setType(protoMethod.outputType()).setExpr(localResponseVarExpr).build())).setExprReferenceExpr(responseObserverVarExpr).build());
    if (!isAnonymousClass) {
        ifBodyExprs.add(MethodInvocationExpr.builder().setMethodName("onCompleted").setExprReferenceExpr(responseObserverVarExpr).build());
    }
    TypeNode exceptionType = TypeNode.withReference(ConcreteReference.withClazz(Exception.class));
    // Constructs `response == null ? "" : response.getClass().getName()`.
    Expr actualResponseTypeString = TernaryExpr.builder().setConditionExpr(RelationalOperationExpr.equalToWithExprs(localResponseVarExpr, ValueExpr.createNullExpr())).setThenExpr(ValueExpr.withValue(StringObjectValue.withValue("null"))).setElseExpr(MethodInvocationExpr.builder().setExprReferenceExpr(MethodInvocationExpr.builder().setExprReferenceExpr(localResponseVarExpr).setMethodName("getClass").build()).setMethodName("getName").setReturnType(TypeNode.STRING).build()).build();
    Function<TypeNode, Expr> typeToStrFn = t -> MethodInvocationExpr.builder().setExprReferenceExpr(VariableExpr.builder().setStaticReferenceType(t).setVariable(Variable.builder().setType(TypeNode.CLASS_OBJECT).setName("class").build()).build()).setMethodName("getName").setReturnType(TypeNode.STRING).build();
    Expr expectedResponseTypeOneString = typeToStrFn.apply(protoMethod.outputType());
    Expr expectedResponseTypeTwoString = typeToStrFn.apply(exceptionType);
    Expr newExceptionExpr = NewObjectExpr.builder().setType(TypeNode.withReference(ConcreteReference.withClazz(IllegalArgumentException.class))).setArguments(// Operation.class.getName(), Exception.class.getName());
    MethodInvocationExpr.builder().setStaticReferenceType(TypeNode.STRING).setMethodName("format").setArguments(ValueExpr.withValue(StringObjectValue.withValue("Unrecognized response type %s for method " + protoMethod.name() + ", expected %s or %s")), actualResponseTypeString, expectedResponseTypeOneString, expectedResponseTypeTwoString).build()).build();
    return IfStatement.builder().setConditionExpr(InstanceofExpr.builder().setExpr(localResponseVarExpr).setCheckType(protoMethod.outputType()).build()).setBody(ifBodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).addElseIf(InstanceofExpr.builder().setExpr(localResponseVarExpr).setCheckType(exceptionType).build(), Arrays.asList(ExprStatement.withExpr(MethodInvocationExpr.builder().setMethodName("onError").setArguments(Arrays.asList(CastExpr.builder().setType(exceptionType).setExpr(localResponseVarExpr).build())).setExprReferenceExpr(responseObserverVarExpr).build()))).setElseBody(Arrays.asList(ExprStatement.withExpr(MethodInvocationExpr.builder().setMethodName("onError").setExprReferenceExpr(responseObserverVarExpr).setArguments(Arrays.asList(newExceptionExpr)).build()))).build();
}
Also used : VaporReference(com.google.api.generator.engine.ast.VaporReference) IfStatement(com.google.api.generator.engine.ast.IfStatement) Arrays(java.util.Arrays) BetaApi(com.google.api.core.BetaApi) TypeNode(com.google.api.generator.engine.ast.TypeNode) 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) Operation(com.google.longrunning.Operation) ThisObjectValue(com.google.api.generator.engine.ast.ThisObjectValue) Variable(com.google.api.generator.engine.ast.Variable) Function(java.util.function.Function) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) ArrayList(java.util.ArrayList) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) 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) StreamObserver(io.grpc.stub.StreamObserver) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) Stream(com.google.api.generator.gapic.model.Method.Stream) LinkedList(java.util.LinkedList) ClassComposer(com.google.api.generator.gapic.composer.common.ClassComposer) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) 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) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) Collectors(java.util.stream.Collectors) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) GapicClass(com.google.api.generator.gapic.model.GapicClass) Statement(com.google.api.generator.engine.ast.Statement) 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) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) GapicContext(com.google.api.generator.gapic.model.GapicContext) Queue(java.util.Queue) ServerServiceDefinition(io.grpc.ServerServiceDefinition) 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) InstanceofExpr(com.google.api.generator.engine.ast.InstanceofExpr) CastExpr(com.google.api.generator.engine.ast.CastExpr) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ArrayList(java.util.ArrayList) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 35 with TypeNode

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

the class MockServiceImplClassComposer method createGenericClientStreamingProtoMethodOverride.

private static MethodDefinition createGenericClientStreamingProtoMethodOverride(Method protoMethod, VariableExpr responseObserverVarExpr, VariableExpr localResponseVarExpr) {
    ConcreteReference streamObserverRef = ConcreteReference.withClazz(StreamObserver.class);
    TypeNode returnType = TypeNode.withReference(streamObserverRef.copyAndSetGenerics(Arrays.asList(protoMethod.inputType().reference())));
    VariableExpr requestObserverVarExpr = VariableExpr.withVariable(Variable.builder().setName("requestObserver").setType(returnType).build());
    return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(returnType).setName(JavaStyle.toLowerCamelCase(protoMethod.name())).setArguments(Arrays.asList(responseObserverVarExpr.toBuilder().setIsFinal(true).setIsDecl(true).build())).setBody(Arrays.asList(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(requestObserverVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(createStreamObserverClassInstance(protoMethod, returnType, responseObserverVarExpr, localResponseVarExpr)).build()))).setReturnExpr(requestObserverVarExpr).build();
}
Also used : VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference)

Aggregations

TypeNode (com.google.api.generator.engine.ast.TypeNode)232 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)119 MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)111 Test (org.junit.Test)103 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)84 Message (com.google.api.generator.gapic.model.Message)81 ArrayList (java.util.ArrayList)81 Expr (com.google.api.generator.engine.ast.Expr)77 ValueExpr (com.google.api.generator.engine.ast.ValueExpr)77 Method (com.google.api.generator.gapic.model.Method)72 NewObjectExpr (com.google.api.generator.engine.ast.NewObjectExpr)68 ResourceName (com.google.api.generator.gapic.model.ResourceName)65 ExprStatement (com.google.api.generator.engine.ast.ExprStatement)64 List (java.util.List)63 ConcreteReference (com.google.api.generator.engine.ast.ConcreteReference)61 MethodDefinition (com.google.api.generator.engine.ast.MethodDefinition)59 Variable (com.google.api.generator.engine.ast.Variable)55 Statement (com.google.api.generator.engine.ast.Statement)53 Collectors (java.util.stream.Collectors)46 RelationalOperationExpr (com.google.api.generator.engine.ast.RelationalOperationExpr)45