Search in sources :

Example 11 with Message

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

the class ServiceClientTestClassComposer method createStreamingRpcExceptionTestStatements.

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

Example 12 with Message

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

the class DefaultValueComposer method createValue.

public static Expr createValue(Field field, boolean useExplicitInitTypeInGenerics, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes, Map<String, String> valuePatterns) {
    if (field.isRepeated()) {
        ConcreteReference.Builder refBuilder = ConcreteReference.builder().setClazz(field.isMap() ? HashMap.class : ArrayList.class);
        if (useExplicitInitTypeInGenerics) {
            if (field.isMap()) {
                refBuilder = refBuilder.setGenerics(field.type().reference().generics().subList(0, 2));
            } else {
                refBuilder = refBuilder.setGenerics(field.type().reference().generics().get(0));
            }
        }
        TypeNode newType = TypeNode.withReference(refBuilder.build());
        return NewObjectExpr.builder().setType(newType).setIsGeneric(true).build();
    }
    if (field.isEnum()) {
        return MethodInvocationExpr.builder().setStaticReferenceType(field.type()).setMethodName("forNumber").setArguments(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build())).setReturnType(field.type()).build();
    }
    if (field.isMessage()) {
        String nestedFieldName = field.name();
        Map<String, String> nestedValuePatterns = new HashMap<>();
        for (Map.Entry<String, String> entry : valuePatterns.entrySet()) {
            if (entry.getKey().startsWith(nestedFieldName + '.')) {
                nestedValuePatterns.put(entry.getKey().substring(nestedFieldName.length() + 1), entry.getValue());
            }
        }
        if (!nestedValuePatterns.isEmpty()) {
            Message nestedMessage = messageTypes.get(field.type().reference().fullName());
            if (nestedMessage != null) {
                return createSimpleMessageBuilderValue(nestedMessage, resourceNames, messageTypes, nestedValuePatterns);
            }
        }
        MethodInvocationExpr newBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(field.type()).setMethodName("newBuilder").build();
        return MethodInvocationExpr.builder().setExprReferenceExpr(newBuilderExpr).setMethodName("build").setReturnType(field.type()).build();
    }
    if (field.type().equals(TypeNode.STRING)) {
        String javaFieldName = JavaStyle.toLowerCamelCase(field.name());
        return ValueExpr.withValue(StringObjectValue.withValue(constructValueMatchingPattern(javaFieldName, valuePatterns.get(javaFieldName))));
    }
    if (TypeNode.isNumericType(field.type())) {
        return ValueExpr.withValue(PrimitiveValue.builder().setType(field.type()).setValue(String.format("%s", field.name().hashCode())).build());
    }
    if (field.type().equals(TypeNode.BOOLEAN)) {
        return ValueExpr.withValue(PrimitiveValue.builder().setType(field.type()).setValue("true").build());
    }
    if (field.type().equals(TypeNode.BYTESTRING)) {
        return VariableExpr.builder().setStaticReferenceType(TypeNode.BYTESTRING).setVariable(Variable.builder().setName("EMPTY").setType(TypeNode.BYTESTRING).build()).build();
    }
    throw new UnsupportedOperationException(String.format("Default value for field %s with type %s not implemented yet.", field.name(), field.type()));
}
Also used : Message(com.google.api.generator.gapic.model.Message) HashMap(java.util.HashMap) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ArrayList(java.util.ArrayList) TypeNode(com.google.api.generator.engine.ast.TypeNode) HashMap(java.util.HashMap) Map(java.util.Map) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference)

Example 13 with Message

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

the class GrpcServiceStubClassComposer method createMethodDescriptorVariableDecl.

@Override
protected Statement createMethodDescriptorVariableDecl(Service service, Method protoMethod, VariableExpr methodDescriptorVarExpr, Map<String, Message> messageTypes) {
    MethodInvocationExpr methodDescriptorMaker = MethodInvocationExpr.builder().setMethodName("newBuilder").setStaticReferenceType(FIXED_GRPC_TYPE_STORE.get("MethodDescriptor")).setGenerics(methodDescriptorVarExpr.variable().type().reference().generics()).build();
    BiFunction<String, Expr, Function<MethodInvocationExpr, MethodInvocationExpr>> methodMakerFn = (mName, argExpr) -> m -> MethodInvocationExpr.builder().setMethodName(mName).setArguments(Arrays.asList(argExpr)).setExprReferenceExpr(m).build();
    methodDescriptorMaker = methodMakerFn.apply("setType", getMethodDescriptorMethodTypeExpr(protoMethod)).apply(methodDescriptorMaker);
    String codeMethodNameArg = getProtoRpcFullMethodName(service, protoMethod);
    methodDescriptorMaker = methodMakerFn.apply("setFullMethodName", ValueExpr.withValue(StringObjectValue.withValue(codeMethodNameArg))).apply(methodDescriptorMaker);
    Function<MethodInvocationExpr, MethodInvocationExpr> protoUtilsMarshallerFn = m -> MethodInvocationExpr.builder().setStaticReferenceType(FIXED_GRPC_TYPE_STORE.get("ProtoUtils")).setMethodName("marshaller").setArguments(Arrays.asList(m)).build();
    MethodInvocationExpr methodInvocationArg = MethodInvocationExpr.builder().setMethodName("getDefaultInstance").setStaticReferenceType(protoMethod.inputType()).build();
    methodDescriptorMaker = methodMakerFn.apply("setRequestMarshaller", protoUtilsMarshallerFn.apply(methodInvocationArg)).apply(methodDescriptorMaker);
    methodInvocationArg = MethodInvocationExpr.builder().setMethodName("getDefaultInstance").setStaticReferenceType(protoMethod.outputType()).build();
    methodDescriptorMaker = methodMakerFn.apply("setResponseMarshaller", protoUtilsMarshallerFn.apply(methodInvocationArg)).apply(methodDescriptorMaker);
    methodDescriptorMaker = MethodInvocationExpr.builder().setMethodName("build").setExprReferenceExpr(methodDescriptorMaker).setReturnType(methodDescriptorVarExpr.type()).build();
    return ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(methodDescriptorVarExpr.toBuilder().setIsDecl(true).setScope(ScopeNode.PRIVATE).setIsStatic(true).setIsFinal(true).build()).setValueExpr(methodDescriptorMaker).build());
}
Also used : AbstractTransportServiceStubClassComposer(com.google.api.generator.gapic.composer.common.AbstractTransportServiceStubClassComposer) IfStatement(com.google.api.generator.engine.ast.IfStatement) Arrays(java.util.Arrays) TypeNode(com.google.api.generator.engine.ast.TypeNode) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) GrpcStubCallableFactory(com.google.api.gax.grpc.GrpcStubCallableFactory) BiFunction(java.util.function.BiFunction) PathTemplate(com.google.api.pathtemplate.PathTemplate) Variable(com.google.api.generator.engine.ast.Variable) Function(java.util.function.Function) StringObjectValue(com.google.api.generator.engine.ast.StringObjectValue) ArrayList(java.util.ArrayList) HttpBinding(com.google.api.generator.gapic.model.HttpBindings.HttpBinding) HashSet(java.util.HashSet) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) 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) ImmutableList(com.google.common.collect.ImmutableList) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) Map(java.util.Map) MethodDescriptor(io.grpc.MethodDescriptor) Splitter(com.google.common.base.Splitter) ProtoUtils(io.grpc.protobuf.ProtoUtils) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) ImmutableMap(com.google.common.collect.ImmutableMap) Set(java.util.Set) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) RequestParamsBuilder(com.google.api.gax.rpc.RequestParamsBuilder) Statement(com.google.api.generator.engine.ast.Statement) Service(com.google.api.generator.gapic.model.Service) List(java.util.List) GrpcCallSettings(com.google.api.gax.grpc.GrpcCallSettings) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) GrpcOperationsStub(com.google.longrunning.stub.GrpcOperationsStub) Message(com.google.api.generator.gapic.model.Message) RoutingHeaderParam(com.google.api.generator.gapic.model.RoutingHeaderRule.RoutingHeaderParam) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) EnumRefExpr(com.google.api.generator.engine.ast.EnumRefExpr) LogicalOperationExpr(com.google.api.generator.engine.ast.LogicalOperationExpr) Expr(com.google.api.generator.engine.ast.Expr) RelationalOperationExpr(com.google.api.generator.engine.ast.RelationalOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr)

Example 14 with Message

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

the class ServiceClientCallableMethodSampleComposer method composeLroCallableMethod.

// Compose sample code for the method where it is CallableMethodKind.LRO.
public static Sample composeLroCallableMethod(Method method, TypeNode clientType, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
    VariableExpr clientVarExpr = VariableExpr.withVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(clientType.reference().name())).setType(clientType).build());
    // Assign method's request variable with the default value.
    VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setName("request").setType(method.inputType()).build());
    Message requestMessage = messageTypes.get(method.inputType().reference().fullName());
    Preconditions.checkNotNull(requestMessage, String.format("Could not find the message type %s.", method.inputType().reference().fullName()));
    Expr requestBuilderExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes);
    AssignmentExpr requestAssignmentExpr = AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(requestBuilderExpr).build();
    List<Expr> bodyExprs = new ArrayList<>();
    bodyExprs.add(requestAssignmentExpr);
    // Create OperationFuture variable expr with invoking client's LRO callable method.
    // e.g. OperationFuture<Empty, WaitMetadata> future =
    // echoClient.waitOperationCallable().futureCall(request);
    TypeNode operationFutureType = TypeNode.withReference(ConcreteReference.builder().setClazz(OperationFuture.class).setGenerics(method.lro().responseType().reference(), method.lro().metadataType().reference()).build());
    VariableExpr operationFutureVarExpr = VariableExpr.withVariable(Variable.builder().setName("future").setType(operationFutureType).build());
    MethodInvocationExpr rpcMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(String.format("%sOperationCallable", JavaStyle.toLowerCamelCase(method.name()))).build();
    rpcMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(rpcMethodInvocationExpr).setMethodName("futureCall").setArguments(requestVarExpr).setReturnType(operationFutureType).build();
    bodyExprs.add(AssignmentExpr.builder().setVariableExpr(operationFutureVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(rpcMethodInvocationExpr).build());
    List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
    bodyExprs.clear();
    // Add a line comment
    bodyStatements.add(CommentStatement.withComment(LineComment.withComment("Do something.")));
    // Assign response variable with invoking client's LRO method.
    // e.g. if return void, future.get(); or,
    // e.g. if return other type, WaitResponse response = future.get();
    MethodInvocationExpr futureGetMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(operationFutureVarExpr).setMethodName("get").setReturnType(method.lro().responseType()).build();
    boolean returnsVoid = method.lro().responseType().isProtoEmptyType();
    if (returnsVoid) {
        bodyExprs.add(futureGetMethodExpr);
    } else {
        VariableExpr responseVarExpr = VariableExpr.builder().setVariable(Variable.builder().setName("response").setType(method.lro().responseType()).build()).setIsDecl(true).build();
        bodyExprs.add(AssignmentExpr.builder().setVariableExpr(responseVarExpr).setValueExpr(futureGetMethodExpr).build());
    }
    bodyStatements.addAll(bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    bodyExprs.clear();
    RegionTag regionTag = RegionTag.builder().setServiceName(clientType.reference().name()).setRpcName(method.name()).setIsAsynchronous(true).setOverloadDisambiguation("LRO").build();
    List<Statement> body = Arrays.asList(TryCatchStatement.builder().setTryResourceExpr(SampleComposerUtil.assignClientVariableWithCreateMethodExpr(clientVarExpr)).setTryBody(bodyStatements).setIsSampleCode(true).build());
    return Sample.builder().setBody(body).setRegionTag(regionTag).build();
}
Also used : IfStatement(com.google.api.generator.engine.ast.IfStatement) Arrays(java.util.Arrays) TypeNode(com.google.api.generator.engine.ast.TypeNode) OperationFuture(com.google.api.gax.longrunning.OperationFuture) BreakStatement(com.google.api.generator.engine.ast.BreakStatement) Operation(com.google.longrunning.Operation) Variable(com.google.api.generator.engine.ast.Variable) RegionTag(com.google.api.generator.gapic.model.RegionTag) ArrayList(java.util.ArrayList) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) DefaultValueComposer(com.google.api.generator.gapic.composer.defaultvalue.DefaultValueComposer) Strings(com.google.common.base.Strings) Expr(com.google.api.generator.engine.ast.Expr) Field(com.google.api.generator.gapic.model.Field) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) Method(com.google.api.generator.gapic.model.Method) PrimitiveValue(com.google.api.generator.engine.ast.PrimitiveValue) Map(java.util.Map) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) ServerStream(com.google.api.gax.rpc.ServerStream) LineComment(com.google.api.generator.engine.ast.LineComment) UnaryOperationExpr(com.google.api.generator.engine.ast.UnaryOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) ConcreteReference(com.google.api.generator.engine.ast.ConcreteReference) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) ForStatement(com.google.api.generator.engine.ast.ForStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) ScopeNode(com.google.api.generator.engine.ast.ScopeNode) Sample(com.google.api.generator.gapic.model.Sample) Collectors(java.util.stream.Collectors) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) ResourceName(com.google.api.generator.gapic.model.ResourceName) ApiFuture(com.google.api.core.ApiFuture) ApiStreamObserver(com.google.api.gax.rpc.ApiStreamObserver) Statement(com.google.api.generator.engine.ast.Statement) List(java.util.List) BidiStream(com.google.api.gax.rpc.BidiStream) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Preconditions(com.google.common.base.Preconditions) Message(com.google.api.generator.gapic.model.Message) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) Message(com.google.api.generator.gapic.model.Message) IfStatement(com.google.api.generator.engine.ast.IfStatement) BreakStatement(com.google.api.generator.engine.ast.BreakStatement) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) RegionTag(com.google.api.generator.gapic.model.RegionTag) ArrayList(java.util.ArrayList) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) Expr(com.google.api.generator.engine.ast.Expr) UnaryOperationExpr(com.google.api.generator.engine.ast.UnaryOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) OperationFuture(com.google.api.gax.longrunning.OperationFuture)

Example 15 with Message

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

the class ServiceClientCallableMethodSampleComposer method composePagedCallableSample.

private static Sample composePagedCallableSample(Method method, VariableExpr clientVarExpr, VariableExpr requestVarExpr, Map<String, Message> messageTypes) {
    // Find the repeated field.
    Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
    Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
    Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated field found on message %s for method %s", methodOutputMessage.name(), method.name()));
    TypeNode repeatedResponseType = repeatedPagedResultsField.type();
    // Assign future variable by invoking paged callable method.
    // e.g. ApiFuture<PagedExpandPagedResponse> future =
    // echoClient.pagedExpandCallable().futureCall(request);
    VariableExpr responseVarExpr = VariableExpr.withVariable(Variable.builder().setName("response").setType(method.outputType()).build());
    MethodInvocationExpr pagedCallableMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(JavaStyle.toLowerCamelCase(String.format("%sCallable", method.name()))).build();
    pagedCallableMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(pagedCallableMethodInvocationExpr).setMethodName("call").setArguments(requestVarExpr).setReturnType(method.outputType()).build();
    AssignmentExpr responseAssignmentExpr = AssignmentExpr.builder().setVariableExpr(responseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(pagedCallableMethodInvocationExpr).build();
    List<Statement> whileBodyStatements = new ArrayList<>();
    whileBodyStatements.add(ExprStatement.withExpr(responseAssignmentExpr));
    // For-loop on repeated response elements.
    // e.g. for (EchoResponse element : response.getResponsesList()) {
    // // doThingsWith(element);
    // }
    VariableExpr repeatedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setName("element").setType(repeatedResponseType).build());
    MethodInvocationExpr getResponseListMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName("getResponsesList").build();
    ForStatement responseForStatements = ForStatement.builder().setLocalVariableExpr(repeatedResponseVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(getResponseListMethodInvocationExpr).setBody(Arrays.asList(CommentStatement.withComment(LineComment.withComment("doThingsWith(element);")))).build();
    whileBodyStatements.add(responseForStatements);
    // Create nextPageToken variable expression and assign it with a value by invoking
    // getNextPageToken method.
    // e.g. String nextPageToken = response.getNextPageToken();
    VariableExpr nextPageTokenVarExpr = VariableExpr.withVariable(Variable.builder().setName("nextPageToken").setType(TypeNode.STRING).build());
    MethodInvocationExpr getNextPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName("getNextPageToken").setReturnType(TypeNode.STRING).build();
    AssignmentExpr nextPageTokenAssignmentExpr = AssignmentExpr.builder().setVariableExpr(nextPageTokenVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(getNextPageTokenMethodInvocationExpr).build();
    whileBodyStatements.add(ExprStatement.withExpr(nextPageTokenAssignmentExpr));
    // If nextPageToken variable expression is not null or empty, assign request variable with a
    // value by invoking setPageToken method.
    // if (!Strings.isNullOrEmpty(nextPageToken)) {
    // request =  request.toBuilder().setPageToken(nextPageToken).build();
    // } else {
    // break;
    // }
    Expr conditionExpr = UnaryOperationExpr.logicalNotWithExpr(MethodInvocationExpr.builder().setStaticReferenceType(TypeNode.withReference(ConcreteReference.withClazz(Strings.class))).setMethodName("isNullOrEmpty").setArguments(nextPageTokenVarExpr).setReturnType(TypeNode.BOOLEAN).build());
    MethodInvocationExpr setPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr).setMethodName("toBuilder").build();
    setPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(setPageTokenMethodInvocationExpr).setMethodName("setPageToken").setArguments(nextPageTokenVarExpr).build();
    setPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(setPageTokenMethodInvocationExpr).setMethodName("build").setReturnType(method.inputType()).build();
    AssignmentExpr requestReAssignmentExpr = AssignmentExpr.builder().setVariableExpr(requestVarExpr).setValueExpr(setPageTokenMethodInvocationExpr).build();
    IfStatement nextPageTokenIfStatement = IfStatement.builder().setConditionExpr(conditionExpr).setBody(Arrays.asList(ExprStatement.withExpr(requestReAssignmentExpr))).setElseBody(Arrays.asList(BreakStatement.create())).build();
    whileBodyStatements.add(nextPageTokenIfStatement);
    WhileStatement pagedWhileStatement = WhileStatement.builder().setConditionExpr(ValueExpr.withValue(PrimitiveValue.builder().setValue("true").setType(TypeNode.BOOLEAN).build())).setBody(whileBodyStatements).build();
    RegionTag regionTag = RegionTag.builder().setServiceName(clientVarExpr.variable().identifier().name()).setRpcName(method.name()).setOverloadDisambiguation("Paged").setIsAsynchronous(true).build();
    return Sample.builder().setBody(Arrays.asList(pagedWhileStatement)).setRegionTag(regionTag).build();
}
Also used : Message(com.google.api.generator.gapic.model.Message) IfStatement(com.google.api.generator.engine.ast.IfStatement) BreakStatement(com.google.api.generator.engine.ast.BreakStatement) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) ForStatement(com.google.api.generator.engine.ast.ForStatement) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) RegionTag(com.google.api.generator.gapic.model.RegionTag) ArrayList(java.util.ArrayList) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) WhileStatement(com.google.api.generator.engine.ast.WhileStatement) Strings(com.google.common.base.Strings) Field(com.google.api.generator.gapic.model.Field) IfStatement(com.google.api.generator.engine.ast.IfStatement) Expr(com.google.api.generator.engine.ast.Expr) UnaryOperationExpr(com.google.api.generator.engine.ast.UnaryOperationExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) AnonymousClassExpr(com.google.api.generator.engine.ast.AnonymousClassExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) ValueExpr(com.google.api.generator.engine.ast.ValueExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode) ForStatement(com.google.api.generator.engine.ast.ForStatement)

Aggregations

Message (com.google.api.generator.gapic.model.Message)123 ResourceName (com.google.api.generator.gapic.model.ResourceName)85 TypeNode (com.google.api.generator.engine.ast.TypeNode)74 Test (org.junit.Test)68 Method (com.google.api.generator.gapic.model.Method)60 FileDescriptor (com.google.protobuf.Descriptors.FileDescriptor)44 HashSet (java.util.HashSet)39 ArrayList (java.util.ArrayList)36 Service (com.google.api.generator.gapic.model.Service)35 List (java.util.List)34 Expr (com.google.api.generator.engine.ast.Expr)32 Field (com.google.api.generator.gapic.model.Field)31 Descriptors (com.google.protobuf.Descriptors)30 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)29 MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)26 ServiceDescriptor (com.google.protobuf.Descriptors.ServiceDescriptor)26 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)25 ExprStatement (com.google.api.generator.engine.ast.ExprStatement)25 Statement (com.google.api.generator.engine.ast.Statement)24 HashMap (java.util.HashMap)23