use of com.google.api.generator.gapic.model.MethodArgument in project gapic-generator-java by googleapis.
the class ServiceClientHeaderSampleComposerTest method valid_composeShowcaseMethodSample_lroRpcWithReturnResponseType.
@Test
public void valid_composeShowcaseMethodSample_lroRpcWithReturnResponseType() {
Descriptors.FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor();
Map<String, ResourceName> resourceNames = Parser.parseResourceNames(echoFileDescriptor);
Map<String, Message> messageTypes = Parser.parseMessages(echoFileDescriptor);
TypeNode clientType = TypeNode.withReference(VaporReference.builder().setName("EchoClient").setPakkage(SHOWCASE_PACKAGE_NAME).build());
TypeNode inputType = TypeNode.withReference(VaporReference.builder().setName("WaitRequest").setPakkage(SHOWCASE_PACKAGE_NAME).build());
TypeNode outputType = TypeNode.withReference(VaporReference.builder().setName("Operation").setPakkage(LRO_PACKAGE_NAME).build());
TypeNode responseType = TypeNode.withReference(VaporReference.builder().setName("WaitResponse").setPakkage(SHOWCASE_PACKAGE_NAME).build());
TypeNode metadataType = TypeNode.withReference(VaporReference.builder().setName("WaitMetadata").setPakkage(SHOWCASE_PACKAGE_NAME).build());
LongrunningOperation lro = LongrunningOperation.builder().setResponseType(responseType).setMetadataType(metadataType).build();
TypeNode ttlTypeNode = TypeNode.withReference(VaporReference.builder().setName("Duration").setPakkage(PROTO_PACKAGE_NAME).build());
MethodArgument ttl = MethodArgument.builder().setName("ttl").setType(ttlTypeNode).setField(Field.builder().setName("ttl").setType(ttlTypeNode).setIsMessage(true).setIsContainedInOneof(true).build()).build();
List<MethodArgument> arguments = Arrays.asList(ttl);
Method method = Method.builder().setName("Wait").setInputType(inputType).setOutputType(outputType).setLro(lro).setMethodSignatures(Arrays.asList(arguments)).build();
String results = writeStatements(ServiceClientHeaderSampleComposer.composeShowcaseMethodSample(method, clientType, arguments, resourceNames, messageTypes));
String expected = LineFormatter.lines("try (EchoClient echoClient = EchoClient.create()) {\n", " Duration ttl = Duration.newBuilder().build();\n", " WaitResponse response = echoClient.waitAsync(ttl).get();\n", "}");
Assert.assertEquals(results, expected);
}
use of com.google.api.generator.gapic.model.MethodArgument in project gapic-generator-java by googleapis.
the class ServiceClientHeaderSampleComposerTest method valid_composeShowcaseMethodSample_pagedRpcWithMultipleMethodArguments.
/*Testing composeShowcaseMethodSample*/
@Test
public void valid_composeShowcaseMethodSample_pagedRpcWithMultipleMethodArguments() {
Descriptors.FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor();
Map<String, ResourceName> resourceNames = Parser.parseResourceNames(echoFileDescriptor);
Map<String, Message> messageTypes = Parser.parseMessages(echoFileDescriptor);
TypeNode clientType = TypeNode.withReference(VaporReference.builder().setName("EchoClient").setPakkage(SHOWCASE_PACKAGE_NAME).build());
TypeNode inputType = TypeNode.withReference(VaporReference.builder().setName("ListContentRequest").setPakkage(SHOWCASE_PACKAGE_NAME).build());
TypeNode outputType = TypeNode.withReference(VaporReference.builder().setName("ListContentResponse").setPakkage(SHOWCASE_PACKAGE_NAME).build());
TypeNode resourceNameType = TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(ConcreteReference.withClazz(String.class)).build());
List<MethodArgument> arguments = Arrays.asList(MethodArgument.builder().setName("resourceName").setType(resourceNameType).setField(Field.builder().setName("resourceName").setType(resourceNameType).setIsRepeated(true).build()).build(), MethodArgument.builder().setName("filter").setType(TypeNode.STRING).setField(Field.builder().setName("filter").setType(TypeNode.STRING).build()).build());
Method method = Method.builder().setName("ListContent").setMethodSignatures(Arrays.asList(arguments)).setInputType(inputType).setOutputType(outputType).setPageSizeFieldName(PAGINATED_FIELD_NAME).build();
Reference repeatedResponseReference = VaporReference.builder().setName("Content").setPakkage(SHOWCASE_PACKAGE_NAME).build();
Field repeatedField = Field.builder().setName("responses").setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(repeatedResponseReference).build())).setIsMessage(true).setIsRepeated(true).build();
Field nextPagedTokenField = Field.builder().setName("next_page_token").setType(TypeNode.STRING).build();
Message listContentResponseMessage = Message.builder().setName("ListContentResponse").setFullProtoName("google.showcase.v1beta1.ListContentResponse").setType(outputType).setFields(Arrays.asList(repeatedField, nextPagedTokenField)).build();
messageTypes.put("com.google.showcase.v1beta1.ListContentResponse", listContentResponseMessage);
String results = writeStatements(ServiceClientHeaderSampleComposer.composeShowcaseMethodSample(method, clientType, arguments, resourceNames, messageTypes));
String expected = LineFormatter.lines("try (EchoClient echoClient = EchoClient.create()) {\n", " List<String> resourceName = new ArrayList<>();\n", " String filter = \"filter-1274492040\";\n", " for (Content element : echoClient.listContent(resourceName, filter).iterateAll())" + " {\n", " // doThingsWith(element);\n", " }\n", "}");
Assert.assertEquals(results, expected);
}
use of com.google.api.generator.gapic.model.MethodArgument in project gapic-generator-java by googleapis.
the class AbstractServiceClientTestClassComposer method createRpcTestMethod.
/**
* Creates a test method for a given RPC, e.g. createAssetTest.
*
* @param method the RPC for which this test method is created.
* @param apiService the host service under test.
* @param rpcService the service that {@code method} belongs to. This is not equal to {@code
* apiService} only when {@code method} is a mixin, in which case {@code rpcService} is the
* mixed-in service. If {@code apiService} and {@code rpcService} are different, they will be
* used only for pagination. Otherwise, {@code rpcService} subsumes {@code apiService}.
* @param methodSignature the method signature of the RPC under test.
* @param variantIndex the nth variant of the RPC under test. This applies when we have
* polymorphism due to the presence of several method signature annotations in the proto.
* @param isRequestArg whether the RPC variant under test take only the request proto message.
* @param classMemberVarExprs the class members in the generated test class.
* @param resourceNames the resource names available for use.
* @param messageTypes the proto message types available for use.
*/
private MethodDefinition createRpcTestMethod(Method method, Service apiService, Service rpcService, List<MethodArgument> methodSignature, int variantIndex, boolean isRequestArg, Map<String, VariableExpr> classMemberVarExprs, Map<String, ResourceName> resourceNames, Map<String, Message> messageTypes) {
if (!method.stream().equals(Method.Stream.NONE)) {
return createStreamingRpcTestMethod(rpcService, method, classMemberVarExprs, resourceNames, messageTypes);
}
// Construct the expected response.
TypeNode methodOutputType = method.hasLro() ? method.lro().responseType() : method.outputType();
List<Expr> methodExprs = new ArrayList<>();
TypeNode repeatedResponseType = null;
VariableExpr responsesElementVarExpr = null;
String mockServiceVarName = getMockServiceVarName(rpcService);
if (method.isPaged()) {
Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated field found for paged method %s with output message type %s", method.name(), methodOutputMessage.name()));
if (repeatedPagedResultsField.isMap()) {
repeatedResponseType = TypeNode.withReference(repeatedPagedResultsField.type().reference().generics().get(1));
} else {
// Must be a non-repeated type.
repeatedResponseType = repeatedPagedResultsField.type();
}
responsesElementVarExpr = VariableExpr.withVariable(Variable.builder().setType(repeatedResponseType).setName("responsesElement").build());
methodExprs.add(AssignmentExpr.builder().setVariableExpr(responsesElementVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(DefaultValueComposer.createValue(Field.builder().setType(repeatedResponseType).setName("responsesElement").setIsMessage(!repeatedResponseType.isProtoPrimitiveType()).build())).build());
}
VariableExpr expectedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(methodOutputType).setName("expectedResponse").build());
Expr expectedResponseValExpr = null;
if (method.isPaged()) {
Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
Field firstRepeatedField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
Preconditions.checkNotNull(firstRepeatedField, String.format("Expected paged RPC %s to have a repeated field in the response %s but found none", method.name(), methodOutputMessage.name()));
expectedResponseValExpr = DefaultValueComposer.createSimplePagedResponseValue(method.outputType(), firstRepeatedField.name(), responsesElementVarExpr, firstRepeatedField.isMap());
} else {
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());
if (method.hasLro() && (method.lro().operationServiceStubType() == null || !method.lro().responseType().equals(method.outputType()))) {
VariableExpr resultOperationVarExpr = VariableExpr.withVariable(Variable.builder().setType(FIXED_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());
}
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 request or method arguments.
VariableExpr requestVarExpr = null;
Message requestMessage = null;
List<VariableExpr> argExprs = new ArrayList<>();
if (isRequestArg) {
requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
argExprs.add(requestVarExpr);
requestMessage = messageTypes.get(method.inputType().reference().fullName());
Preconditions.checkNotNull(requestMessage);
Map<String, String> pathParamValuePatterns = Collections.emptyMap();
if (getTransportContext().useValuePatterns() && method.hasHttpBindings()) {
pathParamValuePatterns = method.httpBindings().getPathParametersValuePatterns();
}
Expr valExpr = DefaultValueComposer.createSimpleMessageBuilderValue(requestMessage, resourceNames, messageTypes, pathParamValuePatterns);
methodExprs.add(AssignmentExpr.builder().setVariableExpr(requestVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
} else {
Map<String, String> valuePatterns = Collections.emptyMap();
if (getTransportContext().useValuePatterns() && method.hasHttpBindings()) {
valuePatterns = method.httpBindings().getPathParametersValuePatterns();
}
for (MethodArgument methodArg : methodSignature) {
String methodArgName = JavaStyle.toLowerCamelCase(methodArg.name());
VariableExpr varExpr = VariableExpr.withVariable(Variable.builder().setType(methodArg.type()).setName(methodArgName).build());
argExprs.add(varExpr);
Expr valExpr = DefaultValueComposer.createMethodArgValue(methodArg, resourceNames, messageTypes, valuePatterns);
methodExprs.add(AssignmentExpr.builder().setVariableExpr(varExpr.toBuilder().setIsDecl(true).build()).setValueExpr(valExpr).build());
}
}
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
// Call the RPC Java method.
VariableExpr actualResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(!method.isPaged() ? methodOutputType : // does not have a client.
getPagedResponseType(method, method.isMixin() ? apiService : rpcService)).setName(method.isPaged() ? "pagedListResponse" : "actualResponse").build());
Expr rpcJavaMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get("client")).setMethodName(JavaStyle.toLowerCamelCase(method.name()) + (method.hasLro() ? "Async" : "")).setArguments(argExprs.stream().map(e -> (Expr) e).collect(Collectors.toList())).setReturnType(actualResponseVarExpr.type()).build();
if (method.hasLro()) {
rpcJavaMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(rpcJavaMethodInvocationExpr).setMethodName("get").setReturnType(rpcJavaMethodInvocationExpr.type()).build();
}
boolean returnsVoid = isProtoEmptyType(methodOutputType);
if (returnsVoid) {
methodExprs.add(rpcJavaMethodInvocationExpr);
} else {
methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualResponseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(rpcJavaMethodInvocationExpr).build());
}
if (method.isPaged()) {
Message methodOutputMessage = messageTypes.get(method.outputType().reference().fullName());
Field repeatedPagedResultsField = methodOutputMessage.findAndUnwrapPaginatedRepeatedField();
// Assign the resources variable.
VariableExpr resourcesVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(repeatedPagedResultsField.type().reference())).build())).setName("resources").build());
Expr iterateAllExpr = MethodInvocationExpr.builder().setExprReferenceExpr(actualResponseVarExpr).setMethodName("iterateAll").build();
Expr resourcesValExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Lists")).setMethodName("newArrayList").setArguments(iterateAllExpr).setReturnType(resourcesVarExpr.type()).build();
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
methodStatements.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(resourcesVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(resourcesValExpr).build()));
methodStatements.add(EMPTY_LINE_STATEMENT);
// 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(resourcesVarExpr).setMethodName("size").setReturnType(TypeNode.INT).build()).build());
// Assert the responses are equivalent.
Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated field found for paged method %s with output message type %s", method.name(), methodOutputMessage.name()));
Expr zeroExpr = ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build());
// Generated code:
// Assert.assertEquals(
// expectedResponse.getItemsMap().entrySet().iterator().next(), resources.get(0));
// )
Expr expectedPagedResponseExpr;
if (repeatedPagedResultsField.isMap()) {
expectedPagedResponseExpr = MethodInvocationExpr.builder().setMethodName("next").setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("iterator").setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("entrySet").setExprReferenceExpr(MethodInvocationExpr.builder().setExprReferenceExpr(expectedResponseVarExpr).setMethodName(String.format("get%sMap", JavaStyle.toUpperCamelCase(repeatedPagedResultsField.name()))).build()).build()).build()).build();
} else {
// Generated code:
// Assert.assertEquals(expectedResponse.getItemsList().get(0), resources.get(0));
expectedPagedResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(expectedResponseVarExpr).setMethodName(String.format("get%sList", JavaStyle.toUpperCamelCase(repeatedPagedResultsField.name()))).build();
expectedPagedResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(expectedPagedResponseExpr).setMethodName("get").setArguments(zeroExpr).build();
}
Expr actualPagedResponseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(resourcesVarExpr).setMethodName("get").setArguments(zeroExpr).build();
methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(expectedPagedResponseExpr, actualPagedResponseExpr).build());
} else if (!returnsVoid) {
methodExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(expectedResponseVarExpr, actualResponseVarExpr).build());
}
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
methodStatements.addAll(methodExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.addAll(constructRpcTestCheckerLogic(method, rpcService, isRequestArg, classMemberVarExprs, requestVarExpr, requestMessage, argExprs));
String testMethodName = String.format("%sTest%s", JavaStyle.toLowerCamelCase(method.name()), variantIndex > 0 ? variantIndex + 1 : "");
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();
}
use of com.google.api.generator.gapic.model.MethodArgument in project gapic-generator-java by googleapis.
the class AbstractServiceClientClassComposer method createRequestBuilderExpr.
@VisibleForTesting
static Expr createRequestBuilderExpr(Method method, List<MethodArgument> signature, TypeStore typeStore) {
TypeNode methodInputType = method.inputType();
Expr newBuilderExpr = MethodInvocationExpr.builder().setMethodName("newBuilder").setStaticReferenceType(methodInputType).build();
// Maintain the args' order of appearance for better determinism.
List<Field> rootFields = new ArrayList<>();
Map<Field, Trie<Field>> rootFieldToTrie = new HashMap<>();
for (MethodArgument arg : signature) {
Field rootField = arg.nestedFields().isEmpty() ? arg.field() : arg.nestedFields().get(0);
if (!rootFields.contains(rootField)) {
rootFields.add(rootField);
}
Trie<Field> updatedTrie = rootFieldToTrie.containsKey(rootField) ? rootFieldToTrie.get(rootField) : new Trie<>();
List<Field> nestedFieldsWithChild = new ArrayList<>(arg.nestedFields());
nestedFieldsWithChild.add(arg.field());
updatedTrie.insert(nestedFieldsWithChild);
rootFieldToTrie.put(rootField, updatedTrie);
}
Function<Field, Expr> parentPreprocFn = field -> (Expr) MethodInvocationExpr.builder().setStaticReferenceType(field.type()).setMethodName("newBuilder").build();
TriFunction<Field, Expr, Expr, Expr> parentPostprocFn = (field, baseRefExpr, leafProcessedExpr) -> {
boolean isRootNode = field == null;
return isRootNode ? leafProcessedExpr : MethodInvocationExpr.builder().setExprReferenceExpr(baseRefExpr).setMethodName(String.format("set%s", JavaStyle.toUpperCamelCase(field.name()))).setArguments(MethodInvocationExpr.builder().setExprReferenceExpr(leafProcessedExpr).setMethodName("build").build()).build();
};
final Map<Field, MethodArgument> fieldToMethodArg = signature.stream().collect(Collectors.toMap(a -> a.field(), a -> a));
BiFunction<Field, Expr, Expr> leafProcFn = (field, parentBaseRefExpr) -> (Expr) buildNestedSetterInvocationExpr(fieldToMethodArg.get(field), parentBaseRefExpr);
for (Field rootField : rootFields) {
newBuilderExpr = rootFieldToTrie.get(rootField).dfsTraverseAndReduce(parentPreprocFn, parentPostprocFn, leafProcFn, newBuilderExpr);
}
return MethodInvocationExpr.builder().setExprReferenceExpr(newBuilderExpr).setMethodName("build").setReturnType(methodInputType).build();
}
use of com.google.api.generator.gapic.model.MethodArgument in project gapic-generator-java by googleapis.
the class MethodSignatureParser method flattenMethodSignatureVariants.
private static List<List<MethodArgument>> flattenMethodSignatureVariants(List<String> argumentNames, Map<String, List<MethodArgument>> argumentNameToOverloads, int depth) {
List<List<MethodArgument>> methodArgs = new ArrayList<>();
if (depth >= argumentNames.size() - 1) {
for (MethodArgument methodArg : argumentNameToOverloads.get(argumentNames.get(depth))) {
methodArgs.add(Lists.newArrayList(methodArg));
}
return methodArgs;
}
List<List<MethodArgument>> subsequentArgs = flattenMethodSignatureVariants(argumentNames, argumentNameToOverloads, depth + 1);
for (MethodArgument methodArg : argumentNameToOverloads.get(argumentNames.get(depth))) {
for (List<MethodArgument> subsequentArg : subsequentArgs) {
// Use a new list to avoid appending all subsequent elements (in upcoming loop iterations)
// to the same list.
List<MethodArgument> appendedArgs = new ArrayList<>(subsequentArg);
appendedArgs.add(0, methodArg);
methodArgs.add(appendedArgs);
}
}
return methodArgs;
}
Aggregations