Search in sources :

Example 1 with GapicServiceConfig

use of com.google.api.generator.gapic.model.GapicServiceConfig 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 2 with GapicServiceConfig

use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.

the class AbstractServiceStubSettingsClassComposer method generate.

@Override
public GapicClass generate(GapicContext context, Service service) {
    // TODO(miraleung): Robustify this against a null serviceConfig.
    GapicServiceConfig serviceConfig = context.serviceConfig();
    Map<String, Message> messageTypes = context.messages();
    String pakkage = String.format("%s.stub", service.pakkage());
    TypeStore typeStore = createDynamicTypes(service, pakkage);
    List<Sample> samples = new ArrayList<>();
    Set<String> deprecatedSettingVarNames = new HashSet<>();
    Map<String, VariableExpr> methodSettingsMemberVarExprs = createMethodSettingsClassMemberVarExprs(service, serviceConfig, typeStore, /* isNestedClass= */
    false, deprecatedSettingVarNames);
    String className = ClassNames.getServiceStubSettingsClassName(service);
    List<CommentStatement> classHeaderComments = createClassHeaderComments(service, typeStore.get(className), samples);
    ClassDefinition classDef = ClassDefinition.builder().setPackageString(pakkage).setHeaderCommentStatements(classHeaderComments).setAnnotations(createClassAnnotations(service)).setScope(ScopeNode.PUBLIC).setName(className).setExtendsType(createExtendsType(service, typeStore)).setStatements(createClassStatements(service, serviceConfig, methodSettingsMemberVarExprs, messageTypes, typeStore)).setMethods(createClassMethods(service, methodSettingsMemberVarExprs, deprecatedSettingVarNames, typeStore)).setNestedClasses(Arrays.asList(createNestedBuilderClass(service, serviceConfig, typeStore))).build();
    return GapicClass.create(GapicClass.Kind.STUB, classDef, SampleComposerUtil.handleDuplicateSamples(samples));
}
Also used : Message(com.google.api.generator.gapic.model.Message) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) Sample(com.google.api.generator.gapic.model.Sample) ArrayList(java.util.ArrayList) ClassDefinition(com.google.api.generator.engine.ast.ClassDefinition) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) HashSet(java.util.HashSet)

Example 3 with GapicServiceConfig

use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.

the class RetrySettingsComposer method createRetryCodesDefinitionsBlock.

public static BlockStatement createRetryCodesDefinitionsBlock(Service service, GapicServiceConfig serviceConfig, VariableExpr retryCodesDefinitionsClassMemberVarExpr) {
    TypeNode definitionsType = TypeNode.withReference(ConcreteReference.builder().setClazz(ImmutableMap.Builder.class).setGenerics(retryCodesDefinitionsClassMemberVarExpr.type().reference().generics()).build());
    VariableExpr definitionsVarExpr = VariableExpr.withVariable(Variable.builder().setType(definitionsType).setName("definitions").build());
    List<Expr> bodyExprs = new ArrayList<>();
    // Create the first expr.
    bodyExprs.add(AssignmentExpr.builder().setVariableExpr(definitionsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")).setMethodName("builder").setReturnType(definitionsVarExpr.type()).build()).build());
    for (Map.Entry<String, List<Code>> codeEntry : serviceConfig.getAllRetryCodes(service).entrySet()) {
        bodyExprs.add(createRetryCodeDefinitionExpr(codeEntry.getKey(), codeEntry.getValue(), definitionsVarExpr));
    }
    // Reassign the new codes.
    bodyExprs.add(AssignmentExpr.builder().setVariableExpr(retryCodesDefinitionsClassMemberVarExpr).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(definitionsVarExpr).setMethodName("build").setReturnType(retryCodesDefinitionsClassMemberVarExpr.type()).build()).build());
    // Put everything together.
    return BlockStatement.builder().setIsStatic(true).setBody(bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build();
}
Also used : BlockStatement(com.google.api.generator.engine.ast.BlockStatement) Arrays(java.util.Arrays) TypeNode(com.google.api.generator.engine.ast.TypeNode) GapicLroRetrySettings(com.google.api.generator.gapic.model.GapicLroRetrySettings) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) ProtoOperationTransformers(com.google.api.gax.grpc.ProtoOperationTransformers) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) FlowControlSettings(com.google.api.gax.batching.FlowControlSettings) FlowController(com.google.api.gax.batching.FlowController) RetryPolicy(io.grpc.serviceconfig.MethodConfig.RetryPolicy) Variable(com.google.api.generator.engine.ast.Variable) Function(java.util.function.Function) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) Durations(com.google.protobuf.util.Durations) ArrayList(java.util.ArrayList) RetrySettings(com.google.api.gax.retrying.RetrySettings) UnaryCallSettings(com.google.api.gax.rpc.UnaryCallSettings) Expr(com.google.api.generator.engine.ast.Expr) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) Method(com.google.api.generator.gapic.model.Method) Lists(com.google.common.collect.Lists) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) Map(java.util.Map) Code(com.google.rpc.Code) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) BatchingSettings(com.google.api.gax.batching.BatchingSettings) OperationSnapshot(com.google.api.gax.longrunning.OperationSnapshot) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) GapicBatchingSettings(com.google.api.generator.gapic.model.GapicBatchingSettings) Collectors(java.util.stream.Collectors) GapicRetrySettings(com.google.api.generator.gapic.model.GapicRetrySettings) Service(com.google.api.generator.gapic.model.Service) Duration(com.google.protobuf.Duration) List(java.util.List) OperationTimedPollAlgorithm(com.google.api.gax.longrunning.OperationTimedPollAlgorithm) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) Optional(java.util.Optional) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Preconditions(com.google.common.base.Preconditions) StatusCode(com.google.api.gax.rpc.StatusCode) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) 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) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ArrayList(java.util.ArrayList) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) ArrayList(java.util.ArrayList) List(java.util.List) TypeNode(com.google.api.generator.engine.ast.TypeNode) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 4 with GapicServiceConfig

use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.

the class RetrySettingsComposer method createRetryParamDefinitionsBlock.

public static BlockStatement createRetryParamDefinitionsBlock(Service service, GapicServiceConfig serviceConfig, VariableExpr retryParamDefinitionsClassMemberVarExpr) {
    List<Expr> bodyExprs = new ArrayList<>();
    TypeNode definitionsType = TypeNode.withReference(ConcreteReference.builder().setClazz(ImmutableMap.Builder.class).setGenerics(retryParamDefinitionsClassMemberVarExpr.type().reference().generics()).build());
    VariableExpr definitionsVarExpr = VariableExpr.withVariable(Variable.builder().setType(definitionsType).setName("definitions").build());
    VariableExpr settingsVarExpr = VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("RetrySettings")).setName("settings").build());
    // Create the first two exprs.
    bodyExprs.add(AssignmentExpr.builder().setVariableExpr(definitionsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")).setMethodName("builder").setReturnType(definitionsVarExpr.type()).build()).build());
    bodyExprs.add(AssignmentExpr.builder().setVariableExpr(settingsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(ValueExpr.createNullExpr()).build());
    // Build the settings object for each config.
    for (Map.Entry<String, GapicRetrySettings> settingsEntry : serviceConfig.getAllGapicRetrySettings(service).entrySet()) {
        bodyExprs.addAll(createRetrySettingsExprs(settingsEntry.getKey(), settingsEntry.getValue(), settingsVarExpr, definitionsVarExpr));
    }
    // Reassign the new settings.
    bodyExprs.add(AssignmentExpr.builder().setVariableExpr(retryParamDefinitionsClassMemberVarExpr).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(definitionsVarExpr).setMethodName("build").setReturnType(retryParamDefinitionsClassMemberVarExpr.type()).build()).build());
    // Put everything together.
    return BlockStatement.builder().setIsStatic(true).setBody(bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build();
}
Also used : BlockStatement(com.google.api.generator.engine.ast.BlockStatement) Arrays(java.util.Arrays) TypeNode(com.google.api.generator.engine.ast.TypeNode) GapicLroRetrySettings(com.google.api.generator.gapic.model.GapicLroRetrySettings) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) ProtoOperationTransformers(com.google.api.gax.grpc.ProtoOperationTransformers) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) FlowControlSettings(com.google.api.gax.batching.FlowControlSettings) FlowController(com.google.api.gax.batching.FlowController) RetryPolicy(io.grpc.serviceconfig.MethodConfig.RetryPolicy) Variable(com.google.api.generator.engine.ast.Variable) Function(java.util.function.Function) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) Durations(com.google.protobuf.util.Durations) ArrayList(java.util.ArrayList) RetrySettings(com.google.api.gax.retrying.RetrySettings) UnaryCallSettings(com.google.api.gax.rpc.UnaryCallSettings) Expr(com.google.api.generator.engine.ast.Expr) TypeStore(com.google.api.generator.gapic.composer.store.TypeStore) Method(com.google.api.generator.gapic.model.Method) Lists(com.google.common.collect.Lists) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) Map(java.util.Map) Code(com.google.rpc.Code) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) BatchingSettings(com.google.api.gax.batching.BatchingSettings) OperationSnapshot(com.google.api.gax.longrunning.OperationSnapshot) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) GapicBatchingSettings(com.google.api.generator.gapic.model.GapicBatchingSettings) Collectors(java.util.stream.Collectors) GapicRetrySettings(com.google.api.generator.gapic.model.GapicRetrySettings) Service(com.google.api.generator.gapic.model.Service) Duration(com.google.protobuf.Duration) List(java.util.List) OperationTimedPollAlgorithm(com.google.api.gax.longrunning.OperationTimedPollAlgorithm) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) Optional(java.util.Optional) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Preconditions(com.google.common.base.Preconditions) StatusCode(com.google.api.gax.rpc.StatusCode) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) 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) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) ArrayList(java.util.ArrayList) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) GapicRetrySettings(com.google.api.generator.gapic.model.GapicRetrySettings) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 5 with GapicServiceConfig

use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.

the class Parser method parseMethods.

@VisibleForTesting
static List<Method> parseMethods(ServiceDescriptor serviceDescriptor, String servicePackage, Map<String, Message> messageTypes, Map<String, ResourceName> resourceNames, Optional<GapicServiceConfig> serviceConfigOpt, Set<ResourceName> outputArgResourceNames, Transport transport) {
    List<Method> methods = new ArrayList<>();
    for (MethodDescriptor protoMethod : serviceDescriptor.getMethods()) {
        // Parse the method.
        TypeNode inputType = TypeParser.parseType(protoMethod.getInputType());
        Method.Builder methodBuilder = Method.builder();
        if (protoMethod.getFile().toProto().hasSourceCodeInfo()) {
            SourceCodeInfoLocation protoMethodLocation = SOURCE_CODE_INFO_PARSER.getLocation(protoMethod);
            if (!Objects.isNull(protoMethodLocation) && !Strings.isNullOrEmpty(protoMethodLocation.getLeadingComments())) {
                methodBuilder.setDescription(protoMethodLocation.getLeadingComments());
            }
        }
        boolean isDeprecated = false;
        if (protoMethod.getOptions().hasDeprecated()) {
            isDeprecated = protoMethod.getOptions().getDeprecated();
        }
        Message inputMessage = messageTypes.get(inputType.reference().fullName());
        Preconditions.checkNotNull(inputMessage, String.format("No message found for %s", inputType.reference().fullName()));
        HttpBindings httpBindings = HttpRuleParser.parse(protoMethod, inputMessage, messageTypes);
        boolean isBatching = !serviceConfigOpt.isPresent() ? false : serviceConfigOpt.get().hasBatchingSetting(/* protoPakkage */
        protoMethod.getFile().getPackage(), serviceDescriptor.getName(), protoMethod.getName());
        boolean operationPollingMethod = protoMethod.getOptions().hasExtension(ExtendedOperationsProto.operationPollingMethod) ? protoMethod.getOptions().getExtension(ExtendedOperationsProto.operationPollingMethod) : false;
        RoutingHeaderRule routingHeaderRule = RoutingRuleParser.parse(protoMethod, inputMessage, messageTypes);
        methods.add(methodBuilder.setName(protoMethod.getName()).setInputType(inputType).setOutputType(TypeParser.parseType(protoMethod.getOutputType())).setStream(Method.toStream(protoMethod.isClientStreaming(), protoMethod.isServerStreaming())).setLro(parseLro(servicePackage, protoMethod, messageTypes)).setMethodSignatures(MethodSignatureParser.parseMethodSignatures(protoMethod, servicePackage, inputType, messageTypes, resourceNames, outputArgResourceNames)).setHttpBindings(httpBindings).setRoutingHeaderRule(routingHeaderRule).setIsBatching(isBatching).setPageSizeFieldName(parsePageSizeFieldName(protoMethod, messageTypes, transport)).setIsDeprecated(isDeprecated).setOperationPollingMethod(operationPollingMethod).build());
        // Any input type that has a resource reference will need a resource name helper class.
        for (Field field : inputMessage.fields()) {
            if (field.hasResourceReference()) {
                String resourceTypeString = field.resourceReference().resourceTypeString();
                ResourceName resourceName = null;
                // versus example.com/FooBar.
                if (resourceTypeString.indexOf(SLASH) < 0) {
                    Optional<String> actualResourceTypeNameOpt = resourceNames.keySet().stream().filter(k -> k.substring(k.lastIndexOf(SLASH) + 1).equals(resourceTypeString)).findFirst();
                    if (actualResourceTypeNameOpt.isPresent()) {
                        resourceName = resourceNames.get(actualResourceTypeNameOpt.get());
                    }
                } else {
                    resourceName = resourceNames.get(resourceTypeString);
                }
                if (ResourceNameConstants.WILDCARD_PATTERN.equals(resourceTypeString)) {
                    resourceName = WILDCARD_RESOURCE_NAME;
                } else {
                    Preconditions.checkNotNull(resourceName, String.format("Resource name %s not found; parsing field %s in message %s in method %s", resourceTypeString, field.name(), inputMessage.name(), protoMethod.getName()));
                }
                outputArgResourceNames.add(resourceName);
            }
        }
    }
    return methods;
}
Also used : HttpBindings(com.google.api.generator.gapic.model.HttpBindings) CodeGeneratorRequest(com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest) Arrays(java.util.Arrays) RoutingHeaderRule(com.google.api.generator.gapic.model.RoutingHeaderRule) OperationInfo(com.google.longrunning.OperationInfo) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) DescriptorValidationException(com.google.protobuf.Descriptors.DescriptorValidationException) Field(com.google.api.generator.gapic.model.Field) Method(com.google.api.generator.gapic.model.Method) HttpRule(com.google.api.HttpRule) LongrunningOperation(com.google.api.generator.gapic.model.LongrunningOperation) Map(java.util.Map) ResourceProto(com.google.api.ResourceProto) FieldOptions(com.google.protobuf.DescriptorProtos.FieldOptions) FileDescriptor(com.google.protobuf.Descriptors.FileDescriptor) BiMap(com.google.common.collect.BiMap) ResourceDescriptor(com.google.api.ResourceDescriptor) ImmutableSet(com.google.common.collect.ImmutableSet) ResourceReference(com.google.api.generator.gapic.model.ResourceReference) Collection(java.util.Collection) Set(java.util.Set) FieldDescriptor(com.google.protobuf.Descriptors.FieldDescriptor) OperationsProto(com.google.longrunning.OperationsProto) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ResourceNameConstants(com.google.api.generator.gapic.utils.ResourceNameConstants) List(java.util.List) FileDescriptorProto(com.google.protobuf.DescriptorProtos.FileDescriptorProto) EnumDescriptor(com.google.protobuf.Descriptors.EnumDescriptor) DocumentationRule(com.google.api.DocumentationRule) Optional(java.util.Optional) Transport(com.google.api.generator.gapic.model.Transport) GapicContext(com.google.api.generator.gapic.model.GapicContext) GapicLanguageSettings(com.google.api.generator.gapic.model.GapicLanguageSettings) IntStream(java.util.stream.IntStream) VaporReference(com.google.api.generator.engine.ast.VaporReference) TypeNode(com.google.api.generator.engine.ast.TypeNode) GapicLroRetrySettings(com.google.api.generator.gapic.model.GapicLroRetrySettings) Descriptor(com.google.protobuf.Descriptors.Descriptor) HashMap(java.util.HashMap) Function(java.util.function.Function) OperationResponseMapping(com.google.cloud.OperationResponseMapping) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) MethodDescriptor(com.google.protobuf.Descriptors.MethodDescriptor) GapicBatchingSettings(com.google.api.generator.gapic.model.GapicBatchingSettings) Maps(com.google.common.collect.Maps) ResourceName(com.google.api.generator.gapic.model.ResourceName) Service(com.google.api.generator.gapic.model.Service) HashBiMap(com.google.common.collect.HashBiMap) ServiceOptions(com.google.protobuf.DescriptorProtos.ServiceOptions) ExtendedOperationsProto(com.google.cloud.ExtendedOperationsProto) EnumValueDescriptor(com.google.protobuf.Descriptors.EnumValueDescriptor) Preconditions(com.google.common.base.Preconditions) ServiceDescriptor(com.google.protobuf.Descriptors.ServiceDescriptor) OperationResponse(com.google.api.generator.gapic.model.OperationResponse) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Message(com.google.api.generator.gapic.model.Message) MethodOptions(com.google.protobuf.DescriptorProtos.MethodOptions) Collections(java.util.Collections) ClientProto(com.google.api.ClientProto) MessageOptions(com.google.protobuf.DescriptorProtos.MessageOptions) SourceCodeInfoLocation(com.google.api.generator.gapic.model.SourceCodeInfoLocation) Message(com.google.api.generator.gapic.model.Message) HttpBindings(com.google.api.generator.gapic.model.HttpBindings) ResourceName(com.google.api.generator.gapic.model.ResourceName) ArrayList(java.util.ArrayList) Method(com.google.api.generator.gapic.model.Method) MethodDescriptor(com.google.protobuf.Descriptors.MethodDescriptor) Field(com.google.api.generator.gapic.model.Field) SourceCodeInfoLocation(com.google.api.generator.gapic.model.SourceCodeInfoLocation) RoutingHeaderRule(com.google.api.generator.gapic.model.RoutingHeaderRule) TypeNode(com.google.api.generator.engine.ast.TypeNode) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

GapicServiceConfig (com.google.api.generator.gapic.model.GapicServiceConfig)28 Service (com.google.api.generator.gapic.model.Service)26 Message (com.google.api.generator.gapic.model.Message)19 HashSet (java.util.HashSet)19 Path (java.nio.file.Path)17 ResourceName (com.google.api.generator.gapic.model.ResourceName)16 FileDescriptor (com.google.protobuf.Descriptors.FileDescriptor)16 List (java.util.List)15 GapicBatchingSettings (com.google.api.generator.gapic.model.GapicBatchingSettings)13 Method (com.google.api.generator.gapic.model.Method)13 Expr (com.google.api.generator.engine.ast.Expr)12 ServiceDescriptor (com.google.protobuf.Descriptors.ServiceDescriptor)12 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)11 ArrayList (java.util.ArrayList)10 Test (org.junit.Test)10 TypeNode (com.google.api.generator.engine.ast.TypeNode)9 GapicContext (com.google.api.generator.gapic.model.GapicContext)9 Preconditions (com.google.common.base.Preconditions)9 ImmutableSet (com.google.common.collect.ImmutableSet)9 Arrays (java.util.Arrays)9