Search in sources :

Example 41 with Statement

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

the class HttpJsonServiceStubClassComposer method setPollingRequestFactoryExpr.

private List<Expr> setPollingRequestFactoryExpr(Method protoMethod, Map<String, Message> messageTypes) {
    BiFunction<String, List<Expr>, Function<MethodInvocationExpr, MethodInvocationExpr>> methodMaker = getMethodMaker();
    Message inputOperationMessage = messageTypes.get(protoMethod.inputType().reference().fullName());
    List<Statement> createBody = new ArrayList<>(1);
    // Generate input variables for create
    VariableExpr compoundOperationIdVarExpr = VariableExpr.builder().setVariable(Variable.builder().setType(TypeNode.STRING).setName("compoundOperationId").build()).build();
    // Generate idComponenets
    TypeNode listStringType = TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(ConcreteReference.withClazz(String.class)).build());
    TypeNode arrayListStringType = TypeNode.withReference(ConcreteReference.builder().setClazz(ArrayList.class).setGenerics(ConcreteReference.withClazz(String.class)).build());
    TypeNode arraysType = TypeNode.withReference(ConcreteReference.withClazz(Arrays.class));
    VariableExpr idComponentsVarExpr = VariableExpr.withVariable(Variable.builder().setName("idComponents").setType(listStringType).build());
    MethodInvocationExpr compoundOperationIdSplitExpr = MethodInvocationExpr.builder().setExprReferenceExpr(compoundOperationIdVarExpr).setMethodName("split").setArguments(ValueExpr.withValue(StringObjectValue.withValue(":"))).setReturnType(arrayListStringType).build();
    MethodInvocationExpr asListExpr = MethodInvocationExpr.builder().setStaticReferenceType(arraysType).setMethodName("asList").setArguments(compoundOperationIdSplitExpr).setReturnType(arrayListStringType).build();
    AssignmentExpr idComponentsAssignExpr = AssignmentExpr.builder().setVariableExpr(idComponentsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(asListExpr).build();
    createBody.add(ExprStatement.withExpr(idComponentsAssignExpr));
    // Generate return statement
    TypeNode getOperationRequestType = TypeNode.withReference(protoMethod.inputType().reference());
    MethodInvocationExpr newBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(getOperationRequestType).setMethodName("newBuilder").build();
    BiMap<String, String> responseFieldsMap = inputOperationMessage.operationResponseFields();
    List<String> responseFieldAnnotationNames = new ArrayList<>(responseFieldsMap.keySet());
    Collections.sort(responseFieldAnnotationNames);
    Set<String> responseFieldsNames = responseFieldsMap.inverse().keySet();
    Set<String> allFieldsNames = inputOperationMessage.fieldMap().keySet();
    ArrayList<String> nonResponseFieldsNames = new ArrayList<>();
    for (String fieldName : allFieldsNames) {
        if (!responseFieldsNames.contains(fieldName)) {
            nonResponseFieldsNames.add(fieldName);
        }
    }
    Collections.sort(nonResponseFieldsNames);
    int index = 0;
    for (String fieldAnnotationName : responseFieldAnnotationNames) {
        newBuilderExpr = methodMaker.apply(setMethodFormat(responseFieldsMap.get(fieldAnnotationName)), Collections.singletonList(getExpr(idComponentsVarExpr, Integer.toString(index)))).apply(newBuilderExpr);
        index++;
    }
    for (String fieldName : nonResponseFieldsNames) {
        newBuilderExpr = methodMaker.apply(setMethodFormat(fieldName), Collections.singletonList(getExpr(idComponentsVarExpr, Integer.toString(index)))).apply(newBuilderExpr);
        index++;
    }
    MethodInvocationExpr buildExpr = MethodInvocationExpr.builder().setExprReferenceExpr(newBuilderExpr).setMethodName("build").setReturnType(getOperationRequestType).build();
    // Return lambda anonymous class
    return Collections.singletonList(LambdaExpr.builder().setArguments(compoundOperationIdVarExpr.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) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) Arrays(java.util.Arrays)

Example 42 with Statement

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

the class BatchingDescriptorComposer method createSplitResponseMethod.

private static MethodDefinition createSplitResponseMethod(Method method, GapicBatchingSettings batchingSettings, Map<String, Message> messageTypes) {
    VariableExpr batchResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.outputType()).setName("batchResponse").build());
    TypeNode batchedRequestIssuerType = toType(BATCHED_REQUEST_ISSUER_REF, method.outputType());
    TypeNode batchVarType = TypeNode.withReference(ConcreteReference.builder().setClazz(Collection.class).setGenerics(Arrays.asList(ConcreteReference.wildcardWithUpperBound(batchedRequestIssuerType.reference()))).build());
    VariableExpr batchVarExpr = VariableExpr.withVariable(Variable.builder().setType(batchVarType).setName("batch").build());
    VariableExpr responderVarExpr = VariableExpr.withVariable(Variable.builder().setType(batchedRequestIssuerType).setName("responder").build());
    VariableExpr batchMessageIndexVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.INT).setName("batchMessageIndex").build());
    VariableExpr subresponseElementsVarExpr = null;
    boolean hasSubresponseField = batchingSettings.subresponseFieldName() != null;
    List<Statement> outerForBody = new ArrayList<>();
    if (hasSubresponseField) {
        Message outputMessage = messageTypes.get(method.outputType().reference().fullName());
        Preconditions.checkNotNull(outputMessage, String.format("Output message not found for RPC %s", method.name()));
        Field subresponseElementField = outputMessage.fieldMap().get(batchingSettings.subresponseFieldName());
        Preconditions.checkNotNull(subresponseElementField, String.format("Subresponse field %s not found in message %s", batchingSettings.subresponseFieldName(), outputMessage.name()));
        TypeNode subresponseElementType = subresponseElementField.type();
        subresponseElementsVarExpr = VariableExpr.withVariable(Variable.builder().setType(subresponseElementType).setName("subresponseElements").build());
        VariableExpr subresponseCountVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.LONG).setName("subresponseCount").build());
        outerForBody.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(subresponseElementsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(TypeNode.withReference(ConcreteReference.withClazz(ArrayList.class))).setIsGeneric(true).build()).build()));
        String getFooCountMethodName = "getMessageCount";
        outerForBody.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(subresponseCountVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(responderVarExpr).setMethodName(getFooCountMethodName).setReturnType(subresponseCountVarExpr.type()).build()).build()));
        List<Expr> innerSubresponseForExprs = new ArrayList<>();
        String getSubresponseFieldMethodName = String.format("get%s", JavaStyle.toUpperCamelCase(batchingSettings.subresponseFieldName()));
        Expr addMethodArgExpr = MethodInvocationExpr.builder().setExprReferenceExpr(batchResponseVarExpr).setMethodName(getSubresponseFieldMethodName).setArguments(UnaryOperationExpr.postfixIncrementWithExpr(batchMessageIndexVarExpr)).build();
        innerSubresponseForExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(subresponseElementsVarExpr).setMethodName("add").setArguments(addMethodArgExpr).build());
        // TODO(miraleung): Increment batchMessageIndexVarExpr.
        VariableExpr forIndexVarExpr = VariableExpr.builder().setIsDecl(true).setVariable(Variable.builder().setType(TypeNode.INT).setName("i").build()).build();
        ValueExpr initValueExpr = ValueExpr.withValue(PrimitiveValue.builder().setValue("0").setType(TypeNode.INT).build());
        GeneralForStatement innerSubresponseForStatement = GeneralForStatement.incrementWith(forIndexVarExpr, initValueExpr, subresponseCountVarExpr, innerSubresponseForExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
        outerForBody.add(innerSubresponseForStatement);
    }
    TypeNode responseType = method.outputType();
    Expr responseBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(responseType).setMethodName("newBuilder").build();
    if (hasSubresponseField) {
        Preconditions.checkNotNull(subresponseElementsVarExpr, String.format("subresponseElements variable should not be null for method %s", method.name()));
        responseBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseBuilderExpr).setMethodName(String.format("addAll%s", JavaStyle.toUpperCamelCase(batchingSettings.subresponseFieldName()))).setArguments(subresponseElementsVarExpr).build();
    }
    responseBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseBuilderExpr).setMethodName("build").setReturnType(responseType).build();
    VariableExpr responseVarExpr = VariableExpr.withVariable(Variable.builder().setType(responseType).setName("response").build());
    outerForBody.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(responseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(responseBuilderExpr).build()));
    outerForBody.add(ExprStatement.withExpr(MethodInvocationExpr.builder().setExprReferenceExpr(responderVarExpr).setMethodName("setResponse").setArguments(responseVarExpr).build()));
    ForStatement outerForStatement = ForStatement.builder().setLocalVariableExpr(responderVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(batchVarExpr).setBody(outerForBody).build();
    List<Statement> bodyStatements = new ArrayList<>();
    if (hasSubresponseField) {
        bodyStatements.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(batchMessageIndexVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build())).build()));
    }
    bodyStatements.add(outerForStatement);
    return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName("splitResponse").setArguments(Arrays.asList(batchResponseVarExpr, batchVarExpr).stream().map(v -> v.toBuilder().setIsDecl(true).build()).collect(Collectors.toList())).setBody(bodyStatements).build();
}
Also used : ValueExpr(com.google.api.generator.engine.ast.ValueExpr) Message(com.google.api.generator.gapic.model.Message) IfStatement(com.google.api.generator.engine.ast.IfStatement) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) ArrayList(java.util.ArrayList) Field(com.google.api.generator.gapic.model.Field) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) UnaryOperationExpr(com.google.api.generator.engine.ast.UnaryOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) Collection(java.util.Collection) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) GeneralForStatement(com.google.api.generator.engine.ast.GeneralForStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement)

Example 43 with Statement

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

the class SampleCodeWriter method write.

@VisibleForTesting
public static String write(List<Statement> statements) {
    JavaWriterVisitor visitor = new JavaWriterVisitor();
    for (Statement statement : statements) {
        statement.accept(visitor);
    }
    String formattedSampleCode = SampleBodyJavaFormatter.format(visitor.write());
    // Escape character "@" in the markdown code block <pre>{@code...} tags.
    return formattedSampleCode.replaceAll("@", "{@literal @}");
}
Also used : Statement(com.google.api.generator.engine.ast.Statement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) JavaWriterVisitor(com.google.api.generator.engine.writer.JavaWriterVisitor) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 44 with Statement

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

the class ServiceClientCallableMethodSampleComposer method composeUnaryOrLroCallableSample.

private static Sample composeUnaryOrLroCallableSample(Method method, VariableExpr clientVarExpr, VariableExpr requestVarExpr) {
    List<Statement> bodyStatements = new ArrayList<>();
    // Create api future variable expression, and assign it with a value by invoking callable
    // method.
    // e.g. ApiFuture<EchoResponse> future = echoClient.echoCallable().futureCall(request);
    TypeNode apiFutureType = TypeNode.withReference(ConcreteReference.builder().setClazz(ApiFuture.class).setGenerics(method.hasLro() ? ConcreteReference.withClazz(Operation.class) : method.outputType().reference()).build());
    VariableExpr apiFutureVarExpr = VariableExpr.withVariable(Variable.builder().setName("future").setType(apiFutureType).build());
    MethodInvocationExpr callableMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(JavaStyle.toLowerCamelCase(String.format("%sCallable", method.name()))).build();
    callableMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(callableMethodInvocationExpr).setMethodName("futureCall").setArguments(requestVarExpr).setReturnType(apiFutureType).build();
    AssignmentExpr futureAssignmentExpr = AssignmentExpr.builder().setVariableExpr(apiFutureVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(callableMethodInvocationExpr).build();
    bodyStatements.add(ExprStatement.withExpr(futureAssignmentExpr));
    bodyStatements.add(CommentStatement.withComment(LineComment.withComment("Do something.")));
    MethodInvocationExpr getMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(apiFutureVarExpr).setMethodName("get").setReturnType(method.outputType()).build();
    TypeNode methodOutputType = method.hasLro() ? method.lro().responseType() : method.outputType();
    boolean returnsVoid = methodOutputType.isProtoEmptyType();
    if (returnsVoid) {
        bodyStatements.add(ExprStatement.withExpr(getMethodInvocationExpr));
    } else {
        VariableExpr responseVarExpr = VariableExpr.builder().setVariable(Variable.builder().setType(method.outputType()).setName("response").build()).setIsDecl(true).build();
        AssignmentExpr responseAssignmentExpr = AssignmentExpr.builder().setVariableExpr(responseVarExpr).setValueExpr(getMethodInvocationExpr).build();
        bodyStatements.add(ExprStatement.withExpr(responseAssignmentExpr));
    }
    RegionTag regionTag = RegionTag.builder().setServiceName(clientVarExpr.variable().identifier().name()).setRpcName(method.name()).setIsAsynchronous(true).build();
    return Sample.builder().setBody(bodyStatements).setRegionTag(regionTag).setIsCanonical(true).build();
}
Also used : ApiFuture(com.google.api.core.ApiFuture) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) 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) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr)

Example 45 with Statement

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

the class ServiceClientCallableMethodSampleComposer method composeRegularCallableMethod.

// Compose sample code for the method where it is CallableMethodKind.REGULAR.
public static Sample composeRegularCallableMethod(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<Statement> bodyStatements = new ArrayList<>();
    bodyStatements.add(ExprStatement.withExpr(requestAssignmentExpr));
    RegionTag regionTag;
    if (method.isPaged()) {
        Sample pagedCallable = composePagedCallableSample(method, clientVarExpr, requestVarExpr, messageTypes);
        bodyStatements.addAll(pagedCallable.body());
        regionTag = pagedCallable.regionTag();
    } else {
        // e.g.  echoClient.echoCallable().futureCall(request)
        Sample unaryOrLroCallable = composeUnaryOrLroCallableSample(method, clientVarExpr, requestVarExpr);
        bodyStatements.addAll(unaryOrLroCallable.body());
        regionTag = unaryOrLroCallable.regionTag();
    }
    List<Statement> body = Arrays.asList(TryCatchStatement.builder().setTryResourceExpr(SampleComposerUtil.assignClientVariableWithCreateMethodExpr(clientVarExpr)).setTryBody(bodyStatements).setIsSampleCode(true).build());
    return Sample.builder().setBody(body).setRegionTag(regionTag).build();
}
Also used : Message(com.google.api.generator.gapic.model.Message) 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) 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) Sample(com.google.api.generator.gapic.model.Sample) ArrayList(java.util.ArrayList) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) 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