use of com.google.api.generator.engine.ast.AssignmentExpr 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.AssignmentExpr 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.AssignmentExpr 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;
}
use of com.google.api.generator.engine.ast.AssignmentExpr in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createParseListMethod.
private static MethodDefinition createParseListMethod(TypeNode thisClassType) {
TypeNode listStringType = TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(ConcreteReference.withClazz(String.class))).build());
TypeNode returnType = TypeNode.withReference(ConcreteReference.builder().setClazz(List.class).setGenerics(Arrays.asList(thisClassType.reference())).build());
VariableExpr formattedStringsVarExpr = VariableExpr.withVariable(Variable.builder().setName("formattedStrings").setType(listStringType).build());
VariableExpr listVarExpr = VariableExpr.withVariable(Variable.builder().setName("list").setType(returnType).build());
AssignmentExpr listAssignExpr = AssignmentExpr.builder().setVariableExpr(listVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(NewObjectExpr.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(ArrayList.class).build())).setIsGeneric(true).setArguments(Arrays.asList(MethodInvocationExpr.builder().setExprReferenceExpr(formattedStringsVarExpr).setMethodName("size").build())).build()).build();
VariableExpr singleStrVarExpr = VariableExpr.withVariable(Variable.builder().setName("formattedString").setType(TypeNode.STRING).build());
ForStatement forStatement = ForStatement.builder().setLocalVariableExpr(singleStrVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(formattedStringsVarExpr).setBody(Arrays.asList(ExprStatement.withExpr(MethodInvocationExpr.builder().setExprReferenceExpr(listVarExpr).setMethodName("add").setArguments(Arrays.asList(MethodInvocationExpr.builder().setMethodName("parse").setArguments(Arrays.asList(singleStrVarExpr)).build())).build()))).build();
return MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setIsStatic(true).setReturnType(returnType).setName("parseList").setArguments(Arrays.asList(formattedStringsVarExpr.toBuilder().setIsDecl(true).build())).setBody(Arrays.asList(ExprStatement.withExpr(listAssignExpr), forStatement)).setReturnExpr(listVarExpr).build();
}
use of com.google.api.generator.engine.ast.AssignmentExpr in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createConstructorMethods.
private static List<MethodDefinition> createConstructorMethods(ResourceName resourceName, List<VariableExpr> templateFinalVarExprs, Map<String, VariableExpr> patternTokenVarExprs, List<List<String>> tokenHierarchies, TypeStore typeStore) {
String thisClassName = getThisClassName(resourceName);
TypeNode thisClassType = typeStore.get(thisClassName);
boolean hasVariants = tokenHierarchies.size() > 1;
List<MethodDefinition> javaMethods = new ArrayList<>();
final ValueExpr nullExpr = ValueExpr.createNullExpr();
Function<String, AssignmentExpr> assignTokenToNullExpr = t -> AssignmentExpr.builder().setVariableExpr(patternTokenVarExprs.get(t)).setValueExpr(nullExpr).build();
// Special-cased PubSub handling.
List<List<String>> processedTokenHierarchies = tokenHierarchies.stream().filter(tokens -> !tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)).collect(Collectors.toList());
boolean hasDeletedTopicPattern = tokenHierarchies.size() > processedTokenHierarchies.size();
// First deprecated constructor.
javaMethods.add(MethodDefinition.constructorBuilder().setAnnotations(Arrays.asList(AnnotationNode.withType(TypeNode.withReference(ConcreteReference.withClazz(Deprecated.class))))).setScope(ScopeNode.PROTECTED).setReturnType(thisClassType).setBody(getTokenSet(processedTokenHierarchies).stream().map(t -> ExprStatement.withExpr(assignTokenToNullExpr.apply(t))).collect(Collectors.toList())).build());
for (int i = 0; i < processedTokenHierarchies.size(); i++) {
List<String> tokens = processedTokenHierarchies.get(i);
List<Expr> bodyExprs = new ArrayList<>();
TypeNode argType = getBuilderType(typeStore, processedTokenHierarchies, i);
VariableExpr builderArgExpr = VariableExpr.withVariable(Variable.builder().setName("builder").setType(argType).build());
for (String token : tokens) {
MethodInvocationExpr checkNotNullExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Preconditions")).setMethodName("checkNotNull").setReturnType(TypeNode.STRING).setArguments(Arrays.asList(MethodInvocationExpr.builder().setExprReferenceExpr(builderArgExpr).setMethodName(String.format("get%s", JavaStyle.toUpperCamelCase(token))).build())).build();
bodyExprs.add(AssignmentExpr.builder().setVariableExpr(patternTokenVarExprs.get(token)).setValueExpr(checkNotNullExpr).build());
}
// Initialize the rest to null.
for (String token : getTokenSet(processedTokenHierarchies)) {
if (tokens.contains(token)) {
continue;
}
bodyExprs.add(assignTokenToNullExpr.apply(token));
}
if (hasVariants) {
AssignmentExpr pathTemplateAssignExpr = AssignmentExpr.builder().setVariableExpr(FIXED_CLASS_VARS.get("pathTemplate")).setValueExpr(templateFinalVarExprs.get(i)).build();
bodyExprs.add(pathTemplateAssignExpr);
}
// Private constructor.
javaMethods.add(MethodDefinition.constructorBuilder().setScope(ScopeNode.PRIVATE).setReturnType(thisClassType).setArguments(Arrays.asList(builderArgExpr.toBuilder().setIsDecl(true).build())).setBody(bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build());
}
if (hasDeletedTopicPattern) {
Expr thisExpr = ValueExpr.withValue(ThisObjectValue.withType(thisClassType));
// PubSub special-case handling for the _deleted-topic_ pattern - add an extra constructor.
// private TopicName(String fixedValue) {
// this.fixedValue = fixedValue;
// fieldValuesMap = ImmutableMap.of("", fixedValue);
// }
VariableExpr fixedValueVarExpr = VariableExpr.withVariable(Variable.builder().setName("fixedValue").setType(TypeNode.STRING).build());
List<Expr> specialCtorBodyExprs = new ArrayList<>();
specialCtorBodyExprs.add(AssignmentExpr.builder().setVariableExpr(VariableExpr.builder().setExprReferenceExpr(thisExpr).setVariable(fixedValueVarExpr.variable()).build()).setValueExpr(fixedValueVarExpr).build());
specialCtorBodyExprs.add(AssignmentExpr.builder().setVariableExpr(FIXED_CLASS_VARS.get("fieldValuesMap")).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")).setMethodName("of").setArguments(ValueExpr.withValue(StringObjectValue.withValue("")), fixedValueVarExpr).setReturnType(FIXED_TYPESTORE.get("ImmutableMap")).build()).build());
specialCtorBodyExprs.addAll(getTokenSet(processedTokenHierarchies).stream().map(t -> assignTokenToNullExpr.apply(t)).collect(Collectors.toList()));
javaMethods.add(MethodDefinition.constructorBuilder().setScope(ScopeNode.PRIVATE).setReturnType(thisClassType).setArguments(Arrays.asList(fixedValueVarExpr.toBuilder().setIsDecl(true).build())).setBody(specialCtorBodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build());
}
return javaMethods;
}
Aggregations