use of com.google.api.generator.engine.ast.MethodInvocationExpr 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.MethodInvocationExpr in project gapic-generator-java by googleapis.
the class ServiceStubSettingsClassComposer method createDefaultCredentialsProviderBuilderMethod.
@Override
protected MethodDefinition createDefaultCredentialsProviderBuilderMethod() {
TypeNode returnType = TypeNode.withReference(ConcreteReference.withClazz(GoogleCredentialsProvider.Builder.class));
MethodInvocationExpr credsProviderBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("GoogleCredentialsProvider")).setMethodName("newBuilder").build();
credsProviderBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(credsProviderBuilderExpr).setMethodName("setScopesToApply").setArguments(DEFAULT_SERVICE_SCOPES_VAR_EXPR).setReturnType(returnType).build();
// This section is specific to GAPIC clients. It sets UseJwtAccessWithScope value to true to
// enable self signed JWT feature.
credsProviderBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(credsProviderBuilderExpr).setMethodName("setUseJwtAccessWithScope").setArguments(ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.BOOLEAN).setValue("true").build())).setReturnType(returnType).build();
return MethodDefinition.builder().setHeaderCommentStatements(SettingsCommentComposer.DEFAULT_CREDENTIALS_PROVIDER_BUILDER_METHOD_COMMENT).setScope(ScopeNode.PUBLIC).setIsStatic(true).setReturnType(returnType).setName("defaultCredentialsProviderBuilder").setReturnExpr(credsProviderBuilderExpr).build();
}
use of com.google.api.generator.engine.ast.MethodInvocationExpr 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;
}
use of com.google.api.generator.engine.ast.MethodInvocationExpr in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createNestedBuilderClass.
private static ClassDefinition createNestedBuilderClass(TypeNode outerClassType, List<String> tokens, VariableExpr templateFinalVarExpr, String resourceNamePattern, TypeStore typeStore, boolean hasVariants, boolean isDefaultClass) {
String className = isDefaultClass ? "Builder" : getBuilderTypeName(tokens);
// Class member declarations.
List<VariableExpr> classMemberVarExprs = tokens.stream().map(t -> VariableExpr.withVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(t)).setType(TypeNode.STRING).build())).collect(Collectors.toList());
List<Statement> classMemberDecls = classMemberVarExprs.stream().map(v -> ExprStatement.withExpr(v.toBuilder().setIsDecl(true).setScope(ScopeNode.PRIVATE).build())).collect(Collectors.toList());
// Constructor.
List<MethodDefinition> nestedClassMethods = new ArrayList<>();
TypeNode thisClassType = typeStore.get(className);
MethodDefinition ctor = MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(thisClassType).build();
nestedClassMethods.add(ctor);
// Getters and setters.
List<MethodDefinition> getterMethods = new ArrayList<>();
List<MethodDefinition> setterMethods = new ArrayList<>();
ValueExpr thisExpr = ValueExpr.withValue(ThisObjectValue.withType(thisClassType));
for (int i = 0; i < tokens.size(); i++) {
String token = tokens.get(i);
String upperCamelTokenName = JavaStyle.toUpperCamelCase(token);
VariableExpr currClassTokenVarExpr = classMemberVarExprs.get(i);
// Getter.
MethodDefinition getterMethod = MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.STRING).setName(String.format("get%s", upperCamelTokenName)).setReturnExpr(currClassTokenVarExpr).build();
getterMethods.add(getterMethod);
// Setter.
VariableExpr tokenArgVarExpr = currClassTokenVarExpr;
AssignmentExpr fieldAssignExpr = AssignmentExpr.builder().setVariableExpr(currClassTokenVarExpr.toBuilder().setExprReferenceExpr(thisExpr).build()).setValueExpr(tokenArgVarExpr).build();
MethodDefinition setterMethod = MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setReturnType(thisClassType).setName(String.format("set%s", upperCamelTokenName)).setArguments(classMemberVarExprs.get(i).toBuilder().setIsDecl(true).build()).setBody(Arrays.asList(ExprStatement.withExpr(fieldAssignExpr))).setReturnExpr(thisExpr).build();
setterMethods.add(setterMethod);
}
nestedClassMethods.addAll(getterMethods);
nestedClassMethods.addAll(setterMethods);
// Private builder constructor method.
if (isDefaultClass) {
VariableExpr outerClassVarExpr = VariableExpr.withVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(outerClassType.reference().name())).setType(outerClassType).build());
List<Expr> builderCtorBodyExprs = new ArrayList<>();
if (hasVariants) {
// TODO(miraleung): Use eq operator instead.
MethodInvocationExpr equalsCheckExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Objects")).setMethodName("equals").setArguments(FIXED_CLASS_VARS.get("pathTemplate").toBuilder().setExprReferenceExpr(outerClassVarExpr).build(), templateFinalVarExpr).build();
builderCtorBodyExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Preconditions")).setMethodName("checkArgument").setArguments(equalsCheckExpr, ValueExpr.withValue(StringObjectValue.withValue(String.format("toBuilder is only supported when %s has the pattern of %s", outerClassType.reference().name(), resourceNamePattern)))).build());
}
for (VariableExpr memberVarExpr : classMemberVarExprs) {
VariableExpr currClassTokenVarExpr = memberVarExpr.toBuilder().setExprReferenceExpr(thisExpr).build();
builderCtorBodyExprs.add(AssignmentExpr.builder().setVariableExpr(currClassTokenVarExpr).setValueExpr(currClassTokenVarExpr.toBuilder().setExprReferenceExpr(outerClassVarExpr).build()).build());
}
MethodDefinition fromOuterTypeCtor = MethodDefinition.constructorBuilder().setScope(ScopeNode.PRIVATE).setReturnType(thisClassType).setArguments(outerClassVarExpr.toBuilder().setIsDecl(true).build()).setBody(builderCtorBodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build();
nestedClassMethods.add(fromOuterTypeCtor);
}
// Last build() method.
MethodDefinition buildMethod = MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setReturnType(outerClassType).setName("build").setReturnExpr(NewObjectExpr.builder().setType(outerClassType).setArguments(thisExpr).build()).build();
nestedClassMethods.add(buildMethod);
// Return the class.
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> classAnnotations = isDefaultClass ? Collections.emptyList() : Arrays.asList(betaAnnotation);
return ClassDefinition.builder().setHeaderCommentStatements(CommentStatement.withComment(JavaDocComment.withComment(String.format(BUILDER_CLASS_HEADER_PATTERN, resourceNamePattern)))).setAnnotations(classAnnotations).setIsNested(true).setScope(ScopeNode.PUBLIC).setIsStatic(true).setName(className).setStatements(classMemberDecls).setMethods(nestedClassMethods).build();
}
use of com.google.api.generator.engine.ast.MethodInvocationExpr in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createToStringMethod.
private static MethodDefinition createToStringMethod(List<VariableExpr> templateFinalVarExprs, Map<String, VariableExpr> patternTokenVarExprs, List<List<String>> tokenHierarchies) {
boolean hasVariants = tokenHierarchies.size() > 1;
if (!hasVariants) {
List<Expr> instantiateArgExprs = new ArrayList<>();
List<String> tokens = getTokenSet(tokenHierarchies).stream().collect(Collectors.toList());
for (String token : tokens) {
Preconditions.checkNotNull(patternTokenVarExprs.get(token), String.format("No expression found for token %s amongst values %s", token, patternTokenVarExprs.toString()));
instantiateArgExprs.add(ValueExpr.withValue(StringObjectValue.withValue(token)));
instantiateArgExprs.add(patternTokenVarExprs.get(token));
}
MethodInvocationExpr returnInstantiateExpr = MethodInvocationExpr.builder().setExprReferenceExpr(templateFinalVarExprs.get(0)).setMethodName("instantiate").setArguments(instantiateArgExprs).setReturnType(TypeNode.STRING).build();
return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.STRING).setName("toString").setReturnExpr(returnInstantiateExpr).build();
}
VariableExpr fixedValueVarExpr = FIXED_CLASS_VARS.get("fixedValue");
// Code: return fixedValue != null ? fixedValue : pathTemplate.instantiate(getFieldValuesMap())
Expr fixedValueNullCheck = RelationalOperationExpr.notEqualToWithExprs(fixedValueVarExpr, ValueExpr.createNullExpr());
MethodInvocationExpr instantiateExpr = MethodInvocationExpr.builder().setExprReferenceExpr(FIXED_CLASS_VARS.get("pathTemplate")).setMethodName("instantiate").setArguments(MethodInvocationExpr.builder().setMethodName("getFieldValuesMap").build()).setReturnType(TypeNode.STRING).build();
TernaryExpr returnExpr = TernaryExpr.builder().setConditionExpr(fixedValueNullCheck).setElseExpr(instantiateExpr).setThenExpr(fixedValueVarExpr).build();
return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.STRING).setName("toString").setReturnExpr(returnExpr).build();
}
Aggregations