Search in sources :

Example 11 with VariableExpr

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

the class AbstractTransportServiceStubClassComposer method createStubOverrideMethods.

private List<MethodDefinition> createStubOverrideMethods(VariableExpr backgroundResourcesVarExpr, Service service) {
    Function<String, MethodDefinition.Builder> methodMakerStarterFn = methodName -> MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setName(methodName);
    Function<String, MethodDefinition> voidMethodMakerFn = methodName -> methodMakerStarterFn.apply(methodName).setReturnType(TypeNode.VOID).setBody(Arrays.asList(ExprStatement.withExpr(MethodInvocationExpr.builder().setExprReferenceExpr(backgroundResourcesVarExpr).setMethodName(methodName).build()))).build();
    Function<String, MethodDefinition> booleanMethodMakerFn = methodName -> methodMakerStarterFn.apply(methodName).setReturnType(TypeNode.BOOLEAN).setReturnExpr(MethodInvocationExpr.builder().setExprReferenceExpr(backgroundResourcesVarExpr).setMethodName(methodName).setReturnType(TypeNode.BOOLEAN).build()).build();
    // Generate the close() method:
    // @Override
    // public final void close() {
    // try {
    // backgroundResources.close();
    // } catch (RuntimeException e) {
    // throw e;
    // } catch (Exception e) {
    // throw new IllegalStateException("Failed to close resource", e);
    // }
    // }
    VariableExpr catchRuntimeExceptionVarExpr = VariableExpr.builder().setVariable(Variable.builder().setType(TypeNode.withExceptionClazz(RuntimeException.class)).setName("e").build()).build();
    VariableExpr catchExceptionVarExpr = VariableExpr.builder().setVariable(Variable.builder().setType(TypeNode.withExceptionClazz(Exception.class)).setName("e").build()).build();
    List<MethodDefinition> javaMethods = new ArrayList<>();
    if (service.operationPollingMethod() != null) {
        javaMethods.addAll(createLongRunningClientGetters());
    }
    javaMethods.add(methodMakerStarterFn.apply("close").setIsFinal(true).setReturnType(TypeNode.VOID).setBody(Arrays.asList(TryCatchStatement.builder().setTryBody(Arrays.asList(ExprStatement.withExpr(MethodInvocationExpr.builder().setExprReferenceExpr(backgroundResourcesVarExpr).setMethodName("close").build()))).addCatch(catchRuntimeExceptionVarExpr.toBuilder().setIsDecl(true).build(), Arrays.asList(ExprStatement.withExpr(ThrowExpr.builder().setThrowExpr(catchRuntimeExceptionVarExpr).build()))).addCatch(catchExceptionVarExpr.toBuilder().setIsDecl(true).build(), Arrays.asList(ExprStatement.withExpr(ThrowExpr.builder().setType(TypeNode.withExceptionClazz(IllegalStateException.class)).setMessageExpr("Failed to close resource").setCauseExpr(catchExceptionVarExpr).build()))).build())).build());
    javaMethods.add(voidMethodMakerFn.apply("shutdown"));
    javaMethods.add(booleanMethodMakerFn.apply("isShutdown"));
    javaMethods.add(booleanMethodMakerFn.apply("isTerminated"));
    javaMethods.add(voidMethodMakerFn.apply("shutdownNow"));
    List<VariableExpr> awaitTerminationArgs = Arrays.asList(VariableExpr.withVariable(Variable.builder().setName("duration").setType(TypeNode.LONG).build()), VariableExpr.withVariable(Variable.builder().setName("unit").setType(FIXED_TYPESTORE.get("TimeUnit")).build()));
    javaMethods.add(methodMakerStarterFn.apply("awaitTermination").setReturnType(TypeNode.BOOLEAN).setArguments(awaitTerminationArgs.stream().map(v -> v.toBuilder().setIsDecl(true).build()).collect(Collectors.toList())).setThrowsExceptions(Arrays.asList(FIXED_TYPESTORE.get("InterruptedException"))).setReturnExpr(MethodInvocationExpr.builder().setExprReferenceExpr(backgroundResourcesVarExpr).setMethodName("awaitTermination").setArguments(awaitTerminationArgs.stream().map(v -> (Expr) v).collect(Collectors.toList())).setReturnType(TypeNode.BOOLEAN).build()).build());
    return javaMethods;
}
Also used : Arrays(java.util.Arrays) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) BiFunction(java.util.function.BiFunction) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) ThisObjectValue(com.google.api.generator.engine.ast.ThisObjectValue) Variable(com.google.api.generator.engine.ast.Variable) BackgroundResource(com.google.api.gax.core.BackgroundResource) 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) Map(java.util.Map) ServerStreamingCallable(com.google.api.gax.rpc.ServerStreamingCallable) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) LongRunningClient(com.google.api.gax.rpc.LongRunningClient) ImmutableMap(com.google.common.collect.ImmutableMap) OperationSnapshot(com.google.api.gax.longrunning.OperationSnapshot) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) Collectors(java.util.stream.Collectors) List(java.util.List) RequestParamsExtractor(com.google.api.gax.rpc.RequestParamsExtractor) Optional(java.util.Optional) GapicContext(com.google.api.generator.gapic.model.GapicContext) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) VaporReference(com.google.api.generator.engine.ast.VaporReference) BetaApi(com.google.api.core.BetaApi) TypeNode(com.google.api.generator.engine.ast.TypeNode) BidiStreamingCallable(com.google.api.gax.rpc.BidiStreamingCallable) Kind(com.google.api.generator.gapic.model.GapicClass.Kind) ClientContext(com.google.api.gax.rpc.ClientContext) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) PackageChecker(com.google.api.generator.gapic.composer.utils.PackageChecker) Operation(com.google.longrunning.Operation) 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) LinkedHashMap(java.util.LinkedHashMap) Expr(com.google.api.generator.engine.ast.Expr) StubCommentComposer(com.google.api.generator.gapic.composer.comment.StubCommentComposer) ImmutableList(com.google.common.collect.ImmutableList) ClientStreamingCallable(com.google.api.gax.rpc.ClientStreamingCallable) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) Nullable(javax.annotation.Nullable) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) BackgroundResourceAggregation(com.google.api.gax.core.BackgroundResourceAggregation) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) IOException(java.io.IOException) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) GapicClass(com.google.api.generator.gapic.model.GapicClass) TimeUnit(java.util.concurrent.TimeUnit) OperationCallable(com.google.api.gax.rpc.OperationCallable) UnaryCallable(com.google.api.gax.rpc.UnaryCallable) Statement(com.google.api.generator.engine.ast.Statement) Service(com.google.api.generator.gapic.model.Service) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) Preconditions(com.google.common.base.Preconditions) Message(com.google.api.generator.gapic.model.Message) Collections(java.util.Collections) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) 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) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) VariableExpr(com.google.api.generator.engine.ast.VariableExpr)

Example 12 with VariableExpr

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

the class AbstractTransportServiceStubClassComposer method createConstructorMethods.

protected List<MethodDefinition> createConstructorMethods(GapicContext context, Service service, TypeStore typeStore, Map<String, VariableExpr> classMemberVarExprs, Map<String, VariableExpr> callableClassMemberVarExprs, Map<String, VariableExpr> protoMethodNameToDescriptorVarExprs, List<Statement> classStatements) {
    TypeNode stubSettingsType = typeStore.get(getTransportContext().classNames().getServiceStubSettingsClassName(service));
    VariableExpr settingsVarExpr = VariableExpr.withVariable(Variable.builder().setName("settings").setType(stubSettingsType).build());
    TypeNode clientContextType = FIXED_TYPESTORE.get("ClientContext");
    VariableExpr clientContextVarExpr = VariableExpr.withVariable(Variable.builder().setName("clientContext").setType(clientContextType).build());
    VariableExpr callableFactoryVarExpr = VariableExpr.withVariable(Variable.builder().setName("callableFactory").setType(getTransportContext().stubCallableFactoryType()).build());
    TypeNode thisClassType = typeStore.get(getTransportContext().classNames().getTransportServiceStubClassName(service));
    TypeNode ioExceptionType = TypeNode.withReference(ConcreteReference.withClazz(IOException.class));
    BiFunction<List<VariableExpr>, List<Statement>, MethodDefinition> ctorMakerFn = (args, body) -> MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(thisClassType).setHeaderCommentStatements(Arrays.asList(createProtectedCtorComment(service))).setArguments(args.stream().map(v -> v.toBuilder().setIsDecl(true).build()).collect(Collectors.toList())).setThrowsExceptions(Arrays.asList(ioExceptionType)).setBody(body).build();
    // First constructor method.
    MethodDefinition firstCtor = ctorMakerFn.apply(Arrays.asList(settingsVarExpr, clientContextVarExpr), Arrays.asList(ExprStatement.withExpr(ReferenceConstructorExpr.thisBuilder().setType(thisClassType).setArguments(settingsVarExpr, clientContextVarExpr, NewObjectExpr.builder().setType(typeStore.get(getTransportContext().classNames().getTransportServiceCallableFactoryClassName(service))).build()).build())));
    Expr thisExpr = ValueExpr.withValue(ThisObjectValue.withType(typeStore.get(getTransportContext().classNames().getTransportServiceStubClassName(service))));
    // Body of the second constructor method.
    List<Statement> secondCtorStatements = new ArrayList<>();
    List<Expr> secondCtorExprs = new ArrayList<>();
    secondCtorExprs.add(AssignmentExpr.builder().setVariableExpr(classMemberVarExprs.get("callableFactory").toBuilder().setExprReferenceExpr(thisExpr).build()).setValueExpr(callableFactoryVarExpr).build());
    VariableExpr operationsStubClassVarExpr = classMemberVarExprs.get(getTransportContext().transportOperationsStubNames().get(0));
    // TODO: refactor this
    if (generateOperationsStubLogic(service)) {
        secondCtorExprs.addAll(createOperationsStubInitExpr(service, thisExpr, operationsStubClassVarExpr, clientContextVarExpr, callableFactoryVarExpr));
    }
    secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
    secondCtorExprs.clear();
    secondCtorStatements.add(EMPTY_LINE_STATEMENT);
    // Transport settings local variables.
    Map<String, VariableExpr> javaStyleMethodNameToTransportSettingsVarExprs = service.methods().stream().collect(Collectors.toMap(m -> JavaStyle.toLowerCamelCase(m.name()), m -> VariableExpr.withVariable(Variable.builder().setName(String.format("%sTransportSettings", JavaStyle.toLowerCamelCase(m.name()))).setType(TypeNode.withReference(ConcreteReference.builder().setClazz(getTransportContext().callSettingsClass()).setGenerics(Arrays.asList(m.inputType().reference(), m.outputType().reference())).build())).build())));
    secondCtorExprs.addAll(service.methods().stream().map(m -> createTransportSettingsInitExpr(m, javaStyleMethodNameToTransportSettingsVarExprs.get(JavaStyle.toLowerCamelCase(m.name())), protoMethodNameToDescriptorVarExprs.get(m.name()), classStatements)).collect(Collectors.toList()));
    secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
    secondCtorExprs.clear();
    secondCtorStatements.add(EMPTY_LINE_STATEMENT);
    // Initialize <method>Callable variables.
    secondCtorExprs.addAll(callableClassMemberVarExprs.entrySet().stream().map(e -> createCallableInitExpr(context, service, e.getKey(), e.getValue(), callableFactoryVarExpr, settingsVarExpr, clientContextVarExpr, operationsStubClassVarExpr, thisExpr, javaStyleMethodNameToTransportSettingsVarExprs)).collect(Collectors.toList()));
    secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
    secondCtorExprs.clear();
    secondCtorStatements.add(EMPTY_LINE_STATEMENT);
    secondCtorStatements.addAll(createLongRunningClient(service, typeStore));
    // Instantiate backgroundResources.
    MethodInvocationExpr getBackgroundResourcesMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientContextVarExpr).setMethodName("getBackgroundResources").build();
    VariableExpr backgroundResourcesVarExpr = classMemberVarExprs.get("backgroundResources");
    secondCtorExprs.add(AssignmentExpr.builder().setVariableExpr(backgroundResourcesVarExpr.toBuilder().setExprReferenceExpr(thisExpr).build()).setValueExpr(NewObjectExpr.builder().setType(FIXED_TYPESTORE.get("BackgroundResourceAggregation")).setArguments(Arrays.asList(getBackgroundResourcesMethodExpr)).build()).build());
    secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
    secondCtorExprs.clear();
    // Second constructor method.
    MethodDefinition secondCtor = ctorMakerFn.apply(Arrays.asList(settingsVarExpr, clientContextVarExpr, callableFactoryVarExpr), secondCtorStatements);
    return Arrays.asList(firstCtor, secondCtor);
}
Also used : Arrays(java.util.Arrays) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) BiFunction(java.util.function.BiFunction) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) ThisObjectValue(com.google.api.generator.engine.ast.ThisObjectValue) Variable(com.google.api.generator.engine.ast.Variable) BackgroundResource(com.google.api.gax.core.BackgroundResource) 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) Map(java.util.Map) ServerStreamingCallable(com.google.api.gax.rpc.ServerStreamingCallable) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) LongRunningClient(com.google.api.gax.rpc.LongRunningClient) ImmutableMap(com.google.common.collect.ImmutableMap) OperationSnapshot(com.google.api.gax.longrunning.OperationSnapshot) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) Collectors(java.util.stream.Collectors) List(java.util.List) RequestParamsExtractor(com.google.api.gax.rpc.RequestParamsExtractor) Optional(java.util.Optional) GapicContext(com.google.api.generator.gapic.model.GapicContext) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) VaporReference(com.google.api.generator.engine.ast.VaporReference) BetaApi(com.google.api.core.BetaApi) TypeNode(com.google.api.generator.engine.ast.TypeNode) BidiStreamingCallable(com.google.api.gax.rpc.BidiStreamingCallable) Kind(com.google.api.generator.gapic.model.GapicClass.Kind) ClientContext(com.google.api.gax.rpc.ClientContext) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) PackageChecker(com.google.api.generator.gapic.composer.utils.PackageChecker) Operation(com.google.longrunning.Operation) 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) LinkedHashMap(java.util.LinkedHashMap) Expr(com.google.api.generator.engine.ast.Expr) StubCommentComposer(com.google.api.generator.gapic.composer.comment.StubCommentComposer) ImmutableList(com.google.common.collect.ImmutableList) ClientStreamingCallable(com.google.api.gax.rpc.ClientStreamingCallable) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) Nullable(javax.annotation.Nullable) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) BackgroundResourceAggregation(com.google.api.gax.core.BackgroundResourceAggregation) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) IOException(java.io.IOException) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) GapicClass(com.google.api.generator.gapic.model.GapicClass) TimeUnit(java.util.concurrent.TimeUnit) OperationCallable(com.google.api.gax.rpc.OperationCallable) UnaryCallable(com.google.api.gax.rpc.UnaryCallable) Statement(com.google.api.generator.engine.ast.Statement) Service(com.google.api.generator.gapic.model.Service) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) Preconditions(com.google.common.base.Preconditions) Message(com.google.api.generator.gapic.model.Message) Collections(java.util.Collections) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) 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) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) 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)

Example 13 with VariableExpr

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

the class BatchingDescriptorComposer method createGetRequestBuilderMethod.

private static MethodDefinition createGetRequestBuilderMethod(Method method, GapicBatchingSettings batchingSettings) {
    TypeNode builderType = TypeNode.withReference(VaporReference.builder().setEnclosingClassNames(method.inputType().reference().name()).setName("Builder").setPakkage(method.inputType().reference().pakkage()).build());
    VariableExpr builderVarExpr = VariableExpr.withVariable(Variable.builder().setType(builderType).setName("builder").build());
    VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
    Expr toBuilderExpr = AssignmentExpr.builder().setVariableExpr(builderVarExpr).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr).setMethodName("toBuilder").setReturnType(builderType).build()).build();
    String upperBatchedFieldName = JavaStyle.toUpperCamelCase(batchingSettings.batchedFieldName());
    String getFooListMethodName = String.format(GET_LIST_METHOD_PATTERN, upperBatchedFieldName);
    Expr getFooListExpr = MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr).setMethodName(getFooListMethodName).build();
    String addAllMethodName = String.format(ADD_ALL_METHOD_PATTERN, upperBatchedFieldName);
    Expr addAllExpr = MethodInvocationExpr.builder().setExprReferenceExpr(builderVarExpr).setMethodName(addAllMethodName).setArguments(getFooListExpr).build();
    MethodDefinition appendRequestMethod = MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName("appendRequest").setArguments(requestVarExpr.toBuilder().setIsDecl(true).build()).setBody(Arrays.asList(IfStatement.builder().setConditionExpr(RelationalOperationExpr.equalToWithExprs(builderVarExpr, ValueExpr.createNullExpr())).setBody(Arrays.asList(ExprStatement.withExpr(toBuilderExpr))).setElseBody(Arrays.asList(ExprStatement.withExpr(addAllExpr))).build())).build();
    MethodDefinition buildMethod = MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(method.inputType()).setName("build").setReturnExpr(MethodInvocationExpr.builder().setExprReferenceExpr(builderVarExpr).setMethodName("build").setReturnType(method.inputType()).build()).build();
    TypeNode anonClassType = toType(REQUEST_BUILDER_REF, method.inputType());
    AnonymousClassExpr requestBuilderAnonClassExpr = AnonymousClassExpr.builder().setType(anonClassType).setStatements(Arrays.asList(ExprStatement.withExpr(builderVarExpr.toBuilder().setIsDecl(true).setScope(ScopeNode.PRIVATE).build()))).setMethods(Arrays.asList(appendRequestMethod, buildMethod)).build();
    return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(anonClassType).setName("getRequestBuilder").setReturnExpr(requestBuilderAnonClassExpr).build();
}
Also used : 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) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr)

Example 14 with VariableExpr

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

the class AbstractServiceClientClassComposer method createMethodVariants.

private static List<MethodDefinition> createMethodVariants(Method method, String clientName, Map<String, Message> messageTypes, TypeStore typeStore, Map<String, ResourceName> resourceNames, List<Sample> samples) {
    List<MethodDefinition> javaMethods = new ArrayList<>();
    String methodName = JavaStyle.toLowerCamelCase(method.name());
    TypeNode methodInputType = method.inputType();
    TypeNode methodOutputType = method.isPaged() ? typeStore.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) : method.outputType();
    if (method.hasLro()) {
        LongrunningOperation lro = method.lro();
        methodOutputType = TypeNode.withReference(typeStore.get("OperationFuture").reference().copyAndSetGenerics(Arrays.asList(lro.responseType().reference(), lro.metadataType().reference())));
    }
    for (List<MethodArgument> signature : method.methodSignatures()) {
        // Get the argument list.
        List<VariableExpr> arguments = signature.stream().map(methodArg -> VariableExpr.builder().setVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(methodArg.name())).setType(methodArg.type()).build()).setIsDecl(true).build()).collect(Collectors.toList());
        // Request proto builder.
        VariableExpr requestVarExpr = VariableExpr.builder().setVariable(Variable.builder().setName("request").setType(methodInputType).build()).setIsDecl(true).build();
        Expr requestBuilderExpr = createRequestBuilderExpr(method, signature, typeStore);
        AssignmentExpr requestAssignmentExpr = AssignmentExpr.builder().setVariableExpr(requestVarExpr).setValueExpr(requestBuilderExpr).build();
        List<Statement> statements = new ArrayList<>();
        statements.add(ExprStatement.withExpr(requestAssignmentExpr));
        MethodInvocationExpr rpcInvocationExpr = MethodInvocationExpr.builder().setMethodName(String.format(method.hasLro() ? "%sAsync" : "%s", methodName)).setArguments(Arrays.asList(requestVarExpr.toBuilder().setIsDecl(false).build())).setReturnType(methodOutputType).build();
        Optional<Sample> methodSample = Optional.of(ServiceClientHeaderSampleComposer.composeShowcaseMethodSample(method, typeStore.get(clientName), signature, resourceNames, messageTypes));
        Optional<String> methodDocSample = Optional.empty();
        if (methodSample.isPresent()) {
            samples.add(methodSample.get());
            methodDocSample = Optional.of(SampleCodeWriter.writeInlineSample(methodSample.get().body()));
        }
        MethodDefinition.Builder methodVariantBuilder = MethodDefinition.builder().setHeaderCommentStatements(ServiceClientCommentComposer.createRpcMethodHeaderComment(method, signature, methodDocSample)).setScope(ScopeNode.PUBLIC).setIsFinal(true).setName(String.format(method.hasLro() ? "%sAsync" : "%s", methodName)).setArguments(arguments);
        if (isProtoEmptyType(methodOutputType)) {
            statements.add(ExprStatement.withExpr(rpcInvocationExpr));
            methodVariantBuilder = methodVariantBuilder.setReturnType(TypeNode.VOID);
        } else {
            methodVariantBuilder = methodVariantBuilder.setReturnType(methodOutputType).setReturnExpr(rpcInvocationExpr);
        }
        if (method.isDeprecated()) {
            methodVariantBuilder = methodVariantBuilder.setAnnotations(Arrays.asList(AnnotationNode.withType(TypeNode.DEPRECATED)));
        }
        methodVariantBuilder = methodVariantBuilder.setBody(statements);
        javaMethods.add(methodVariantBuilder.build());
    }
    return javaMethods;
}
Also used : LongrunningOperation(com.google.api.generator.gapic.model.LongrunningOperation) Arrays(java.util.Arrays) ServiceClientHeaderSampleComposer(com.google.api.generator.gapic.composer.samplecode.ServiceClientHeaderSampleComposer) OperationFuture(com.google.api.gax.longrunning.OperationFuture) BiFunction(java.util.function.BiFunction) Reference(com.google.api.generator.engine.ast.Reference) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) ThisObjectValue(com.google.api.generator.engine.ast.ThisObjectValue) Variable(com.google.api.generator.engine.ast.Variable) BackgroundResource(com.google.api.gax.core.BackgroundResource) Field(com.google.api.generator.gapic.model.Field) Generated(javax.annotation.Generated) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) Method(com.google.api.generator.gapic.model.Method) MethodArgument(com.google.api.generator.gapic.model.MethodArgument) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) LongrunningOperation(com.google.api.generator.gapic.model.LongrunningOperation) Stream(com.google.api.generator.gapic.model.Method.Stream) Map(java.util.Map) ServiceClientMethodSampleComposer(com.google.api.generator.gapic.composer.samplecode.ServiceClientMethodSampleComposer) ServerStreamingCallable(com.google.api.gax.rpc.ServerStreamingCallable) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) ApiFutures(com.google.api.core.ApiFutures) PageContext(com.google.api.gax.rpc.PageContext) Status(com.google.rpc.Status) Set(java.util.Set) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) ServiceClientCommentComposer(com.google.api.generator.gapic.composer.comment.ServiceClientCommentComposer) Collectors(java.util.stream.Collectors) ApiFuture(com.google.api.core.ApiFuture) Objects(java.util.Objects) ClassNames(com.google.api.generator.gapic.composer.utils.ClassNames) List(java.util.List) ServiceClientCallableMethodSampleComposer(com.google.api.generator.gapic.composer.samplecode.ServiceClientCallableMethodSampleComposer) SampleCodeWriter(com.google.api.generator.gapic.composer.samplecode.SampleCodeWriter) Optional(java.util.Optional) GapicContext(com.google.api.generator.gapic.model.GapicContext) ApiFunction(com.google.api.core.ApiFunction) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) BetaApi(com.google.api.core.BetaApi) TypeNode(com.google.api.generator.engine.ast.TypeNode) BidiStreamingCallable(com.google.api.gax.rpc.BidiStreamingCallable) Kind(com.google.api.generator.gapic.model.GapicClass.Kind) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) PackageChecker(com.google.api.generator.gapic.composer.utils.PackageChecker) HashMap(java.util.HashMap) GapicMetadata(com.google.gapic.metadata.GapicMetadata) Operation(com.google.longrunning.Operation) Function(java.util.function.Function) ArrayList(java.util.ArrayList) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Strings(com.google.common.base.Strings) Expr(com.google.api.generator.engine.ast.Expr) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) ClientStreamingCallable(com.google.api.gax.rpc.ClientStreamingCallable) TriFunction(com.google.api.generator.util.TriFunction) AbstractFixedSizeCollection(com.google.api.gax.paging.AbstractFixedSizeCollection) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) Iterator(java.util.Iterator) AbstractPage(com.google.api.gax.paging.AbstractPage) CastExpr(com.google.api.generator.engine.ast.CastExpr) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) IOException(java.io.IOException) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) Sample(com.google.api.generator.gapic.model.Sample) GapicClass(com.google.api.generator.gapic.model.GapicClass) ResourceName(com.google.api.generator.gapic.model.ResourceName) Trie(com.google.api.generator.util.Trie) TimeUnit(java.util.concurrent.TimeUnit) OperationCallable(com.google.api.gax.rpc.OperationCallable) UnaryCallable(com.google.api.gax.rpc.UnaryCallable) Statement(com.google.api.generator.engine.ast.Statement) Service(com.google.api.generator.gapic.model.Service) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) SuperObjectValue(com.google.api.generator.engine.ast.SuperObjectValue) SampleComposerUtil(com.google.api.generator.gapic.composer.samplecode.SampleComposerUtil) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Message(com.google.api.generator.gapic.model.Message) Collections(java.util.Collections) AbstractPagedListResponse(com.google.api.gax.paging.AbstractPagedListResponse) MethodArgument(com.google.api.generator.gapic.model.MethodArgument) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) Sample(com.google.api.generator.gapic.model.Sample) ArrayList(java.util.ArrayList) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) 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) CastExpr(com.google.api.generator.engine.ast.CastExpr) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 15 with VariableExpr

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

the class AbstractServiceClientTestClassComposer method createRpcExceptionTestStatements.

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

Aggregations

VariableExpr (com.google.api.generator.engine.ast.VariableExpr)217 MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)137 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)132 TypeNode (com.google.api.generator.engine.ast.TypeNode)118 Expr (com.google.api.generator.engine.ast.Expr)114 ValueExpr (com.google.api.generator.engine.ast.ValueExpr)107 ExprStatement (com.google.api.generator.engine.ast.ExprStatement)91 Variable (com.google.api.generator.engine.ast.Variable)88 NewObjectExpr (com.google.api.generator.engine.ast.NewObjectExpr)87 ArrayList (java.util.ArrayList)87 Test (org.junit.Test)82 Statement (com.google.api.generator.engine.ast.Statement)80 List (java.util.List)64 ConcreteReference (com.google.api.generator.engine.ast.ConcreteReference)62 MethodDefinition (com.google.api.generator.engine.ast.MethodDefinition)58 RelationalOperationExpr (com.google.api.generator.engine.ast.RelationalOperationExpr)56 CastExpr (com.google.api.generator.engine.ast.CastExpr)53 CommentStatement (com.google.api.generator.engine.ast.CommentStatement)53 Arrays (java.util.Arrays)48 IfStatement (com.google.api.generator.engine.ast.IfStatement)47