use of com.google.api.generator.engine.ast.Expr in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createBuilderCreatorMethods.
private static List<MethodDefinition> createBuilderCreatorMethods(ResourceName resourceName, List<List<String>> tokenHierarchies, TypeStore typeStore) {
List<MethodDefinition> javaMethods = new ArrayList<>();
String newMethodNameFormat = "new%s";
AnnotationNode betaAnnotation = AnnotationNode.builder().setType(FIXED_TYPESTORE.get("BetaApi")).setDescription("The per-pattern Builders are not stable yet and may be changed in the future.").build();
List<AnnotationNode> annotations = Arrays.asList(betaAnnotation);
// Variation example: newProjectLocationAutoscalingPolicyBuilder().
for (int i = 0; i < tokenHierarchies.size(); i++) {
// PubSub special-case handling.
if (tokenHierarchies.get(i).contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) {
continue;
}
final TypeNode returnType = getBuilderType(typeStore, tokenHierarchies, i);
final Expr returnExpr = NewObjectExpr.withType(returnType);
Function<String, MethodDefinition.Builder> methodDefStarterFn = methodName -> MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setIsStatic(true).setReturnType(returnType).setName(methodName).setReturnExpr(returnExpr);
String variantName = getBuilderTypeName(tokenHierarchies, i);
javaMethods.add(methodDefStarterFn.apply(String.format(newMethodNameFormat, variantName)).setAnnotations(i == 0 ? Collections.emptyList() : annotations).build());
if (i == 0 && tokenHierarchies.size() > 1) {
// Create another builder creator method, but with the per-variant name.
javaMethods.add(methodDefStarterFn.apply(String.format(newMethodNameFormat, getBuilderTypeName(tokenHierarchies.get(i)))).setAnnotations(annotations).build());
}
}
// TODO(miraleung, v2): It seems weird that we currently generate a toBuilder method only for
// the default class, and none for the Builder variants.
TypeNode toBuilderReturnType = getBuilderType(typeStore, tokenHierarchies, 0);
TypeNode thisClassType = typeStore.get(getThisClassName(resourceName));
javaMethods.add(MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setReturnType(toBuilderReturnType).setName("toBuilder").setReturnExpr(NewObjectExpr.builder().setType(toBuilderReturnType).setArguments(Arrays.asList(ValueExpr.withValue(ThisObjectValue.withType(thisClassType)))).build()).build());
return javaMethods;
}
use of com.google.api.generator.engine.ast.Expr in project gapic-generator-java by googleapis.
the class HttpJsonServiceStubClassComposer method createTypeRegistry.
@Override
protected List<Statement> createTypeRegistry(Service service) {
TypeNode typeRegistryType = FIXED_REST_TYPESTORE.get(TypeRegistry.class.getSimpleName());
VariableExpr typeRegistryVarExpr = TYPE_REGISTRY_VAR_EXPR.toBuilder().setIsDecl(true).setIsStatic(true).setScope(ScopeNode.PRIVATE).setIsFinal(true).build();
Map<String, TypeNode> anyTypes = new HashMap<>();
for (Method method : service.methods()) {
if (method.hasLro()) {
TypeNode anyType = method.lro().responseType();
anyTypes.put(anyType.reference().fullName(), anyType);
anyType = method.lro().metadataType();
anyTypes.put(anyType.reference().fullName(), anyType);
}
}
Expr typeRegistryBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(typeRegistryType).setMethodName("newBuilder").build();
for (TypeNode anyType : anyTypes.values()) {
typeRegistryBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(typeRegistryBuilderExpr).setMethodName("add").setArguments(MethodInvocationExpr.builder().setStaticReferenceType(anyType).setMethodName("getDescriptor").build()).build();
}
typeRegistryBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(typeRegistryBuilderExpr).setMethodName("build").setReturnType(typeRegistryType).build();
return Collections.singletonList(ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(typeRegistryVarExpr).setValueExpr(typeRegistryBuilderExpr).build()));
}
use of com.google.api.generator.engine.ast.Expr in project gapic-generator-java by googleapis.
the class ServiceClientCallableMethodSampleComposer method composeLroCallableMethod.
// Compose sample code for the method where it is CallableMethodKind.LRO.
public static Sample composeLroCallableMethod(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);
// Create OperationFuture variable expr with invoking client's LRO callable method.
// e.g. OperationFuture<Empty, WaitMetadata> future =
// echoClient.waitOperationCallable().futureCall(request);
TypeNode operationFutureType = TypeNode.withReference(ConcreteReference.builder().setClazz(OperationFuture.class).setGenerics(method.lro().responseType().reference(), method.lro().metadataType().reference()).build());
VariableExpr operationFutureVarExpr = VariableExpr.withVariable(Variable.builder().setName("future").setType(operationFutureType).build());
MethodInvocationExpr rpcMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(String.format("%sOperationCallable", JavaStyle.toLowerCamelCase(method.name()))).build();
rpcMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(rpcMethodInvocationExpr).setMethodName("futureCall").setArguments(requestVarExpr).setReturnType(operationFutureType).build();
bodyExprs.add(AssignmentExpr.builder().setVariableExpr(operationFutureVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(rpcMethodInvocationExpr).build());
List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
bodyExprs.clear();
// Add a line comment
bodyStatements.add(CommentStatement.withComment(LineComment.withComment("Do something.")));
// Assign response variable with invoking client's LRO method.
// e.g. if return void, future.get(); or,
// e.g. if return other type, WaitResponse response = future.get();
MethodInvocationExpr futureGetMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(operationFutureVarExpr).setMethodName("get").setReturnType(method.lro().responseType()).build();
boolean returnsVoid = method.lro().responseType().isProtoEmptyType();
if (returnsVoid) {
bodyExprs.add(futureGetMethodExpr);
} else {
VariableExpr responseVarExpr = VariableExpr.builder().setVariable(Variable.builder().setName("response").setType(method.lro().responseType()).build()).setIsDecl(true).build();
bodyExprs.add(AssignmentExpr.builder().setVariableExpr(responseVarExpr).setValueExpr(futureGetMethodExpr).build());
}
bodyStatements.addAll(bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()));
bodyExprs.clear();
RegionTag regionTag = RegionTag.builder().setServiceName(clientType.reference().name()).setRpcName(method.name()).setIsAsynchronous(true).setOverloadDisambiguation("LRO").build();
List<Statement> body = Arrays.asList(TryCatchStatement.builder().setTryResourceExpr(SampleComposerUtil.assignClientVariableWithCreateMethodExpr(clientVarExpr)).setTryBody(bodyStatements).setIsSampleCode(true).build());
return Sample.builder().setBody(body).setRegionTag(regionTag).build();
}
use of com.google.api.generator.engine.ast.Expr in project gapic-generator-java by googleapis.
the class ServiceClientCallableMethodSampleComposer method composeStreamServerSample.
private static Sample composeStreamServerSample(Method method, VariableExpr clientVarExpr, AssignmentExpr requestAssignmentExpr) {
List<Expr> bodyExprs = new ArrayList<>();
bodyExprs.add(requestAssignmentExpr);
// Create server stream variable expression, and assign it a value by invoking server stream
// method.
// e.g. ServerStream<EchoResponse> stream = echoClient.expandCallable().call(request)
TypeNode serverStreamType = TypeNode.withReference(ConcreteReference.builder().setClazz(ServerStream.class).setGenerics(method.outputType().reference()).build());
VariableExpr serverStreamVarExpr = VariableExpr.withVariable(Variable.builder().setName("stream").setType(serverStreamType).build());
MethodInvocationExpr clientStreamCallMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(JavaStyle.toLowerCamelCase(String.format("%sCallable", method.name()))).build();
clientStreamCallMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientStreamCallMethodInvocationExpr).setMethodName("call").setArguments(requestAssignmentExpr.variableExpr().toBuilder().setIsDecl(false).build()).setReturnType(serverStreamType).build();
AssignmentExpr streamAssignmentExpr = AssignmentExpr.builder().setVariableExpr(serverStreamVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(clientStreamCallMethodInvocationExpr).build();
bodyExprs.add(streamAssignmentExpr);
List<Statement> bodyStatements = bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
// For-loop on server stream variable expression.
// e.g. for (EchoResponse response : stream) {
// // Do something when a response is received.
// }
VariableExpr responseVarExpr = VariableExpr.builder().setVariable(Variable.builder().setName("response").setType(method.outputType()).build()).setIsDecl(true).build();
ForStatement forStatement = ForStatement.builder().setLocalVariableExpr(responseVarExpr).setCollectionExpr(serverStreamVarExpr).setBody(Arrays.asList(CommentStatement.withComment(LineComment.withComment("Do something when a response is received.")))).build();
bodyStatements.add(forStatement);
RegionTag regionTag = RegionTag.builder().setServiceName(clientVarExpr.variable().identifier().name()).setRpcName(method.name()).setIsAsynchronous(true).build();
return Sample.builder().setBody(bodyStatements).setRegionTag(regionTag).build();
}
use of com.google.api.generator.engine.ast.Expr in project gapic-generator-java by googleapis.
the class ServiceClientCallableMethodSampleComposer method composePagedCallableSample.
private static Sample composePagedCallableSample(Method method, VariableExpr clientVarExpr, VariableExpr requestVarExpr, Map<String, Message> messageTypes) {
// 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();
// Assign future variable by invoking paged callable method.
// e.g. ApiFuture<PagedExpandPagedResponse> future =
// echoClient.pagedExpandCallable().futureCall(request);
VariableExpr responseVarExpr = VariableExpr.withVariable(Variable.builder().setName("response").setType(method.outputType()).build());
MethodInvocationExpr pagedCallableMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientVarExpr).setMethodName(JavaStyle.toLowerCamelCase(String.format("%sCallable", method.name()))).build();
pagedCallableMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(pagedCallableMethodInvocationExpr).setMethodName("call").setArguments(requestVarExpr).setReturnType(method.outputType()).build();
AssignmentExpr responseAssignmentExpr = AssignmentExpr.builder().setVariableExpr(responseVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(pagedCallableMethodInvocationExpr).build();
List<Statement> whileBodyStatements = new ArrayList<>();
whileBodyStatements.add(ExprStatement.withExpr(responseAssignmentExpr));
// For-loop on repeated response elements.
// e.g. for (EchoResponse element : response.getResponsesList()) {
// // doThingsWith(element);
// }
VariableExpr repeatedResponseVarExpr = VariableExpr.withVariable(Variable.builder().setName("element").setType(repeatedResponseType).build());
MethodInvocationExpr getResponseListMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName("getResponsesList").build();
ForStatement responseForStatements = ForStatement.builder().setLocalVariableExpr(repeatedResponseVarExpr.toBuilder().setIsDecl(true).build()).setCollectionExpr(getResponseListMethodInvocationExpr).setBody(Arrays.asList(CommentStatement.withComment(LineComment.withComment("doThingsWith(element);")))).build();
whileBodyStatements.add(responseForStatements);
// Create nextPageToken variable expression and assign it with a value by invoking
// getNextPageToken method.
// e.g. String nextPageToken = response.getNextPageToken();
VariableExpr nextPageTokenVarExpr = VariableExpr.withVariable(Variable.builder().setName("nextPageToken").setType(TypeNode.STRING).build());
MethodInvocationExpr getNextPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(responseVarExpr).setMethodName("getNextPageToken").setReturnType(TypeNode.STRING).build();
AssignmentExpr nextPageTokenAssignmentExpr = AssignmentExpr.builder().setVariableExpr(nextPageTokenVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(getNextPageTokenMethodInvocationExpr).build();
whileBodyStatements.add(ExprStatement.withExpr(nextPageTokenAssignmentExpr));
// If nextPageToken variable expression is not null or empty, assign request variable with a
// value by invoking setPageToken method.
// if (!Strings.isNullOrEmpty(nextPageToken)) {
// request = request.toBuilder().setPageToken(nextPageToken).build();
// } else {
// break;
// }
Expr conditionExpr = UnaryOperationExpr.logicalNotWithExpr(MethodInvocationExpr.builder().setStaticReferenceType(TypeNode.withReference(ConcreteReference.withClazz(Strings.class))).setMethodName("isNullOrEmpty").setArguments(nextPageTokenVarExpr).setReturnType(TypeNode.BOOLEAN).build());
MethodInvocationExpr setPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(requestVarExpr).setMethodName("toBuilder").build();
setPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(setPageTokenMethodInvocationExpr).setMethodName("setPageToken").setArguments(nextPageTokenVarExpr).build();
setPageTokenMethodInvocationExpr = MethodInvocationExpr.builder().setExprReferenceExpr(setPageTokenMethodInvocationExpr).setMethodName("build").setReturnType(method.inputType()).build();
AssignmentExpr requestReAssignmentExpr = AssignmentExpr.builder().setVariableExpr(requestVarExpr).setValueExpr(setPageTokenMethodInvocationExpr).build();
IfStatement nextPageTokenIfStatement = IfStatement.builder().setConditionExpr(conditionExpr).setBody(Arrays.asList(ExprStatement.withExpr(requestReAssignmentExpr))).setElseBody(Arrays.asList(BreakStatement.create())).build();
whileBodyStatements.add(nextPageTokenIfStatement);
WhileStatement pagedWhileStatement = WhileStatement.builder().setConditionExpr(ValueExpr.withValue(PrimitiveValue.builder().setValue("true").setType(TypeNode.BOOLEAN).build())).setBody(whileBodyStatements).build();
RegionTag regionTag = RegionTag.builder().setServiceName(clientVarExpr.variable().identifier().name()).setRpcName(method.name()).setOverloadDisambiguation("Paged").setIsAsynchronous(true).build();
return Sample.builder().setBody(Arrays.asList(pagedWhileStatement)).setRegionTag(regionTag).build();
}
Aggregations