Search in sources :

Example 21 with Sample

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

the class ServiceClientHeaderSampleComposerTest method composeClassHeaderSample_unaryRpc.

/*Testing composeClassHeaderSample*/
@Test
public void composeClassHeaderSample_unaryRpc() {
    Descriptors.FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor();
    Map<String, ResourceName> resourceNames = Parser.parseResourceNames(echoFileDescriptor);
    Map<String, Message> messageTypes = Parser.parseMessages(echoFileDescriptor);
    Set<ResourceName> outputResourceNames = new HashSet<>();
    List<Service> services = Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames);
    Service echoProtoService = services.get(0);
    TypeNode clientType = TypeNode.withReference(VaporReference.builder().setName("EchoClient").setPakkage(SHOWCASE_PACKAGE_NAME).build());
    Sample sample = ServiceClientHeaderSampleComposer.composeClassHeaderSample(echoProtoService, clientType, resourceNames, messageTypes);
    String results = writeStatements(sample);
    String expected = LineFormatter.lines("try (EchoClient echoClient = EchoClient.create()) {\n", "  EchoResponse response = echoClient.echo();\n", "}");
    Assert.assertEquals(expected, results);
}
Also used : Message(com.google.api.generator.gapic.model.Message) ResourceName(com.google.api.generator.gapic.model.ResourceName) Sample(com.google.api.generator.gapic.model.Sample) Service(com.google.api.generator.gapic.model.Service) Descriptors(com.google.protobuf.Descriptors) TypeNode(com.google.api.generator.engine.ast.TypeNode) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 22 with Sample

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

the class AbstractServiceClientClassComposer method createMethodDefaultMethod.

private static MethodDefinition createMethodDefaultMethod(Method method, String clientName, Map<String, Message> messageTypes, TypeStore typeStore, Map<String, ResourceName> resourceNames, List<Sample> samples) {
    String methodName = JavaStyle.toLowerCamelCase(method.name());
    TypeNode methodInputType = method.inputType();
    TypeNode methodOutputType = method.isPaged() ? typeStore.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) : method.outputType();
    List<AnnotationNode> annotations = new ArrayList<>();
    if (method.hasLro()) {
        LongrunningOperation lro = method.lro();
        methodOutputType = TypeNode.withReference(typeStore.get("OperationFuture").reference().copyAndSetGenerics(Arrays.asList(lro.responseType().reference(), lro.metadataType().reference())));
        if (method.lro().operationServiceStubType() != null) {
            annotations.add(AnnotationNode.withTypeAndDescription(typeStore.get("BetaApi"), "The surface for long-running operations is not stable yet and may change in the" + " future."));
        }
    }
    // Construct the method that accepts a request proto.
    VariableExpr requestArgVarExpr = VariableExpr.builder().setVariable(Variable.builder().setName("request").setType(methodInputType).build()).setIsDecl(true).build();
    String callableMethodName = method.isPaged() ? String.format(PAGED_CALLABLE_NAME_PATTERN, methodName) : String.format(CALLABLE_NAME_PATTERN, methodName);
    if (method.hasLro()) {
        callableMethodName = String.format(OPERATION_CALLABLE_NAME_PATTERN, methodName);
    }
    Optional<Sample> defaultMethodSample = Optional.of(ServiceClientMethodSampleComposer.composeCanonicalSample(method, typeStore.get(clientName), resourceNames, messageTypes));
    Optional<String> defaultMethodDocSample = Optional.empty();
    if (defaultMethodSample.isPresent()) {
        samples.add(defaultMethodSample.get());
        defaultMethodDocSample = Optional.of(SampleCodeWriter.writeInlineSample(defaultMethodSample.get().body()));
    }
    MethodInvocationExpr callableMethodExpr = MethodInvocationExpr.builder().setMethodName(callableMethodName).build();
    callableMethodExpr = MethodInvocationExpr.builder().setMethodName(method.hasLro() ? "futureCall" : "call").setArguments(Arrays.asList(requestArgVarExpr.toBuilder().setIsDecl(false).build())).setExprReferenceExpr(callableMethodExpr).setReturnType(methodOutputType).build();
    MethodDefinition.Builder methodBuilder = MethodDefinition.builder().setHeaderCommentStatements(ServiceClientCommentComposer.createRpcMethodHeaderComment(method, defaultMethodDocSample)).setScope(ScopeNode.PUBLIC).setIsFinal(true).setName(String.format(method.hasLro() ? "%sAsync" : "%s", methodName)).setArguments(Arrays.asList(requestArgVarExpr));
    if (method.isDeprecated()) {
        annotations.add(AnnotationNode.withType(TypeNode.DEPRECATED));
    }
    if (isProtoEmptyType(methodOutputType)) {
        methodBuilder = methodBuilder.setBody(Arrays.asList(ExprStatement.withExpr(callableMethodExpr))).setReturnType(TypeNode.VOID);
    } else {
        methodBuilder = methodBuilder.setReturnExpr(callableMethodExpr).setReturnType(methodOutputType);
    }
    methodBuilder.setAnnotations(annotations);
    return methodBuilder.build();
}
Also used : LongrunningOperation(com.google.api.generator.gapic.model.LongrunningOperation) Sample(com.google.api.generator.gapic.model.Sample) ArrayList(java.util.ArrayList) AnnotationNode(com.google.api.generator.engine.ast.AnnotationNode) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 23 with Sample

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

the class AbstractServiceClientClassComposer method createCallableMethod.

private static MethodDefinition createCallableMethod(Service service, Method method, CallableMethodKind callableMethodKind, TypeStore typeStore, Map<String, Message> messageTypes, Map<String, ResourceName> resourceNames, List<Sample> samples) {
    TypeNode rawCallableReturnType = null;
    if (callableMethodKind.equals(CallableMethodKind.LRO)) {
        rawCallableReturnType = typeStore.get("OperationCallable");
    } else {
        switch(method.stream()) {
            case CLIENT:
                rawCallableReturnType = typeStore.get("ClientStreamingCallable");
                break;
            case SERVER:
                rawCallableReturnType = typeStore.get("ServerStreamingCallable");
                break;
            case BIDI:
                rawCallableReturnType = typeStore.get("BidiStreamingCallable");
                break;
            case NONE:
            // Fall through.
            default:
                rawCallableReturnType = typeStore.get("UnaryCallable");
        }
    }
    // Set generics.
    TypeNode returnType = TypeNode.withReference(rawCallableReturnType.reference().copyAndSetGenerics(getGenericsForCallable(callableMethodKind, method, typeStore)));
    String rawMethodName = JavaStyle.toLowerCamelCase(method.name());
    String methodName = getCallableName(callableMethodKind, rawMethodName);
    TypeNode stubType = typeStore.get(ClassNames.getServiceStubClassName(service));
    MethodInvocationExpr returnExpr = MethodInvocationExpr.builder().setExprReferenceExpr(VariableExpr.builder().setVariable(Variable.builder().setName("stub").setType(stubType).build()).build()).setMethodName(methodName).setReturnType(returnType).build();
    Optional<Sample> sampleCode = Optional.empty();
    if (callableMethodKind.equals(CallableMethodKind.LRO)) {
        sampleCode = Optional.of(ServiceClientCallableMethodSampleComposer.composeLroCallableMethod(method, typeStore.get(ClassNames.getServiceClientClassName(service)), resourceNames, messageTypes));
    } else if (callableMethodKind.equals(CallableMethodKind.PAGED)) {
        sampleCode = Optional.of(ServiceClientCallableMethodSampleComposer.composePagedCallableMethod(method, typeStore.get(ClassNames.getServiceClientClassName(service)), resourceNames, messageTypes));
    } else if (callableMethodKind.equals(CallableMethodKind.REGULAR)) {
        if (method.stream().equals(Stream.NONE)) {
            sampleCode = Optional.of(ServiceClientCallableMethodSampleComposer.composeRegularCallableMethod(method, typeStore.get(ClassNames.getServiceClientClassName(service)), resourceNames, messageTypes));
        } else {
            sampleCode = Optional.of(ServiceClientCallableMethodSampleComposer.composeStreamCallableMethod(method, typeStore.get(ClassNames.getServiceClientClassName(service)), resourceNames, messageTypes));
        }
    }
    Optional<String> sampleDocCode = Optional.empty();
    if (sampleCode.isPresent()) {
        samples.add(sampleCode.get());
        sampleDocCode = Optional.of(SampleCodeWriter.writeInlineSample(sampleCode.get().body()));
    }
    MethodDefinition.Builder methodDefBuilder = MethodDefinition.builder();
    if (method.isDeprecated()) {
        methodDefBuilder = methodDefBuilder.setAnnotations(Arrays.asList(AnnotationNode.withType(TypeNode.DEPRECATED)));
    }
    return methodDefBuilder.setHeaderCommentStatements(ServiceClientCommentComposer.createRpcCallableMethodHeaderComment(method, sampleDocCode)).setScope(ScopeNode.PUBLIC).setIsFinal(true).setName(methodName).setReturnType(returnType).setReturnExpr(returnExpr).build();
}
Also used : MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Sample(com.google.api.generator.gapic.model.Sample) MethodDefinition(com.google.api.generator.engine.ast.MethodDefinition) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 24 with Sample

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

the class SampleComposerUtil method handleDuplicateSamples.

public static List<Sample> handleDuplicateSamples(List<Sample> samples) {
    // grab all distinct samples and group by sample name
    // ie: { "echo", ["echo(request"],
    // "echoString", ["echo(parent)", "echo(child)", "echo(context)"],
    // "echoDelete", ["echo.delete(request)"] }
    Map<String, List<Sample>> distinctSamplesGroupedByName = samples.stream().distinct().collect(Collectors.groupingBy(s -> s.name()));
    // collect samples that don't have duplicates
    // ie: ["echo", "echoDelete"]
    List<Sample> uniqueSamples = distinctSamplesGroupedByName.entrySet().stream().filter(entry -> entry.getValue().size() < 2).map(entry -> entry.getValue().get(0)).collect(Collectors.toList());
    if (uniqueSamples.size() == distinctSamplesGroupedByName.size()) {
        return uniqueSamples;
    }
    // collect samples that do have duplicates
    // ie: ["echoString"]
    List<Map.Entry<String, List<Sample>>> duplicateDistinctSamples = distinctSamplesGroupedByName.entrySet().stream().filter(entry -> entry.getValue().size() > 1).collect(Collectors.toList());
    // ie: ["echo", "echoDelete", "echoString", "echoString1"]
    for (Map.Entry<String, List<Sample>> entry : duplicateDistinctSamples) {
        int sampleNum = 0;
        for (Sample sample : entry.getValue()) {
            Sample uniqueSample = sample;
            // first sample will be "canonical", not updating name
            if (sampleNum != 0) {
                uniqueSample = sample.withRegionTag(sample.regionTag().withOverloadDisambiguation(sample.regionTag().overloadDisambiguation() + sampleNum));
            }
            uniqueSamples.add(uniqueSample);
            sampleNum++;
        }
    }
    return uniqueSamples;
}
Also used : AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) List(java.util.List) MethodArgument(com.google.api.generator.gapic.model.MethodArgument) TypeNode(com.google.api.generator.engine.ast.TypeNode) Map(java.util.Map) JavaStyle(com.google.api.generator.gapic.utils.JavaStyle) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) Sample(com.google.api.generator.gapic.model.Sample) Collectors(java.util.stream.Collectors) ResourceName(com.google.api.generator.gapic.model.ResourceName) Sample(com.google.api.generator.gapic.model.Sample) List(java.util.List) Map(java.util.Map)

Example 25 with Sample

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

the class ServiceClientCallableMethodSampleComposer method composeRegularCallableMethod.

// Compose sample code for the method where it is CallableMethodKind.REGULAR.
public static Sample composeRegularCallableMethod(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<Statement> bodyStatements = new ArrayList<>();
    bodyStatements.add(ExprStatement.withExpr(requestAssignmentExpr));
    RegionTag regionTag;
    if (method.isPaged()) {
        Sample pagedCallable = composePagedCallableSample(method, clientVarExpr, requestVarExpr, messageTypes);
        bodyStatements.addAll(pagedCallable.body());
        regionTag = pagedCallable.regionTag();
    } else {
        // e.g.  echoClient.echoCallable().futureCall(request)
        Sample unaryOrLroCallable = composeUnaryOrLroCallableSample(method, clientVarExpr, requestVarExpr);
        bodyStatements.addAll(unaryOrLroCallable.body());
        regionTag = unaryOrLroCallable.regionTag();
    }
    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 : Message(com.google.api.generator.gapic.model.Message) 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) 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) Sample(com.google.api.generator.gapic.model.Sample) ArrayList(java.util.ArrayList) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr)

Aggregations

Sample (com.google.api.generator.gapic.model.Sample)34 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)19 ExprStatement (com.google.api.generator.engine.ast.ExprStatement)17 TypeNode (com.google.api.generator.engine.ast.TypeNode)17 ArrayList (java.util.ArrayList)17 AssignmentExpr (com.google.api.generator.engine.ast.AssignmentExpr)16 MethodInvocationExpr (com.google.api.generator.engine.ast.MethodInvocationExpr)16 Statement (com.google.api.generator.engine.ast.Statement)16 CommentStatement (com.google.api.generator.engine.ast.CommentStatement)14 Message (com.google.api.generator.gapic.model.Message)14 List (java.util.List)13 Expr (com.google.api.generator.engine.ast.Expr)12 RegionTag (com.google.api.generator.gapic.model.RegionTag)12 ResourceName (com.google.api.generator.gapic.model.ResourceName)11 Collectors (java.util.stream.Collectors)11 TryCatchStatement (com.google.api.generator.engine.ast.TryCatchStatement)10 Variable (com.google.api.generator.engine.ast.Variable)10 JavaStyle (com.google.api.generator.gapic.utils.JavaStyle)10 Arrays (java.util.Arrays)10 Test (org.junit.Test)10