Search in sources :

Example 1 with Reference

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

the class AbstractServiceStubSettingsClassComposer method createNestedClassApplyToAllUnaryMethodsMethod.

private static MethodDefinition createNestedClassApplyToAllUnaryMethodsMethod(TypeNode superType, TypeStore typeStore) {
    List<Reference> apiFunctionTypeGenerics = new ArrayList<>();
    apiFunctionTypeGenerics.addAll(NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR.type().reference().generics());
    apiFunctionTypeGenerics.add(TypeNode.VOID_OBJECT.reference());
    TypeNode settingsUpdaterType = TypeNode.withReference(ConcreteReference.builder().setClazz(ApiFunction.class).setGenerics(apiFunctionTypeGenerics).build());
    VariableExpr settingsUpdaterVarExpr = VariableExpr.withVariable(Variable.builder().setType(settingsUpdaterType).setName("settingsUpdater").build());
    String methodName = "applyToAllUnaryMethods";
    Expr superApplyExpr = MethodInvocationExpr.builder().setExprReferenceExpr(ValueExpr.withValue(SuperObjectValue.withType(superType))).setMethodName(methodName).setArguments(NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR, settingsUpdaterVarExpr).build();
    TypeNode returnType = typeStore.get(NESTED_BUILDER_CLASS_NAME);
    Expr returnExpr = ValueExpr.withValue(ThisObjectValue.withType(returnType));
    return MethodDefinition.builder().setHeaderCommentStatements(SettingsCommentComposer.APPLY_TO_ALL_UNARY_METHODS_METHOD_COMMENTS).setScope(ScopeNode.PUBLIC).setReturnType(returnType).setName(methodName).setArguments(settingsUpdaterVarExpr.toBuilder().setIsDecl(true).build()).setBody(Arrays.asList(ExprStatement.withExpr(superApplyExpr))).setReturnExpr(returnExpr).build();
}
Also used : ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) 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) CastExpr(com.google.api.generator.engine.ast.CastExpr) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) 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) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) VaporReference(com.google.api.generator.engine.ast.VaporReference) Reference(com.google.api.generator.engine.ast.Reference) ArrayList(java.util.ArrayList) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) ApiFunction(com.google.api.core.ApiFunction)

Example 2 with Reference

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

the class AbstractServiceStubSettingsClassComposer method createNestedClassConstructorMethods.

private static List<MethodDefinition> createNestedClassConstructorMethods(Service service, GapicServiceConfig serviceConfig, Map<String, VariableExpr> nestedMethodSettingsMemberVarExprs, TypeStore typeStore) {
    TypeNode builderType = typeStore.get(NESTED_BUILDER_CLASS_NAME);
    List<MethodDefinition> ctorMethods = new ArrayList<>();
    // First argument-less contructor.
    ctorMethods.add(MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(builderType).setBody(Arrays.asList(ExprStatement.withExpr(ReferenceConstructorExpr.thisBuilder().setType(builderType).setArguments(CastExpr.builder().setType(FIXED_TYPESTORE.get("ClientContext")).setExpr(ValueExpr.createNullExpr()).build()).build()))).build());
    // Second ctor that takes a clientContext argument.
    VariableExpr clientContextVarExpr = VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("ClientContext")).setName("clientContext").build());
    Reference pagedSettingsBuilderRef = ConcreteReference.withClazz(PagedCallSettings.Builder.class);
    Reference batchingSettingsBuilderRef = ConcreteReference.withClazz(BatchingCallSettings.Builder.class);
    Reference unaryCallSettingsBuilderRef = ConcreteReference.withClazz(UnaryCallSettings.Builder.class);
    Function<TypeNode, Boolean> isUnaryCallSettingsBuilderFn = t -> t.reference().copyAndSetGenerics(ImmutableList.of()).equals(unaryCallSettingsBuilderRef);
    Function<TypeNode, Boolean> isPagedCallSettingsBuilderFn = t -> t.reference().copyAndSetGenerics(ImmutableList.of()).equals(pagedSettingsBuilderRef);
    Function<TypeNode, Boolean> isBatchingCallSettingsBuilderFn = t -> t.reference().copyAndSetGenerics(ImmutableList.of()).equals(batchingSettingsBuilderRef);
    Function<TypeNode, TypeNode> builderToCallSettingsFn = t -> TypeNode.withReference(VaporReference.builder().setName(String.join(DOT, t.reference().enclosingClassNames())).setPakkage(t.reference().pakkage()).build());
    List<Statement> ctorBodyStatements = new ArrayList<>();
    ctorBodyStatements.add(ExprStatement.withExpr(ReferenceConstructorExpr.superBuilder().setType(builderType).setArguments(clientContextVarExpr).build()));
    ctorBodyStatements.add(EMPTY_LINE_STATEMENT);
    ctorBodyStatements.addAll(nestedMethodSettingsMemberVarExprs.entrySet().stream().map(e -> {
        // TODO(miraleung): Extract this into another method.
        // Name is fooBarSettings.
        VariableExpr varExpr = e.getValue();
        TypeNode varType = varExpr.type();
        Preconditions.checkState(e.getKey().endsWith(SETTINGS_LITERAL), String.format("%s expected to end with \"Settings\"", e.getKey()));
        String methodName = getMethodNameFromSettingsVarName(e.getKey());
        if (!isPagedCallSettingsBuilderFn.apply(varType)) {
            if (!isBatchingCallSettingsBuilderFn.apply(varType)) {
                boolean isUnaryCallSettings = isUnaryCallSettingsBuilderFn.apply(varType);
                Expr builderExpr = AssignmentExpr.builder().setVariableExpr(varExpr).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(builderToCallSettingsFn.apply(varExpr.type())).setMethodName(isUnaryCallSettings ? "newUnaryCallSettingsBuilder" : "newBuilder").setReturnType(varExpr.type()).build()).build();
                return ExprStatement.withExpr(builderExpr);
            }
            Expr newBatchingSettingsExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("BatchingSettings")).setMethodName("newBuilder").build();
            newBatchingSettingsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(newBatchingSettingsExpr).setMethodName("build").build();
            String batchingDescVarName = String.format(BATCHING_DESC_PATTERN, JavaStyle.toUpperSnakeCase(methodName));
            Expr batchingSettingsBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(builderToCallSettingsFn.apply(varType)).setMethodName("newBuilder").setArguments(VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("BatchingDescriptor")).setName(batchingDescVarName).build())).build();
            batchingSettingsBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(batchingSettingsBuilderExpr).setMethodName("setBatchingSettings").setArguments(newBatchingSettingsExpr).setReturnType(varType).build();
            Expr builderExpr = AssignmentExpr.builder().setVariableExpr(varExpr).setValueExpr(batchingSettingsBuilderExpr).build();
            return ExprStatement.withExpr(builderExpr);
        }
        String memberVarName = String.format(PAGED_RESPONSE_FACTORY_PATTERN, JavaStyle.toUpperSnakeCase(methodName));
        VariableExpr argVar = VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("PagedListResponseFactory")).setName(memberVarName).build());
        Expr builderExpr = AssignmentExpr.builder().setVariableExpr(varExpr).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(builderToCallSettingsFn.apply(varExpr.type())).setMethodName("newBuilder").setArguments(argVar).setReturnType(varExpr.type()).build()).build();
        return ExprStatement.withExpr(builderExpr);
    }).collect(Collectors.toList()));
    Expr unaryMethodSettingsBuildersAssignExpr = AssignmentExpr.builder().setVariableExpr(NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableList")).setGenerics(NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR.type().reference().generics()).setMethodName("of").setArguments(nestedMethodSettingsMemberVarExprs.values().stream().filter(v -> isUnaryCallSettingsBuilderFn.apply(v.type()) || isPagedCallSettingsBuilderFn.apply(v.type()) || isBatchingCallSettingsBuilderFn.apply(v.type())).collect(Collectors.toList())).setReturnType(NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR.type()).build()).build();
    ctorBodyStatements.add(EMPTY_LINE_STATEMENT);
    ctorBodyStatements.add(ExprStatement.withExpr(unaryMethodSettingsBuildersAssignExpr));
    ctorBodyStatements.add(ExprStatement.withExpr(MethodInvocationExpr.builder().setMethodName("initDefaults").setArguments(ValueExpr.withValue(ThisObjectValue.withType(builderType))).build()));
    ctorMethods.add(MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(builderType).setArguments(clientContextVarExpr.toBuilder().setIsDecl(true).build()).setBody(ctorBodyStatements).build());
    // Third constructor that takes a ServiceStubSettings.
    TypeNode outerSettingsType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service));
    VariableExpr settingsVarExpr = VariableExpr.withVariable(Variable.builder().setType(outerSettingsType).setName("settings").build());
    ctorBodyStatements = new ArrayList<>();
    ctorBodyStatements.add(ExprStatement.withExpr(ReferenceConstructorExpr.superBuilder().setType(builderType).setArguments(settingsVarExpr).build()));
    ctorBodyStatements.add(EMPTY_LINE_STATEMENT);
    // TODO(cleanup): Technically this should actually use the outer class's <method>Settings
    // members to avoid decoupling variable names.
    ctorBodyStatements.addAll(nestedMethodSettingsMemberVarExprs.values().stream().map(v -> ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(v).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(VariableExpr.builder().setExprReferenceExpr(settingsVarExpr).setVariable(v.variable()).build()).setMethodName("toBuilder").setReturnType(v.type()).build()).build())).collect(Collectors.toList()));
    ctorBodyStatements.add(EMPTY_LINE_STATEMENT);
    ctorBodyStatements.add(ExprStatement.withExpr(unaryMethodSettingsBuildersAssignExpr));
    ctorMethods.add(MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(builderType).setArguments(settingsVarExpr.toBuilder().setIsDecl(true).build()).setBody(ctorBodyStatements).build());
    return ctorMethods;
}
Also used : Arrays(java.util.Arrays) BatchingDescriptor(com.google.api.gax.rpc.BatchingDescriptor) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) ServerStreamingCallSettings(com.google.api.gax.rpc.ServerStreamingCallSettings) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) PagedCallSettings(com.google.api.gax.rpc.PagedCallSettings) Empty(com.google.protobuf.Empty) 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) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) Stream(com.google.api.generator.gapic.model.Method.Stream) Map(java.util.Map) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) PartitionKey(com.google.api.gax.batching.PartitionKey) ApiClientHeaderProvider(com.google.api.gax.rpc.ApiClientHeaderProvider) OperationSnapshot(com.google.api.gax.longrunning.OperationSnapshot) Set(java.util.Set) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) ApiFuture(com.google.api.core.ApiFuture) Duration(org.threeten.bp.Duration) LimitExceededBehavior(com.google.api.gax.batching.FlowController.LimitExceededBehavior) GoogleCredentialsProvider(com.google.api.gax.core.GoogleCredentialsProvider) BatchedRequestIssuer(com.google.api.gax.rpc.BatchedRequestIssuer) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) VaporReference(com.google.api.generator.engine.ast.VaporReference) IfStatement(com.google.api.generator.engine.ast.IfStatement) BetaApi(com.google.api.core.BetaApi) TypeNode(com.google.api.generator.engine.ast.TypeNode) ClientContext(com.google.api.gax.rpc.ClientContext) ReturnExpr(com.google.api.generator.engine.ast.ReturnExpr) ArrayList(java.util.ArrayList) RetrySettings(com.google.api.gax.retrying.RetrySettings) NewObjectExpr(com.google.api.generator.engine.ast.NewObjectExpr) LinkedHashMap(java.util.LinkedHashMap) Expr(com.google.api.generator.engine.ast.Expr) Lists(com.google.common.collect.Lists) StubSettings(com.google.api.gax.rpc.StubSettings) BatchingCallSettings(com.google.api.gax.rpc.BatchingCallSettings) Nullable(javax.annotation.Nullable) 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) InstantiatingExecutorProvider(com.google.api.gax.core.InstantiatingExecutorProvider) GapicBatchingSettings(com.google.api.generator.gapic.model.GapicBatchingSettings) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) GapicClass(com.google.api.generator.gapic.model.GapicClass) SuperObjectValue(com.google.api.generator.engine.ast.SuperObjectValue) SampleComposerUtil(com.google.api.generator.gapic.composer.samplecode.SampleComposerUtil) Preconditions(com.google.common.base.Preconditions) StatusCode(com.google.api.gax.rpc.StatusCode) MonitoredResourceDescriptor(com.google.api.MonitoredResourceDescriptor) RequestBuilder(com.google.api.gax.batching.RequestBuilder) BiFunction(java.util.function.BiFunction) Reference(com.google.api.generator.engine.ast.Reference) ThisObjectValue(com.google.api.generator.engine.ast.ThisObjectValue) Variable(com.google.api.generator.engine.ast.Variable) Field(com.google.api.generator.gapic.model.Field) Generated(javax.annotation.Generated) StreamingCallSettings(com.google.api.gax.rpc.StreamingCallSettings) ImmutableSet(com.google.common.collect.ImmutableSet) SettingsSampleComposer(com.google.api.generator.gapic.composer.samplecode.SettingsSampleComposer) ImmutableMap(com.google.common.collect.ImmutableMap) PageContext(com.google.api.gax.rpc.PageContext) BatchingSettings(com.google.api.gax.batching.BatchingSettings) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ClassNames(com.google.api.generator.gapic.composer.utils.ClassNames) List(java.util.List) OperationCallSettings(com.google.api.gax.rpc.OperationCallSettings) SampleCodeWriter(com.google.api.generator.gapic.composer.samplecode.SampleCodeWriter) TransportChannelProvider(com.google.api.gax.rpc.TransportChannelProvider) Optional(java.util.Optional) GapicContext(com.google.api.generator.gapic.model.GapicContext) ApiFunction(com.google.api.core.ApiFunction) SettingsCommentComposer(com.google.api.generator.gapic.composer.comment.SettingsCommentComposer) ApiCallContext(com.google.api.gax.rpc.ApiCallContext) FlowControlSettings(com.google.api.gax.batching.FlowControlSettings) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) PackageChecker(com.google.api.generator.gapic.composer.utils.PackageChecker) Operation(com.google.longrunning.Operation) Function(java.util.function.Function) PagedListResponseFactory(com.google.api.gax.rpc.PagedListResponseFactory) HashSet(java.util.HashSet) GaxProperties(com.google.api.gax.core.GaxProperties) UnaryCallSettings(com.google.api.gax.rpc.UnaryCallSettings) TernaryExpr(com.google.api.generator.engine.ast.TernaryExpr) ImmutableList(com.google.common.collect.ImmutableList) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) Iterator(java.util.Iterator) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) Sample(com.google.api.generator.gapic.model.Sample) UnaryCallable(com.google.api.gax.rpc.UnaryCallable) Statement(com.google.api.generator.engine.ast.Statement) Service(com.google.api.generator.gapic.model.Service) OperationTimedPollAlgorithm(com.google.api.gax.longrunning.OperationTimedPollAlgorithm) PagedListDescriptor(com.google.api.gax.rpc.PagedListDescriptor) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) Message(com.google.api.generator.gapic.model.Message) Collections(java.util.Collections) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) VaporReference(com.google.api.generator.engine.ast.VaporReference) Reference(com.google.api.generator.engine.ast.Reference) EmptyLineStatement(com.google.api.generator.engine.ast.EmptyLineStatement) IfStatement(com.google.api.generator.engine.ast.IfStatement) 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) ReferenceConstructorExpr(com.google.api.generator.engine.ast.ReferenceConstructorExpr) 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) CastExpr(com.google.api.generator.engine.ast.CastExpr) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) 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) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ThrowExpr(com.google.api.generator.engine.ast.ThrowExpr) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) UnaryCallSettings(com.google.api.gax.rpc.UnaryCallSettings) PagedCallSettings(com.google.api.gax.rpc.PagedCallSettings) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) BatchingCallSettings(com.google.api.gax.rpc.BatchingCallSettings)

Example 3 with Reference

use of com.google.api.generator.engine.ast.Reference 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 4 with Reference

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

Example 5 with Reference

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

the class AbstractServiceStubClassComposer method createCallableGetterHelper.

private MethodDefinition createCallableGetterHelper(Method method, TypeStore typeStore, boolean isLroCallable, boolean isPaged) {
    TypeNode returnType;
    switch(method.stream()) {
        case CLIENT:
            returnType = typeStore.get("ClientStreamingCallable");
            break;
        case SERVER:
            returnType = typeStore.get("ServerStreamingCallable");
            break;
        case BIDI:
            returnType = typeStore.get("BidiStreamingCallable");
            break;
        case NONE:
        // Fall through.
        default:
            returnType = typeStore.get(isLroCallable ? "OperationCallable" : "UnaryCallable");
    }
    String methodName = String.format("%s%sCallable", JavaStyle.toLowerCamelCase(method.name()), (isLroCallable ? "Operation" : isPaged ? "Paged" : ""));
    List<Reference> genericRefs = new ArrayList<>();
    genericRefs.add(method.inputType().reference());
    if (method.hasLro() && isLroCallable) {
        genericRefs.add(method.lro().responseType().reference());
        genericRefs.add(method.lro().metadataType().reference());
    } else if (isPaged) {
        genericRefs.add(typeStore.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())).reference());
    } else {
        genericRefs.add(method.outputType().reference());
    }
    List<AnnotationNode> annotations = method.isDeprecated() ? Arrays.asList(AnnotationNode.withType(TypeNode.DEPRECATED)) : Collections.emptyList();
    returnType = TypeNode.withReference(returnType.reference().copyAndSetGenerics(genericRefs));
    return createCallableGetterMethodDefinition(returnType, methodName, annotations, typeStore);
}
Also used : AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) Reference(com.google.api.generator.engine.ast.Reference) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) ArrayList(java.util.ArrayList) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Aggregations

Reference (com.google.api.generator.engine.ast.Reference)29 ConcreteReference (com.google.api.generator.engine.ast.ConcreteReference)27 TypeNode (com.google.api.generator.engine.ast.TypeNode)21 VaporReference (com.google.api.generator.engine.ast.VaporReference)21 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)17 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)13 ArrayList (java.util.ArrayList)13 Test (org.junit.Test)13 MethodDefinition (com.google.api.generator.engine.ast.MethodDefinition)12 MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)12 CommentStatement (com.google.api.generator.engine.ast.CommentStatement)11 Expr (com.google.api.generator.engine.ast.Expr)11 ExprStatement (com.google.api.generator.engine.ast.ExprStatement)11 Statement (com.google.api.generator.engine.ast.Statement)11 ValueExpr (com.google.api.generator.engine.ast.ValueExpr)11 AnnotationNode (com.google.api.generator.engine.ast.AnnotationNode)10 ClassDefinition (com.google.api.generator.engine.ast.ClassDefinition)10 NewObjectExpr (com.google.api.generator.engine.ast.NewObjectExpr)10 RelationalOperationExpr (com.google.api.generator.engine.ast.RelationalOperationExpr)10 TernaryExpr (com.google.api.generator.engine.ast.TernaryExpr)10