use of com.google.api.generator.engine.ast.Statement 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();
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class HttpJsonServiceStubClassComposer method createBodyFieldsExtractorClassInstance.
private Expr createBodyFieldsExtractorClassInstance(Method method, TypeNode extractorReturnType, Set<HttpBinding> httpBindingFieldNames, String serializerMethodName, boolean asteriskBody) {
List<Statement> bodyStatements = new ArrayList<>();
Expr returnExpr = null;
Expr serializerExpr = MethodInvocationExpr.builder().setMethodName("create").setStaticReferenceType(FIXED_REST_TYPESTORE.get(ProtoRestSerializer.class.getSimpleName())).build();
VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
Expr bodyRequestExpr = requestVarExpr;
String requestMethodPrefix = "get";
String bodyParamName = null;
if (asteriskBody) {
bodyRequestExpr = MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr).setMethodName("toBuilder").build();
// In case of `body: "*"` case we send the whole request message as a body, minus the fields
// in the path, therefore the "clear" prefix here.
requestMethodPrefix = "clear";
}
Expr prevExpr = bodyRequestExpr;
for (HttpBinding httpBindingFieldName : httpBindingFieldNames) {
// Handle foo.bar cases by descending into the subfields.
MethodInvocationExpr.Builder requestFieldMethodExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(prevExpr);
bodyParamName = JavaStyle.toLowerCamelCase(httpBindingFieldName.name());
String[] descendantFields = httpBindingFieldName.name().split("\\.");
if (asteriskBody && descendantFields.length > 1) {
// well-defined case, and it is generally safer to send more than less in such case.
continue;
}
for (int i = 0; i < descendantFields.length; i++) {
String currFieldName = descendantFields[i];
String bindingFieldMethodName = String.format("%s%s", requestMethodPrefix, JavaStyle.toUpperCamelCase(currFieldName));
requestFieldMethodExprBuilder = requestFieldMethodExprBuilder.setMethodName(bindingFieldMethodName);
if (i < descendantFields.length - 1) {
requestFieldMethodExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(requestFieldMethodExprBuilder.build());
}
}
prevExpr = requestFieldMethodExprBuilder.build();
}
if (httpBindingFieldNames.isEmpty() && !asteriskBody) {
returnExpr = ValueExpr.createNullExpr();
} else {
ImmutableList.Builder<Expr> paramsPutArgs = ImmutableList.builder();
if (asteriskBody) {
prevExpr = MethodInvocationExpr.builder().setExprReferenceExpr(prevExpr).setMethodName("build").build();
bodyParamName = "*";
}
paramsPutArgs.add(ValueExpr.withValue(StringObjectValue.withValue(bodyParamName)));
paramsPutArgs.add(prevExpr);
returnExpr = MethodInvocationExpr.builder().setExprReferenceExpr(serializerExpr).setMethodName(serializerMethodName).setArguments(paramsPutArgs.build()).setReturnType(extractorReturnType).build();
}
// (https://github.com/googleapis/gax-java/blob/12b18ee255d3fabe13bb3969df40753b29f830d5/gax-httpjson/src/main/java/com/google/api/gax/httpjson/FieldsExtractor.java).
return LambdaExpr.builder().setArguments(requestVarExpr.toBuilder().setIsDecl(true).build()).setBody(bodyStatements).setReturnExpr(returnExpr).build();
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class HttpJsonServiceStubClassComposer method createFieldsExtractorClassInstance.
private Expr createFieldsExtractorClassInstance(Method method, TypeNode extractorReturnType, Set<HttpBinding> httpBindingFieldNames, String serializerMethodName) {
List<Statement> bodyStatements = new ArrayList<>();
VariableExpr fieldsVarExpr = VariableExpr.withVariable(Variable.builder().setName("fields").setType(extractorReturnType).build());
Expr fieldsAssignExpr = AssignmentExpr.builder().setVariableExpr(fieldsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(FIXED_REST_TYPESTORE.get(HashMap.class.getSimpleName())).setIsGeneric(true).build()).build();
bodyStatements.add(ExprStatement.withExpr(fieldsAssignExpr));
TypeNode serializerVarType = TypeNode.withReference(ConcreteReference.builder().setClazz(ProtoRestSerializer.class).setGenerics(method.inputType().reference()).build());
VariableExpr serializerVarExpr = VariableExpr.withVariable(Variable.builder().setName("serializer").setType(serializerVarType).build());
Expr serializerAssignExpr = AssignmentExpr.builder().setVariableExpr(serializerVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_REST_TYPESTORE.get(ProtoRestSerializer.class.getSimpleName())).setMethodName("create").setReturnType(serializerVarType).build()).build();
bodyStatements.add(ExprStatement.withExpr(serializerAssignExpr));
VariableExpr requestVarExpr = VariableExpr.withVariable(Variable.builder().setType(method.inputType()).setName("request").build());
for (HttpBinding httpBindingFieldName : httpBindingFieldNames) {
// Handle foo.bar cases by descending into the subfields.
MethodInvocationExpr.Builder requestFieldGetterExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr);
MethodInvocationExpr.Builder requestFieldHasExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr);
String[] descendantFields = httpBindingFieldName.name().split("\\.");
for (int i = 0; i < descendantFields.length; i++) {
String currFieldName = descendantFields[i];
String bindingFieldMethodName = String.format("get%s", JavaStyle.toUpperCamelCase(currFieldName));
requestFieldGetterExprBuilder = requestFieldGetterExprBuilder.setMethodName(bindingFieldMethodName);
String bindingFieldHasMethodName = (i < descendantFields.length - 1) ? bindingFieldMethodName : String.format("has%s", JavaStyle.toUpperCamelCase(currFieldName));
requestFieldHasExprBuilder = requestFieldHasExprBuilder.setMethodName(bindingFieldHasMethodName).setReturnType(TypeNode.BOOLEAN);
if (i < descendantFields.length - 1) {
requestFieldGetterExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(requestFieldGetterExprBuilder.build());
requestFieldHasExprBuilder = MethodInvocationExpr.builder().setExprReferenceExpr(requestFieldHasExprBuilder.build());
}
}
MethodInvocationExpr requestBuilderExpr = requestFieldGetterExprBuilder.build();
MethodInvocationExpr requestHasExpr = requestFieldHasExprBuilder.build();
ImmutableList.Builder<Expr> paramsPutArgs = ImmutableList.builder();
paramsPutArgs.add(fieldsVarExpr);
paramsPutArgs.add(ValueExpr.withValue(StringObjectValue.withValue(JavaStyle.toLowerCamelCase(httpBindingFieldName.name()))));
paramsPutArgs.add(requestBuilderExpr);
Expr paramsPutExpr = MethodInvocationExpr.builder().setExprReferenceExpr(serializerVarExpr).setMethodName(serializerMethodName).setArguments(paramsPutArgs.build()).setReturnType(extractorReturnType).build();
if (httpBindingFieldName.isOptional()) {
bodyStatements.add(IfStatement.builder().setConditionExpr(requestHasExpr).setBody(Arrays.asList(ExprStatement.withExpr(paramsPutExpr))).build());
} else {
bodyStatements.add(ExprStatement.withExpr(paramsPutExpr));
}
}
// (https://github.com/googleapis/gax-java/blob/12b18ee255d3fabe13bb3969df40753b29f830d5/gax-httpjson/src/main/java/com/google/api/gax/httpjson/FieldsExtractor.java).
return LambdaExpr.builder().setArguments(requestVarExpr.toBuilder().setIsDecl(true).build()).setBody(bodyStatements).setReturnExpr(fieldsVarExpr).build();
}
use of com.google.api.generator.engine.ast.Statement 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());
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class ServiceClientTestClassComposer method constructRpcTestCheckerLogic.
@Override
protected List<Statement> constructRpcTestCheckerLogic(Method method, Service service, boolean isRequestArg, Map<String, VariableExpr> classMemberVarExprs, VariableExpr requestVarExpr, Message requestMessage, List<VariableExpr> argExprs) {
VariableExpr actualRequestsVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(TypeNode.STRING.reference())).build())).setName("actualRequests").build());
List<Expr> methodExprs = new ArrayList<>();
methodExprs.add(AssignmentExpr.builder().setVariableExpr(actualRequestsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(classMemberVarExprs.get(getMockServiceVarName(service))).setMethodName("getRequestPaths").setReturnType(actualRequestsVarExpr.type()).build()).build());
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(actualRequestsVarExpr).setMethodName("size").build()).build());
List<Statement> methodStatements = new ArrayList<>();
methodStatements.addAll(methodExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
methodExprs.clear();
methodStatements.add(EMPTY_LINE_STATEMENT);
VariableExpr apiClientHeaderKeyVarExpr = VariableExpr.withVariable(Variable.builder().setType(TypeNode.STRING).setName("apiClientHeaderKey").build());
AssignmentExpr apiClientHeaderKeyAssignExpr = AssignmentExpr.builder().setVariableExpr(apiClientHeaderKeyVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setMethodName("next").setReturnType(apiClientHeaderKeyVarExpr.type()).setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("iterator").setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("get").setArguments(MethodInvocationExpr.builder().setMethodName("getDefaultApiClientHeaderKey").setStaticReferenceType(FIXED_REST_TYPESTORE.get("ApiClientHeaderProvider")).build()).setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("getRequestHeaders").setExprReferenceExpr(classMemberVarExprs.get(getMockServiceVarName(service))).build()).build()).build()).build()).build();
methodExprs.add(apiClientHeaderKeyAssignExpr);
methodExprs.add(MethodInvocationExpr.builder().setMethodName("assertTrue").setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setArguments(MethodInvocationExpr.builder().setMethodName("matches").setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("matcher").setArguments(apiClientHeaderKeyVarExpr).setExprReferenceExpr(MethodInvocationExpr.builder().setMethodName("getDefaultApiClientHeaderPattern").setStaticReferenceType(FIXED_REST_TYPESTORE.get("GaxHttpJsonProperties")).build()).build()).build()).build());
methodStatements.addAll(methodExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
methodExprs.clear();
return methodStatements;
}
Aggregations