Search in sources :

Example 16 with Message

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

the class ServiceClientCallableMethodSampleComposer method composeStreamCallableMethod.

public static Sample composeStreamCallableMethod(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();
    RegionTag regionTag = null;
    List<Statement> bodyStatements = new ArrayList<>();
    if (method.stream().equals(Method.Stream.SERVER)) {
        // e.g. ServerStream<EchoResponse> stream = echoClient.expandCallable().call(request);
        Sample streamServer = composeStreamServerSample(method, clientVarExpr, requestAssignmentExpr);
        bodyStatements.addAll(streamServer.body());
        regionTag = streamServer.regionTag();
    } else if (method.stream().equals(Method.Stream.BIDI)) {
        // e.g. echoClient.collect().clientStreamingCall(responseObserver);
        Sample streamBidi = composeStreamBidiSample(method, clientVarExpr, requestAssignmentExpr);
        bodyStatements.addAll(streamBidi.body());
        regionTag = streamBidi.regionTag();
    } else if (method.stream().equals(Method.Stream.CLIENT)) {
        Sample streamClient = composeStreamClientSample(method, clientVarExpr, requestAssignmentExpr);
        bodyStatements.addAll(streamClient.body());
        regionTag = streamClient.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) RegionTag(com.google.api.generator.gapic.model.RegionTag) 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) 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)

Example 17 with Message

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

the class ServiceClientMethodSampleComposer method composePagedSample.

static Sample composePagedSample(Method method, VariableExpr clientVarExpr, List<VariableExpr> rpcMethodArgVarExprs, List<Expr> bodyExprs, Map<String, Message> messageTypes) {
    // Find the repeated field.
    Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
    Preconditions.checkNotNull(methodOutputMessage, "Output message %s not found, keys: ", method.outputType().reference().fullName(), messageTypes.keySet().toString());
    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();
    // For loop paged response item on iterateAll method.
    // e.g. for (LogEntry element : loggingServiceV2Client.ListLogs(parent).iterateAll()) {
    // //doThingsWith(element);
    // }
    MethodInvocationExpr clientMethodIterateAllExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(JavaStyle.toLowerCamelCase(method.name())).setArguments(rpcMethodArgVarExprs.stream().map(e -> (Expr) e).collect(Collectors.toList())).build();
    clientMethodIterateAllExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientMethodIterateAllExpr).setMethodName("iterateAll").setReturnType(repeatedResponseType).build();
    ForStatement loopIteratorStatement = ForStatement.builder().setLocalVariableExpr(VariableExpr.builder().setVariable(Variable.builder().setName("element").setType(repeatedResponseType).build()).setIsDecl(true).build()).setCollectionExpr(clientMethodIterateAllExpr).setBody(Arrays.asList(CommentStatement.withComment(LineComment.withComment("doThingsWith(element);")))).build();
    List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
    bodyExprs.clear();
    bodyStatements.add(loopIteratorStatement);
    RegionTag regionTag = RegionTag.builder().setServiceName(clientVarExpr.variable().identifier().name()).setRpcName(method.name()).setOverloadDisambiguation(SampleComposerUtil.createOverloadDisambiguation(rpcMethodArgVarExprs)).build();
    return Sample.builder().setBody(bodyStatements).setRegionTag(regionTag).build();
}
Also used : Arrays(java.util.Arrays) TypeNode(com.google.api.generator.engine.ast.TypeNode) Variable(com.google.api.generator.engine.ast.Variable) RegionTag(com.google.api.generator.gapic.model.RegionTag) ArrayList(java.util.ArrayList) DefaultValueComposer(com.google.api.generator.gapic.composer.defaultvalue.DefaultValueComposer) Expr(com.google.api.generator.engine.ast.Expr) Field(com.google.api.generator.gapic.model.Field) Method(com.google.api.generator.gapic.model.Method) Map(java.util.Map) TryCatchStatement(com.google.api.generator.engine.ast.TryCatchStatement) LineComment(com.google.api.generator.engine.ast.LineComment) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) 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) Sample(com.google.api.generator.gapic.model.Sample) Collectors(java.util.stream.Collectors) ResourceName(com.google.api.generator.gapic.model.ResourceName) Statement(com.google.api.generator.engine.ast.Statement) List(java.util.List) 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) Field(com.google.api.generator.gapic.model.Field) Message(com.google.api.generator.gapic.model.Message) Expr(com.google.api.generator.engine.ast.Expr) AssignmentExpr(com.google.api.generator.engine.ast.AssignmentExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) MethodInvocationExpr(com.google.api.generator.engine.ast.MethodInvocationExpr) 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) TypeNode(com.google.api.generator.engine.ast.TypeNode) ForStatement(com.google.api.generator.engine.ast.ForStatement)

Example 18 with Message

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

the class ServiceClientMethodSampleComposer method composeCanonicalSample.

public static Sample composeCanonicalSample(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());
    // Create request variable expression and assign with its default value.
    VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setName("request").setType(method.inputType()).build());
    List<VariableExpr> rpcMethodArgVarExprs = Arrays.asList(requestVarExpr);
    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);
    List<Statement> bodyStatements = new ArrayList<>();
    RegionTag regionTag;
    if (method.isPaged()) {
        // e.g. echoClient.pagedExpand(request).iterateAll()
        Sample unaryPagedRpc = composePagedSample(method, clientVarExpr, rpcMethodArgVarExprs, bodyExprs, messageTypes);
        bodyStatements.addAll(unaryPagedRpc.body());
        regionTag = unaryPagedRpc.regionTag();
    } else if (method.hasLro()) {
        Sample unaryLroRpc = composeLroSample(method, clientVarExpr, rpcMethodArgVarExprs, bodyExprs);
        bodyStatements.addAll(unaryLroRpc.body());
        regionTag = unaryLroRpc.regionTag();
    } else {
        // e.g. echoClient.echo(request)
        Sample unaryRpc = composeSample(method, clientVarExpr, rpcMethodArgVarExprs, bodyExprs);
        bodyStatements.addAll(unaryRpc.body());
        regionTag = unaryRpc.regionTag();
    }
    List<Statement> body = Arrays.asList(TryCatchStatement.builder().setTryResourceExpr(SampleComposerUtil.assignClientVariableWithCreateMethodExpr(clientVarExpr)).setTryBody(bodyStatements).setIsSampleCode(true).build());
    return Sample.builder().setBody(body).setRegionTag(regionTag).setIsCanonical(true).build();
}
Also used : Message(com.google.api.generator.gapic.model.Message) 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) 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)

Example 19 with Message

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

the class MethodSignatureParser method parseTypeFromArgumentName.

private static Map<TypeNode, Field> parseTypeFromArgumentName(String argumentName, String servicePackage, Message inputMessage, Map<String, Message> messageTypes, Map<String, ResourceName> resourceNames, Map<String, ResourceName> patternsToResourceNames, List<Field> argumentFieldPathAcc, Set<ResourceName> outputArgResourceNames) {
    Map<TypeNode, Field> typeToField = new HashMap<>();
    int dotIndex = argumentName.indexOf(DOT);
    if (dotIndex < 1) {
        Field field = inputMessage.fieldMap().get(argumentName);
        Preconditions.checkNotNull(field, String.format("Field %s not found from input message %s values %s", argumentName, inputMessage.name(), inputMessage.fieldMap().keySet()));
        if (!field.hasResourceReference()) {
            typeToField.put(field.type(), field);
            return typeToField;
        }
        // Parse the resource name tyeps.
        List<ResourceName> resourceNameArgs = ResourceReferenceParser.parseResourceNames(field.resourceReference(), servicePackage, field.description(), resourceNames, patternsToResourceNames);
        outputArgResourceNames.addAll(resourceNameArgs);
        typeToField.put(TypeNode.STRING, field);
        typeToField.putAll(resourceNameArgs.stream().collect(Collectors.toMap(r -> r.type(), r -> field.toBuilder().setResourceReference(ResourceReference.withType(r.resourceTypeString())).build())));
        // Only resource name helpers should have more than one entry.
        if (typeToField.size() > 1) {
            typeToField.entrySet().stream().forEach(e -> {
                // Skip string-only variants or ResourceName generics.
                if (e.getKey().equals(TypeNode.STRING) || e.getKey().reference().name().equals("ResourceName")) {
                    return;
                }
                String resourceJavaTypeName = e.getKey().reference().name();
                String resourceTypeName = e.getValue().resourceReference().resourceTypeString();
                int indexOfSlash = resourceTypeName.indexOf("/");
                // We assume that the corresponding Java resource name helper type (i.e. the key)
                // ends in *Name. Check that it matches the expeced resource name type.
                Preconditions.checkState(resourceJavaTypeName.substring(0, resourceJavaTypeName.length() - 4).equals(resourceTypeName.substring(indexOfSlash + 1)), String.format("Resource Java type %s does not correspond to proto type %s", resourceJavaTypeName, resourceTypeName));
            });
        }
        return typeToField;
    }
    Preconditions.checkState(dotIndex < argumentName.length() - 1, String.format("Invalid argument name found: dot cannot be at the end of name %s", argumentName));
    String firstFieldName = argumentName.substring(0, dotIndex);
    String remainingArgumentName = argumentName.substring(dotIndex + 1);
    // Must be a sub-message for a type's subfield to be valid.
    Field firstField = inputMessage.fieldMap().get(firstFieldName);
    // Validate the field into which we're descending.
    Preconditions.checkState(!firstField.isRepeated(), String.format("Cannot descend into repeated field %s", firstField.name()));
    TypeNode firstFieldType = firstField.type();
    Preconditions.checkState(TypeNode.isReferenceType(firstFieldType) && !firstFieldType.equals(TypeNode.STRING), String.format("Field reference on %s cannot be a primitive type", firstFieldName));
    String firstFieldTypeName = firstFieldType.reference().fullName();
    Message firstFieldMessage = messageTypes.get(firstFieldTypeName);
    Preconditions.checkNotNull(firstFieldMessage, String.format("Message type %s for field reference %s invalid", firstFieldTypeName, firstFieldName));
    argumentFieldPathAcc.add(firstField);
    return parseTypeFromArgumentName(remainingArgumentName, servicePackage, firstFieldMessage, messageTypes, resourceNames, patternsToResourceNames, argumentFieldPathAcc, outputArgResourceNames);
}
Also used : Field(com.google.api.generator.gapic.model.Field) Message(com.google.api.generator.gapic.model.Message) HashMap(java.util.HashMap) ResourceName(com.google.api.generator.gapic.model.ResourceName) TypeNode(com.google.api.generator.engine.ast.TypeNode)

Example 20 with Message

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

the class Parser method updateResourceNamesInMessages.

/**
 * Populates ResourceName objects in Message POJOs.
 *
 * @param messageTypes A map of the message type name (as in the protobuf) to Message POJOs.
 * @param resources A list of ResourceName POJOs.
 * @return The updated messageTypes map.
 */
public static Map<String, Message> updateResourceNamesInMessages(Map<String, Message> messageTypes, Collection<ResourceName> resources) {
    Map<String, Message> updatedMessages = new HashMap<>(messageTypes);
    for (ResourceName resource : resources) {
        if (!resource.hasParentMessageName()) {
            continue;
        }
        String messageKey = resource.parentMessageName();
        Message messageToUpdate = updatedMessages.get(messageKey);
        updatedMessages.put(messageKey, messageToUpdate.toBuilder().setResource(resource).build());
    }
    return updatedMessages;
}
Also used : Message(com.google.api.generator.gapic.model.Message) HashMap(java.util.HashMap) ResourceName(com.google.api.generator.gapic.model.ResourceName)

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