Search in sources :

Example 81 with Message

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

the class ServiceClientCallableMethodSampleComposer method composePagedCallableMethod.

// Compose sample code for the method where it is CallableMethodKind.PAGED.
public static Sample composePagedCallableMethod(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);
    // 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();
    // Create ApiFuture Variable Expression with assign value by invoking client paged callable
    // method.
    // e.g. ApiFuture<ListExclusionsPagedResponse> future =
    // configServiceV2Client.listExclusionsPagedCallable().futureCall(request);
    TypeNode apiFutureType = TypeNode.withReference(ConcreteReference.builder().setClazz(ApiFuture.class).setGenerics(repeatedResponseType.reference()).build());
    VariableExpr apiFutureVarExpr = VariableExpr.withVariable(Variable.builder().setName("future").setType(apiFutureType).build());
    MethodInvocationExpr pagedCallableFutureMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(String.format("%sPagedCallable", JavaStyle.toLowerCamelCase(method.name()))).build();
    pagedCallableFutureMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(pagedCallableFutureMethodExpr).setMethodName("futureCall").setArguments(requestVarExpr).setReturnType(apiFutureType).build();
    AssignmentExpr apiFutureAssignmentExpr = AssignmentExpr.builder().setVariableExpr(apiFutureVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(pagedCallableFutureMethodExpr).build();
    bodyExprs.add(apiFutureAssignmentExpr);
    List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
    bodyExprs.clear();
    // Add line comment
    bodyStatements.add(CommentStatement.withComment(LineComment.withComment("Do something.")));
    // For-loop on repeated response element
    // e.g. for (ListExclusionsResponse element : future.get().iterateAll()) {
    // // doThingsWith(element);
    // }
    VariableExpr repeatedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setName("element").setType(repeatedResponseType).build());
    MethodInvocationExpr futureGetIterateAllMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(apiFutureVarExpr).setMethodName("get").build();
    futureGetIterateAllMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(futureGetIterateAllMethodExpr).setMethodName("iterateAll").setReturnType(repeatedResponseType).build();
    CommentStatement lineCommentStatement = CommentStatement.withComment(LineComment.withComment("doThingsWith(element);"));
    ForStatement repeatedResponseForStatement = ForStatement.builder().setLocalVariableExpr(repeatedResponseVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(futureGetIterateAllMethodExpr).setBody(Arrays.asList(lineCommentStatement)).build();
    bodyStatements.add(repeatedResponseForStatement);
    List<Statement> body = Arrays.asList(TryCatchStatement.builder().setTryResourceExpr(SampleComposerUtil.assignClientVariableWithCreateMethodExpr(clientVarExpr)).setTryBody(bodyStatements).setIsSampleCode(true).build());
    RegionTag regionTag = RegionTag.builder().setServiceName(clientType.reference().name()).setRpcName(method.name()).setIsAsynchronous(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) CommentStatement(com.google.api.generator.engine.ast.CommentStatement) 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) Field(com.google.api.generator.gapic.model.Field) ApiFuture(com.google.api.core.ApiFuture) 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)

Example 82 with Message

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

the class HttpJsonServiceStubClassComposer method setOperationSnapshotFactoryExpr.

private List<Expr> setOperationSnapshotFactoryExpr(Method protoMethod, Map<String, Message> messageTypes) {
    // Generate input variables for create()
    VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(protoMethod.inputType()).setName("request").build());
    VariableExpr responseVarExpr = VariableExpr.withVariable(Variable.builder().setType(protoMethod.outputType()).setName("response").build());
    MethodInvocationExpr buildExpr;
    List<Statement> createBody = new ArrayList<>(4);
    TypeNode httpJsonOperationSnapshotType = FIXED_REST_TYPESTORE.get(HttpJsonOperationSnapshot.class.getSimpleName());
    TypeNode operationSnapshotType = FIXED_TYPESTORE.get(OperationSnapshot.class.getSimpleName());
    Message inputOperationMessage = messageTypes.get(protoMethod.inputType().reference().fullName());
    Message outputOperationMessage = messageTypes.get(protoMethod.outputType().reference().fullName());
    OperationResponse operationResponse = outputOperationMessage.operationResponse();
    if (operationResponse == null) {
        // AIP-151 LRO
        // HttpJsonOperationSnapshot.create(response)
        buildExpr = MethodInvocationExpr.builder().setStaticReferenceType(httpJsonOperationSnapshotType).setMethodName("create").setArguments(responseVarExpr).setReturnType(operationSnapshotType).build();
    } else {
        BiFunction<String, List<Expr>, Function<MethodInvocationExpr, MethodInvocationExpr>> methodMaker = getMethodMaker();
        // Generate opName
        TypeNode stringBuilderType = TypeNode.withReference(ConcreteReference.withClazz(StringBuilder.class));
        VariableExpr opNameVarExpr = VariableExpr.withVariable(Variable.builder().setType(stringBuilderType).setName("opName").build());
        MethodInvocationExpr getId = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.nameFieldName())).build();
        Expr opNameObjectExpr = NewObjectExpr.builder().setType(stringBuilderType).setArguments(getId).build();
        AssignmentExpr opNameAssignExpr = AssignmentExpr.builder().setVariableExpr(opNameVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(opNameObjectExpr).build();
        createBody.add(ExprStatement.withExpr(opNameAssignExpr));
        // Generate compound operation name
        if (!protoMethod.isOperationPollingMethod()) {
            // TODO: Change to ordered map
            Map<String, String> requestFields = inputOperationMessage.operationRequestFields();
            List<String> fieldAnnotationNames = new ArrayList<>(requestFields.keySet());
            Collections.sort(fieldAnnotationNames);
            for (String fieldName : fieldAnnotationNames) {
                createBody.add(appendField(opNameVarExpr, requestVarExpr, requestFields.get(fieldName)));
            }
        }
        // Generate check for status == done
        MethodInvocationExpr getStatusExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.statusFieldName())).build();
        String statusTypeName = operationResponse.statusFieldTypeName();
        String statusClassName = statusTypeName.substring(statusTypeName.lastIndexOf('.') + 1);
        TypeNode opType = protoMethod.hasLro() ? protoMethod.lro().responseType() : protoMethod.outputType();
        TypeNode statusType = TypeNode.withReference(VaporReference.builder().setName(statusClassName).setPakkage(opType.reference().fullName()).setIsStaticImport(false).build());
        VariableExpr statusDoneExpr = VariableExpr.builder().setVariable(Variable.builder().setName("DONE").setType(TypeNode.INT).build()).setStaticReferenceType(statusType).build();
        MethodInvocationExpr statusEqualsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(statusDoneExpr).setMethodName("equals").setArguments(getStatusExpr).build();
        // Generate return statement
        // Generate getter methods from annotations
        MethodInvocationExpr opNameToStringExpr = MethodInvocationExpr.builder().setExprReferenceExpr(opNameVarExpr).setMethodName("toString").build();
        MethodInvocationExpr getHttpErrorStatusCodeExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.errorCodeFieldName())).build();
        MethodInvocationExpr getHttpErrorMessageExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName(getMethodFormat(operationResponse.errorMessageFieldName())).build();
        MethodInvocationExpr newBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(httpJsonOperationSnapshotType).setMethodName("newBuilder").build();
        newBuilderExpr = methodMaker.apply("setName", Collections.singletonList(opNameToStringExpr)).apply(newBuilderExpr);
        newBuilderExpr = methodMaker.apply("setMetadata", Collections.singletonList(responseVarExpr)).apply(newBuilderExpr);
        newBuilderExpr = methodMaker.apply("setDone", Collections.singletonList(statusEqualsExpr)).apply(newBuilderExpr);
        newBuilderExpr = methodMaker.apply("setResponse", Collections.singletonList(responseVarExpr)).apply(newBuilderExpr);
        newBuilderExpr = methodMaker.apply("setError", Arrays.asList(getHttpErrorStatusCodeExpr, getHttpErrorMessageExpr)).apply(newBuilderExpr);
        buildExpr = MethodInvocationExpr.builder().setExprReferenceExpr(newBuilderExpr).setMethodName("build").setReturnType(operationSnapshotType).build();
    }
    // Generate lambda anonymous class
    return Collections.singletonList(LambdaExpr.builder().setArguments(requestVarExpr.toBuilder().setIsDecl(true).build(), responseVarExpr.toBuilder().setIsDecl(true).build()).setBody(createBody).setReturnExpr(buildExpr).build());
}
Also used : Message(com.google.api.generator.gapic.model.Message) IfStatement(com.google.api.generator.engine.ast.IfStatement) ExprStatement(com.google.api.generator.engine.ast.ExprStatement) Statement(com.google.api.generator.engine.ast.Statement) ArrayList(java.util.ArrayList) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) HttpJsonOperationSnapshot(com.google.api.gax.httpjson.HttpJsonOperationSnapshot) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) 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) LambdaExpr(com.google.api.generator.engine.ast.LambdaExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) TypeNode(com.google.api.generator.engine.ast.TypeNode) OperationSnapshot(com.google.api.gax.longrunning.OperationSnapshot) HttpJsonOperationSnapshot(com.google.api.gax.httpjson.HttpJsonOperationSnapshot) OperationResponse(com.google.api.generator.gapic.model.OperationResponse)

Example 83 with Message

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

the class ServiceClientTestClassComposer method createStreamingRpcTestMethod.

@Override
protected MethodDefinition createStreamingRpcTestMethod(Service service, Method method, Map<String, VariableExpr> classMemberVarExprs, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
    TypeNode methodOutputType = method.hasLro() ? method.lro().responseType() : method.outputType();
    List<Expr> methodExprs = new ArrayList<>();
    VariableExpr expectedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(methodOutputType).setName("expectedResponse").build());
    Expr expectedResponseValExpr = null;
    if (messageTypes.containsKey(methodOutputType.reference().fullName())) {
        expectedResponseValExpr = DefaultValueComposer.createSimpleMessageBuilderValue(messageTypes.get(methodOutputType.reference().fullName()), resourceNames, messageTypes);
    } else {
        // Wrap this in a field so we don't have to split the helper into lots of different methods,
        // or duplicate it for VariableExpr.
        expectedResponseValExpr = DefaultValueComposer.createValue(Field.builder().setType(methodOutputType).setIsMessage(true).setName("expectedResponse").build());
    }
    methodExprs.add(AssignmentExpr.builder().setVariableExpr(expectedResponseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(expectedResponseValExpr).build());
    String mockServiceVarName = getMockServiceVarName(service);
    if (method.hasLro()) {
        VariableExpr resultOperationVarExpr = VariableExpr.withVariable(Variable.builder().setType(FIXED_GRPC_TYPESTORE.get("Operation")).setName("resultOperation").build());
        methodExprs.add(AssignmentExpr.builder().setVariableExpr(resultOperationVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(DefaultValueComposer.createSimpleOperationBuilderValue(String.format("%sTest", JavaStyle.toLowerCamelCase(method.name())), expectedResponseVarExpr)).build());
        methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(mockServiceVarName)).setMethodName("addResponse").setArguments(resultOperationVarExpr).build());
    } else {
        methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(mockServiceVarName)).setMethodName("addResponse").setArguments(expectedResponseVarExpr).build());
    }
    // Construct the request or method arguments.
    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);
    methodExprs.add(AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
    List<Statement> methodStatements = new ArrayList<>();
    methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    methodExprs.clear();
    methodStatements.add(EMPTY_LINE_STATEMENT);
    // Construct the mock stream observer.
    VariableExpr responseObserverVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(FIXED_GRPC_TYPESTORE.get("MockStreamObserver").reference().copyAndSetGenerics(Arrays.asList(method.outputType().reference())))).setName("responseObserver").build());
    methodStatements.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(responseObserverVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(FIXED_GRPC_TYPESTORE.get("MockStreamObserver")).setIsGeneric(true).build()).build()));
    methodStatements.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();
    methodExprs.add(AssignmentExpr.builder().setVariableExpr(callableVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(streamingCallExpr).build());
    // Call the streaming-variant callable method.
    if (method.stream().equals(Method.Stream.SERVER)) {
        methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(callableVarExpr).setMethodName("serverStreamingCall").setArguments(requestVarExpr, responseObserverVarExpr).build());
    } else {
        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);
        methodExprs.add(AssignmentExpr.builder().setVariableExpr(requestObserverVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(callableVarExpr).setMethodName(getCallableMethodName(method)).setArguments(callableMethodArgs).setReturnType(requestObserverVarExpr.type()).build()).build());
        methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
        methodExprs.clear();
        methodStatements.add(EMPTY_LINE_STATEMENT);
        methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(requestObserverVarExpr).setMethodName("onNext").setArguments(requestVarExpr).build());
        methodExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(requestObserverVarExpr).setMethodName("onCompleted").build());
    }
    methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    methodExprs.clear();
    methodStatements.add(EMPTY_LINE_STATEMENT);
    // Check the actual responses.
    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();
    methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualResponsesVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(getFutureResponseExpr).build());
    // Assert the size is equivalent.
    methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("1").build()), MethodInvocationExpr.builder().setExprReferenceExpr(actualResponsesVarExpr).setMethodName("size").setReturnType(TypeNode.INT).build()).build());
    // Assert the responses are equivalent.
    Expr zeroExpr = ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build());
    Expr actualResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(actualResponsesVarExpr).setMethodName("get").setArguments(zeroExpr).build();
    methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(expectedResponseVarExpr, actualResponseExpr).build());
    methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
    methodExprs.clear();
    methodStatements.add(EMPTY_LINE_STATEMENT);
    String testMethodName = String.format("%sTest", JavaStyle.toLowerCamelCase(method.name()));
    return MethodDefinition.builder().setAnnotations(Arrays.asList(TEST_ANNOTATION)).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName(testMethodName).setThrowsExceptions(Arrays.asList(TypeNode.withExceptionClazz(Exception.class))).setBody(methodStatements).build();
}
Also used : 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) AbstractMessage(com.google.protobuf.AbstractMessage) Message(com.google.api.generator.gapic.model.Message) 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) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) List(java.util.List) ArrayList(java.util.ArrayList) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 84 with Message

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

the class HttpRuleParser method validateAndConstructHttpBindings.

private static Set<HttpBinding> validateAndConstructHttpBindings(Set<String> paramNames, Message inputMessage, Map<String, Message> messageTypes, Map<String, String> patternSampleValues) {
    ImmutableSortedSet.Builder<HttpBinding> httpBindings = ImmutableSortedSet.naturalOrder();
    for (String paramName : paramNames) {
        // Handle foo.bar cases by descending into the subfields.
        String patternSampleValue = patternSampleValues != null ? patternSampleValues.get(paramName) : null;
        String[] subFields = paramName.split("\\.");
        if (inputMessage == null) {
            httpBindings.add(HttpBinding.create(paramName, false, patternSampleValue));
            continue;
        }
        Message nestedMessage = inputMessage;
        for (int i = 0; i < subFields.length; i++) {
            String subFieldName = subFields[i];
            if (i < subFields.length - 1) {
                Field field = nestedMessage.fieldMap().get(subFieldName);
                nestedMessage = messageTypes.get(field.type().reference().fullName());
                Preconditions.checkNotNull(nestedMessage, String.format("No containing message found for field %s with type %s", field.name(), field.type().reference().simpleName()));
            } else {
                if (patternSampleValues != null) {
                    checkHttpFieldIsValid(subFieldName, nestedMessage, false);
                    patternSampleValue = patternSampleValues.get(paramName);
                }
                Field field = nestedMessage.fieldMap().get(subFieldName);
                httpBindings.add(HttpBinding.create(paramName, field.isProto3Optional(), patternSampleValue));
            }
        }
    }
    return httpBindings.build();
}
Also used : Field(com.google.api.generator.gapic.model.Field) Message(com.google.api.generator.gapic.model.Message) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) HttpBinding(com.google.api.generator.gapic.model.HttpBindings.HttpBinding)

Example 85 with Message

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

the class HttpRuleParser method parseHttpRuleHelper.

private static HttpBindings parseHttpRuleHelper(HttpRule httpRule, Optional<Message> inputMessageOpt, Map<String, Message> messageTypes) {
    // Get pattern.
    String pattern = getHttpVerbPattern(httpRule);
    ImmutableSet.Builder<String> bindingsBuilder = ImmutableSet.builder();
    bindingsBuilder.addAll(PatternParser.getPattenBindings(pattern));
    if (httpRule.getAdditionalBindingsCount() > 0) {
        for (HttpRule additionalRule : httpRule.getAdditionalBindingsList()) {
            // TODO: save additional bindings path in HttpRuleBindings
            bindingsBuilder.addAll(PatternParser.getPattenBindings(getHttpVerbPattern(additionalRule)));
        }
    }
    Set<String> pathParamNames = bindingsBuilder.build();
    Map<String, String> patternSampleValues = constructPathValuePatterns(pattern);
    // TODO: support nested message fields bindings
    String body = httpRule.getBody();
    Set<String> bodyParamNames;
    Set<String> queryParamNames;
    if (!inputMessageOpt.isPresent()) {
        // Must be a mixin, do not support full HttpRuleBindings for now
        bodyParamNames = ImmutableSet.of();
        queryParamNames = ImmutableSet.of();
    } else if (Strings.isNullOrEmpty(body)) {
        bodyParamNames = ImmutableSet.of();
        queryParamNames = Sets.difference(inputMessageOpt.get().fieldMap().keySet(), pathParamNames);
    } else if (body.equals(ASTERISK)) {
        bodyParamNames = Sets.difference(inputMessageOpt.get().fieldMap().keySet(), pathParamNames);
        queryParamNames = ImmutableSet.of();
    } else {
        bodyParamNames = ImmutableSet.of(body);
        Set<String> bodyBinidngsUnion = Sets.union(bodyParamNames, pathParamNames);
        queryParamNames = Sets.difference(inputMessageOpt.get().fieldMap().keySet(), bodyBinidngsUnion);
    }
    Message message = inputMessageOpt.orElse(null);
    return HttpBindings.builder().setHttpVerb(HttpBindings.HttpVerb.valueOf(httpRule.getPatternCase().toString())).setPattern(pattern).setPathParameters(validateAndConstructHttpBindings(pathParamNames, message, messageTypes, patternSampleValues)).setQueryParameters(validateAndConstructHttpBindings(queryParamNames, message, messageTypes, null)).setBodyParameters(validateAndConstructHttpBindings(bodyParamNames, message, messageTypes, null)).setIsAsteriskBody(body.equals(ASTERISK)).build();
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Message(com.google.api.generator.gapic.model.Message) HttpRule(com.google.api.HttpRule)

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