use of com.google.api.generator.gapic.model.Field 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.Field in project gapic-generator-java by googleapis.
the class AbstractServiceStubSettingsClassComposer method createPagingStaticAssignExprs.
private static List<Expr> createPagingStaticAssignExprs(Service service, GapicServiceConfig serviceConfig, Map<String, Message> messageTypes, TypeStore typeStore) {
List<Expr> descExprs = new ArrayList<>();
List<Expr> factoryExprs = new ArrayList<>();
for (Method method : service.methods()) {
if (!method.isPaged()) {
continue;
}
// Find the repeated type.
String pagedResponseMessageKey = method.outputType().reference().fullName();
if (method.hasLro()) {
pagedResponseMessageKey = method.lro().responseType().reference().fullName();
}
Message pagedResponseMessage = messageTypes.get(pagedResponseMessageKey);
Preconditions.checkNotNull(pagedResponseMessage, String.format("No method found for message type %s for method %s among %s", pagedResponseMessageKey, method.name(), messageTypes.keySet()));
Field repeatedPagedResultsField = pagedResponseMessage.findAndUnwrapPaginatedRepeatedField();
Preconditions.checkNotNull(repeatedPagedResultsField, String.format("No repeated type found for paged reesponse %s for method %s", method.outputType().reference().name(), method.name()));
TypeNode repeatedResponseType = repeatedPagedResultsField.type();
String repeatedFieldName = repeatedPagedResultsField.name();
// Create the PAGE_STR_DESC variable.
TypeNode pagedListDescType = TypeNode.withReference(ConcreteReference.builder().setClazz(PagedListDescriptor.class).setGenerics(Arrays.asList(method.inputType(), method.outputType(), repeatedResponseType).stream().map(t -> t.reference()).collect(Collectors.toList())).build());
String pageStrDescVarName = String.format(PAGE_STR_DESC_PATTERN, JavaStyle.toUpperSnakeCase(method.name()));
VariableExpr pagedListDescVarExpr = VariableExpr.withVariable(Variable.builder().setType(pagedListDescType).setName(pageStrDescVarName).build());
descExprs.add(createPagedListDescriptorAssignExpr(pagedListDescVarExpr, method, repeatedResponseType, repeatedFieldName, messageTypes, typeStore));
factoryExprs.add(createPagedListResponseFactoryAssignExpr(pagedListDescVarExpr, method, repeatedResponseType, typeStore));
}
descExprs.addAll(factoryExprs);
return descExprs;
}
use of com.google.api.generator.gapic.model.Field 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.Field in project gapic-generator-java by googleapis.
the class BatchingDescriptorComposer method createSplitResponseMethod.
private static MethodDefinition createSplitResponseMethod(Method method, GapicBatchingSettings batchingSettings, Map<String, Message> messageTypes) {
VariableExpr batchResponseVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.outputType()).setName("batchResponse").build());
TypeNode batchedRequestIssuerType = toType(BATCHED_REQUEST_ISSUER_REF, method.outputType());
TypeNode batchVarType = TypeNode.withReference(ConcreteReference.builder().setClazz(Collection.class).setGenerics(Arrays.asList(ConcreteReference.wildcardWithUpperBound(batchedRequestIssuerType.reference()))).build());
VariableExpr batchVarExpr = VariableExpr.withVariable(Variable.builder().setType(batchVarType).setName("batch").build());
VariableExpr responderVarExpr = VariableExpr.withVariable(Variable.builder().setType(batchedRequestIssuerType).setName("responder").build());
VariableExpr batchMessageIndexVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.INT).setName("batchMessageIndex").build());
VariableExpr subresponseElementsVarExpr = null;
boolean hasSubresponseField = batchingSettings.subresponseFieldName() != null;
List<Statement> outerForBody = new ArrayList<>();
if (hasSubresponseField) {
Message outputMessage = messageTypes.get(method.outputType().reference().fullName());
Preconditions.checkNotNull(outputMessage, String.format("Output message not found for RPC %s", method.name()));
Field subresponseElementField = outputMessage.fieldMap().get(batchingSettings.subresponseFieldName());
Preconditions.checkNotNull(subresponseElementField, String.format("Subresponse field %s not found in message %s", batchingSettings.subresponseFieldName(), outputMessage.name()));
TypeNode subresponseElementType = subresponseElementField.type();
subresponseElementsVarExpr = VariableExpr.withVariable(Variable.builder().setType(subresponseElementType).setName("subresponseElements").build());
VariableExpr subresponseCountVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.LONG).setName("subresponseCount").build());
outerForBody.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(subresponseElementsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(TypeNode.withReference(ConcreteReference.withClazz(ArrayList.class))).setIsGeneric(true).build()).build()));
String getFooCountMethodName = "getMessageCount";
outerForBody.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(subresponseCountVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(responderVarExpr).setMethodName(getFooCountMethodName).setReturnType(subresponseCountVarExpr.type()).build()).build()));
List<Expr> innerSubresponseForExprs = new ArrayList<>();
String getSubresponseFieldMethodName = String.format("get%s", JavaStyle.toUpperCamelCase(batchingSettings.subresponseFieldName()));
Expr addMethodArgExpr = MethodInvocationExpr.builder().setExprReferenceExpr(batchResponseVarExpr).setMethodName(getSubresponseFieldMethodName).setArguments(UnaryOperationExpr.postfixIncrementWithExpr(batchMessageIndexVarExpr)).build();
innerSubresponseForExprs.add(MethodInvocationExpr.builder().setExprReferenceExpr(subresponseElementsVarExpr).setMethodName("add").setArguments(addMethodArgExpr).build());
// TODO(miraleung): Increment batchMessageIndexVarExpr.
VariableExpr forIndexVarExpr = VariableExpr.builder().setIsDecl(true).setVariable(Variable.builder().setType(TypeNode.INT).setName("i").build()).build();
ValueExpr initValueExpr = ValueExpr.withValue(PrimitiveValue.builder().setValue("0").setType(TypeNode.INT).build());
GeneralForStatement innerSubresponseForStatement = GeneralForStatement.incrementWith(forIndexVarExpr, initValueExpr, subresponseCountVarExpr, innerSubresponseForExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
outerForBody.add(innerSubresponseForStatement);
}
TypeNode responseType = method.outputType();
Expr responseBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(responseType).setMethodName("newBuilder").build();
if (hasSubresponseField) {
Preconditions.checkNotNull(subresponseElementsVarExpr, String.format("subresponseElements variable should not be null for method %s", method.name()));
responseBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseBuilderExpr).setMethodName(String.format("addAll%s", JavaStyle.toUpperCamelCase(batchingSettings.subresponseFieldName()))).setArguments(subresponseElementsVarExpr).build();
}
responseBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseBuilderExpr).setMethodName("build").setReturnType(responseType).build();
VariableExpr responseVarExpr = VariableExpr.withVariable(Variable.builder().setType(responseType).setName("response").build());
outerForBody.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(responseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(responseBuilderExpr).build()));
outerForBody.add(ExprStatement.withExpr(MethodInvocationExpr.builder().setExprReferenceExpr(responderVarExpr).setMethodName("setResponse").setArguments(responseVarExpr).build()));
ForStatement outerForStatement = ForStatement.builder().setLocalVariableExpr(responderVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(batchVarExpr).setBody(outerForBody).build();
List<Statement> bodyStatements = new ArrayList<>();
if (hasSubresponseField) {
bodyStatements.add(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(batchMessageIndexVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build())).build()));
}
bodyStatements.add(outerForStatement);
return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName("splitResponse").setArguments(Arrays.asList(batchResponseVarExpr, batchVarExpr).stream().map(v -> v.toBuilder().setIsDecl(true).build()).collect(Collectors.toList())).setBody(bodyStatements).build();
}
use of com.google.api.generator.gapic.model.Field 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();
}
Aggregations