Search in sources :

Example 11 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) {
    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)

Example 12 with Statement

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

the class ServiceClientTestClassComposer method createStreamingRpcExceptionTestStatements.

@Override
protected List<Statement> createStreamingRpcExceptionTestStatements(Method method, Map<String, VariableExpr> classMemberVarExprs, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
    // Build the request variable and assign it.
    VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
    Message requestMessage = messageTypes.get(method.inputType().reference().fullName());
    Preconditions.checkNotNull(requestMessage);
    Expr valExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes);
    List<Statement> statements = new ArrayList<>();
    statements.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build()));
    statements.add(EMPTY_LINE_STATEMENT);
    // Build the responseObserver variable.
    VariableExpr responseObserverVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(FIXED_GRPC_TYPESTORE.get("MockStreamObserver").reference().copyAndSetGenerics(Arrays.asList(method.outputType().reference())))).setName("responseObserver").build());
    statements.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(responseObserverVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(FIXED_GRPC_TYPESTORE.get("MockStreamObserver")).setIsGeneric(true).build()).build()));
    statements.add(EMPTY_LINE_STATEMENT);
    // Build the callable variable and assign it.
    VariableExpr callableVarExpr = VariableExpr.withVariable(Variable.builder().setType(getCallableType(method)).setName("callable").build());
    Expr streamingCallExpr = MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get("client")).setMethodName(String.format("%sCallable", JavaStyle.toLowerCamelCase(method.name()))).setReturnType(callableVarExpr.type()).build();
    List<Expr> exprs = new ArrayList<>();
    exprs.add(AssignmentExpr.builder().setVariableExpr(callableVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(streamingCallExpr).build());
    if (method.stream().equals(Method.Stream.SERVER)) {
        exprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(callableVarExpr).setMethodName("serverStreamingCall").setArguments(requestVarExpr, responseObserverVarExpr).build());
    } else {
        // Call the streaming-variant callable method.
        VariableExpr requestObserverVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(FIXED_TYPESTORE.get("ApiStreamObserver").reference().copyAndSetGenerics(Arrays.asList(method.inputType().reference())))).setName("requestObserver").build());
        List<Expr> callableMethodArgs = new ArrayList<>();
        if (!method.stream().equals(Method.Stream.BIDI) && !method.stream().equals(Method.Stream.CLIENT)) {
            callableMethodArgs.add(requestVarExpr);
        }
        callableMethodArgs.add(responseObserverVarExpr);
        exprs.add(AssignmentExpr.builder().setVariableExpr(requestObserverVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(callableVarExpr).setMethodName(getCallableMethodName(method)).setArguments(callableMethodArgs).setReturnType(requestObserverVarExpr.type()).build()).build());
        statements.addAll(exprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
        exprs.clear();
        statements.add(EMPTY_LINE_STATEMENT);
        exprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(requestObserverVarExpr).setMethodName("onNext").setArguments(requestVarExpr).build());
    }
    statements.addAll(exprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    exprs.clear();
    statements.add(EMPTY_LINE_STATEMENT);
    List<Expr> tryBodyExprs = new ArrayList<>();
    // TODO(v2): This variable is unused in the generated test, it can be deleted.
    VariableExpr actualResponsesVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(method.outputType().reference())).build())).setName("actualResponses").build());
    Expr getFutureResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseObserverVarExpr).setMethodName("future").build();
    getFutureResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(getFutureResponseExpr).setMethodName("get").setReturnType(actualResponsesVarExpr.type()).build();
    tryBodyExprs.add(AssignmentExpr.builder().setVariableExpr(actualResponsesVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(getFutureResponseExpr).build());
    // 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 thrown"))).build());
    VariableExpr catchExceptionVarExpr = VariableExpr.builder().setVariable(Variable.builder().setType(TypeNode.withExceptionClazz(ExecutionException.class)).setName("e").build()).build();
    TryCatchStatement tryCatchBlock = TryCatchStatement.builder().setTryBody(tryBodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).addCatch(catchExceptionVarExpr.toBuilder().setIsDecl(true).build(), createRpcLroExceptionTestCatchBody(catchExceptionVarExpr, true)).build();
    statements.add(tryCatchBlock);
    return statements;
}
Also used : AbstractMessage(com.google.protobuf.AbstractMessage) Message(com.google.api.generator.gapic.model.Message) 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) 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) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) List(java.util.List) ArrayList(java.util.ArrayList) ExecutionException(java.util.concurrent.ExecutionException)

Example 13 with Statement

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

the class ResourceNameHelperClassComposer method createToStringListMethod.

private static MethodDefinition createToStringListMethod(TypeNode thisClassType) {
    TypeNode listClassType = TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(thisClassType.reference())).build());
    VariableExpr valuesVarExpr = VariableExpr.withVariable(Variable.builder().setName("values").setType(listClassType).build());
    TypeNode listStringType = TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(ConcreteReference.withClazz(String.class))).build());
    VariableExpr listVarExpr = VariableExpr.withVariable(Variable.builder().setName("list").setType(listStringType).build());
    AssignmentExpr listAssignExpr = AssignmentExpr.builder().setVariableExpr(listVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(TypeNode.withReference(ConcreteReference.withClazz(ArrayList.class))).setIsGeneric(true).setArguments(Arrays.asList(MethodInvocationExpr.builder().setExprReferenceExpr(valuesVarExpr).setMethodName("size").build())).build()).build();
    VariableExpr valueVarExpr = VariableExpr.withVariable(Variable.builder().setName("value").setType(thisClassType).build());
    // We use an equality check instead of Objects.isNull() for Java 7 compatibility.
    Expr isNullCheck = RelationalOperationExpr.equalToWithExprs(valueVarExpr, ValueExpr.createNullExpr());
    Statement listAddEmptyStringStatement = ExprStatement.withExpr(MethodInvocationExpr.builder().setExprReferenceExpr(listVarExpr).setMethodName("add").setArguments(Arrays.asList(ValueExpr.withValue(StringObjectValue.withValue("")))).build());
    Statement listAddValueStatement = ExprStatement.withExpr(MethodInvocationExpr.builder().setExprReferenceExpr(listVarExpr).setMethodName("add").setArguments(Arrays.asList(MethodInvocationExpr.builder().setExprReferenceExpr(valueVarExpr).setMethodName("toString").build())).build());
    IfStatement ifStatement = IfStatement.builder().setConditionExpr(isNullCheck).setBody(Arrays.asList(listAddEmptyStringStatement)).setElseBody(Arrays.asList(listAddValueStatement)).build();
    ForStatement forStatement = ForStatement.builder().setLocalVariableExpr(valueVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(valuesVarExpr).setBody(Arrays.asList(ifStatement)).build();
    return MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setIsStatic(true).setReturnType(listStringType).setName("toStringList").setArguments(Arrays.asList(valuesVarExpr.toBuilder().setIsDecl(true).build())).setBody(Arrays.asList(ExprStatement.withExpr(listAssignExpr), forStatement)).setReturnExpr(listVarExpr).build();
}
Also used : IfStatement(com.google.api.generator.engine.ast.IfStatement) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) CastExpr(com.google.api.generator.engine.ast.CastExpr) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) ForStatement(com.google.api.generator.engine.ast.ForStatement) IfStatement(com.google.api.generator.engine.ast.IfStatement) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) 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) List(java.util.List) 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) ForStatement(com.google.api.generator.engine.ast.ForStatement)

Example 14 with Statement

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

the class ResourceNameHelperClassComposer method createClassStatements.

private static List<Statement> createClassStatements(List<VariableExpr> templateFinalVarExprs, Map<String, VariableExpr> patternTokenVarExprs, List<String> patterns, List<List<String>> tokenHierarchies) {
    List<Expr> memberVars = new ArrayList<>();
    // "projects/{project}/locations/{location}/autoscalingPolicies/{autoscaling_policy}");
    for (int i = 0; i < patterns.size(); i++) {
        VariableExpr varExpr = templateFinalVarExprs.get(i).toBuilder().setIsDecl(true).setScope(ScopeNode.PRIVATE).setIsStatic(true).setIsFinal(true).build();
        String pattern = patterns.get(i);
        Expr valueExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("PathTemplate")).setMethodName("createWithoutUrlEncoding").setArguments(Arrays.asList(ValueExpr.withValue(StringObjectValue.withValue(pattern)))).setReturnType(FIXED_TYPESTORE.get("PathTemplate")).build();
        // PubSub special-case handling for _deleted-topic_.
        if (pattern.equals(ResourceNameConstants.DELETED_TOPIC_LITERAL)) {
            valueExpr = ValueExpr.withValue(StringObjectValue.withValue(pattern));
        }
        memberVars.add(AssignmentExpr.builder().setVariableExpr(varExpr).setValueExpr(valueExpr).build());
    }
    memberVars.add(FIXED_CLASS_VARS.get("fieldValuesMap").toBuilder().setIsDecl(true).setScope(ScopeNode.PRIVATE).setIsVolatile(true).build());
    boolean hasVariants = tokenHierarchies.size() > 1;
    if (hasVariants) {
        Function<VariableExpr, VariableExpr> toDeclFn = v -> v.toBuilder().setIsDecl(true).setScope(ScopeNode.PRIVATE).build();
        memberVars.add(toDeclFn.apply(FIXED_CLASS_VARS.get("pathTemplate")));
        memberVars.add(toDeclFn.apply(FIXED_CLASS_VARS.get("fixedValue")));
    }
    // Private per-token string variables.
    // Use the token set as a key to maintain ordering (for consistency).
    Function<VariableExpr, VariableExpr> toFinalDeclFn = v -> v.toBuilder().setIsDecl(true).setScope(ScopeNode.PRIVATE).setIsFinal(true).build();
    // Special-cased PubSub handling.
    List<List<String>> processedTokenHierarchies = tokenHierarchies.stream().filter(tokens -> !tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)).collect(Collectors.toList());
    memberVars.addAll(getTokenSet(processedTokenHierarchies).stream().map(t -> toFinalDeclFn.apply(patternTokenVarExprs.get(t))).collect(Collectors.toList()));
    return memberVars.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
}
Also used : Arrays(java.util.Arrays) Reference(com.google.api.generator.engine.ast.Reference) PathTemplate(com.google.api.pathtemplate.PathTemplate) ThisObjectValue(com.google.api.generator.engine.ast.ThisObjectValue) Variable(com.google.api.generator.engine.ast.Variable) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) Generated(javax.annotation.Generated) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) CommentComposer(com.google.api.generator.gapic.composer.comment.CommentComposer) Map(java.util.Map) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) ImmutableMap(com.google.common.collect.ImmutableMap) ForStatement(com.google.api.generator.engine.ast.ForStatement) Set(java.util.Set) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ResourceNameConstants(com.google.api.generator.gapic.utils.ResourceNameConstants) List(java.util.List) GapicContext(com.google.api.generator.gapic.model.GapicContext) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) IfStatement(com.google.api.generator.engine.ast.IfStatement) BetaApi(com.google.api.core.BetaApi) TypeNode(com.google.api.generator.engine.ast.TypeNode) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) HashMap(java.util.HashMap) JavaDocComment(com.google.api.generator.engine.ast.JavaDocComment) Function(java.util.function.Function) 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) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) ValidationException(com.google.api.pathtemplate.ValidationException) LinkedHashSet(java.util.LinkedHashSet) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) Iterator(java.util.Iterator) CastExpr(com.google.api.generator.engine.ast.CastExpr) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) 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) Statement(com.google.api.generator.engine.ast.Statement) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) CastExpr(com.google.api.generator.engine.ast.CastExpr) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) ArrayList(java.util.ArrayList) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) List(java.util.List) ArrayList(java.util.ArrayList)

Example 15 with Statement

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

the class ResourceNameHelperClassComposer method createGetFieldValuesMapMethod.

private static MethodDefinition createGetFieldValuesMapMethod(ResourceName resourceName, TypeNode thisClassType, Map<String, VariableExpr> patternTokenVarExprs, List<List<String>> tokenHierarchies) {
    Reference strRef = TypeNode.STRING.reference();
    TypeNode mapBuilderType = TypeNode.withReference(ConcreteReference.builder().setClazz(ImmutableMap.Builder.class).setGenerics(Arrays.asList(strRef, strRef)).build());
    VariableExpr fieldMapBuilderVarExpr = VariableExpr.withVariable(Variable.builder().setName("fieldMapBuilder").setType(mapBuilderType).build());
    AssignmentExpr builderAssignExpr = AssignmentExpr.builder().setVariableExpr(fieldMapBuilderVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")).setMethodName("builder").setReturnType(mapBuilderType).build()).build();
    // Special-cased PubSub handling.
    List<List<String>> processedTokenHierarchies = tokenHierarchies.stream().filter(tokens -> !tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)).collect(Collectors.toList());
    // Innermost if-blocks.
    List<Statement> tokenIfStatements = new ArrayList<>();
    for (String token : getTokenSet(processedTokenHierarchies)) {
        VariableExpr tokenVarExpr = patternTokenVarExprs.get(token);
        Preconditions.checkNotNull(tokenVarExpr, String.format("No variable found for %s among %s", token, patternTokenVarExprs.keySet()));
        StringObjectValue tokenStrVal = StringObjectValue.withValue(token);
        MethodInvocationExpr putExpr = MethodInvocationExpr.builder().setExprReferenceExpr(fieldMapBuilderVarExpr).setMethodName("put").setArguments(ValueExpr.withValue(tokenStrVal), tokenVarExpr).build();
        Expr notNullCheckExpr = RelationalOperationExpr.notEqualToWithExprs(tokenVarExpr, ValueExpr.createNullExpr());
        tokenIfStatements.add(IfStatement.builder().setConditionExpr(notNullCheckExpr).setBody(Arrays.asList(ExprStatement.withExpr(putExpr))).build());
    }
    // Put the innermost if-statements and assignment expressions together.
    VariableExpr fieldValuesMapVarExpr = FIXED_CLASS_VARS.get("fieldValuesMap");
    AssignmentExpr fieldValuesMapAssignExpr = AssignmentExpr.builder().setVariableExpr(fieldValuesMapVarExpr).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(fieldMapBuilderVarExpr).setMethodName("build").setReturnType(fieldValuesMapVarExpr.type()).build()).build();
    List<Statement> middleIfBlockStatements = new ArrayList<>();
    middleIfBlockStatements.add(ExprStatement.withExpr(builderAssignExpr));
    middleIfBlockStatements.addAll(tokenIfStatements);
    middleIfBlockStatements.add(ExprStatement.withExpr(fieldValuesMapAssignExpr));
    // Middle if-block, i.e. `if (fieldValuesMap == null)`.
    Expr fieldValuesMapNullCheckExpr = RelationalOperationExpr.equalToWithExprs(fieldValuesMapVarExpr, ValueExpr.createNullExpr());
    IfStatement fieldValuesMapIfStatement = IfStatement.builder().setConditionExpr(fieldValuesMapNullCheckExpr).setBody(middleIfBlockStatements).build();
    // Outer if-block.
    IfStatement outerIfStatement = IfStatement.builder().setConditionExpr(fieldValuesMapNullCheckExpr).setBody(Arrays.asList(SynchronizedStatement.builder().setLock(ThisObjectValue.withType(thisClassType)).setBody(Arrays.asList(fieldValuesMapIfStatement)).build())).build();
    // Put the method together.
    TypeNode mapStringType = fieldValuesMapVarExpr.type();
    return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(mapStringType).setName("getFieldValuesMap").setBody(Arrays.asList(outerIfStatement)).setReturnExpr(fieldValuesMapVarExpr).build();
}
Also used : Arrays(java.util.Arrays) Reference(com.google.api.generator.engine.ast.Reference) PathTemplate(com.google.api.pathtemplate.PathTemplate) ThisObjectValue(com.google.api.generator.engine.ast.ThisObjectValue) Variable(com.google.api.generator.engine.ast.Variable) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) Generated(javax.annotation.Generated) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) CommentComposer(com.google.api.generator.gapic.composer.comment.CommentComposer) Map(java.util.Map) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) ImmutableMap(com.google.common.collect.ImmutableMap) ForStatement(com.google.api.generator.engine.ast.ForStatement) Set(java.util.Set) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ResourceNameConstants(com.google.api.generator.gapic.utils.ResourceNameConstants) List(java.util.List) GapicContext(com.google.api.generator.gapic.model.GapicContext) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) IfStatement(com.google.api.generator.engine.ast.IfStatement) BetaApi(com.google.api.core.BetaApi) TypeNode(com.google.api.generator.engine.ast.TypeNode) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) HashMap(java.util.HashMap) JavaDocComment(com.google.api.generator.engine.ast.JavaDocComment) Function(java.util.function.Function) 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) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) ValidationException(com.google.api.pathtemplate.ValidationException) LinkedHashSet(java.util.LinkedHashSet) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) Iterator(java.util.Iterator) CastExpr(com.google.api.generator.engine.ast.CastExpr) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) 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) Statement(com.google.api.generator.engine.ast.Statement) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) Reference(com.google.api.generator.engine.ast.Reference) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) ForStatement(com.google.api.generator.engine.ast.ForStatement) IfStatement(com.google.api.generator.engine.ast.IfStatement) SynchronizedStatement(com.google.api.generator.engine.ast.SynchronizedStatement) 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) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) IfStatement(com.google.api.generator.engine.ast.IfStatement) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) CastExpr(com.google.api.generator.engine.ast.CastExpr) AssignmentOperationExpr(com.google.api.generator.engine.ast.AssignmentOperationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) List(java.util.List) ArrayList(java.util.ArrayList) TypeNode(com.google.api.generator.engine.ast.TypeNode)

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