use of com.google.api.generator.engine.ast.MethodDefinition 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.MethodDefinition 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.MethodDefinition in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createHashCodeMethod.
private static MethodDefinition createHashCodeMethod(List<List<String>> tokenHierarchies) {
List<Statement> assignmentBody = new ArrayList<>();
// code: int h = 1;
Variable hVar = Variable.builder().setType(TypeNode.INT).setName("h").build();
VariableExpr hVarExpr = VariableExpr.builder().setVariable(hVar).build();
ValueExpr hValueExpr = ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("1").build());
AssignmentExpr hAssignmentExpr = AssignmentExpr.builder().setVariableExpr(hVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(hValueExpr).build();
assignmentBody.add(ExprStatement.withExpr(hAssignmentExpr));
// code: h *= 1000003;
// code: h ^= Objects.hashCode(...);
ValueExpr numValueExpr = ValueExpr.withValue(PrimitiveValue.builder().setType(TypeNode.INT).setValue("1000003").build());
AssignmentOperationExpr multiplyAssignmentOpExpr = AssignmentOperationExpr.multiplyAssignmentWithExprs(hVarExpr, numValueExpr);
// PubSub special-case handling - exclude _deleted-topic_.
List<List<String>> processedTokenHierarchies = tokenHierarchies.stream().filter(ts -> !ts.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)).collect(Collectors.toList());
// If it has variants, add the multiply and xor assignment operation exprs for fixedValue.
boolean hasVariants = processedTokenHierarchies.size() > 1;
if (hasVariants) {
VariableExpr fixedValueVarExpr = FIXED_CLASS_VARS.get("fixedValue");
assignmentBody.add(ExprStatement.withExpr(multiplyAssignmentOpExpr));
assignmentBody.add(ExprStatement.withExpr(AssignmentOperationExpr.xorAssignmentWithExprs(hVarExpr, createObjectsHashCodeForVarMethod(fixedValueVarExpr))));
}
// Add the multiply and xor assignment operation exprs for tokens.
Set<String> tokenSet = getTokenSet(processedTokenHierarchies);
tokenSet.stream().forEach(token -> {
VariableExpr tokenVarExpr = VariableExpr.withVariable(Variable.builder().setName(JavaStyle.toLowerCamelCase(token)).setType(TypeNode.STRING).build());
assignmentBody.add(ExprStatement.withExpr(multiplyAssignmentOpExpr));
assignmentBody.add(ExprStatement.withExpr(AssignmentOperationExpr.xorAssignmentWithExprs(hVarExpr, createObjectsHashCodeForVarMethod(tokenVarExpr))));
});
return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.INT).setName("hashCode").setBody(assignmentBody).setReturnExpr(hVarExpr).build();
}
use of com.google.api.generator.engine.ast.MethodDefinition in project gapic-generator-java by googleapis.
the class ServiceClientTestClassComposer method createStartStaticServerMethod.
@Override
protected MethodDefinition createStartStaticServerMethod(Service service, GapicContext context, Map<String, VariableExpr> classMemberVarExprs, TypeStore typeStore, String newBuilderMethod) {
VariableExpr serviceHelperVarExpr = classMemberVarExprs.get(SERVICE_HELPER_VAR_NAME);
Function<Service, VariableExpr> serviceToVarExprFn = s -> classMemberVarExprs.get(getMockServiceVarName(s));
Function<Service, Expr> serviceToVarInitExprFn = s -> {
VariableExpr mockServiceVarExpr = serviceToVarExprFn.apply(s);
return AssignmentExpr.builder().setVariableExpr(mockServiceVarExpr).setValueExpr(NewObjectExpr.builder().setType(mockServiceVarExpr.type()).build()).build();
};
List<Expr> varInitExprs = new ArrayList<>();
List<Expr> mockServiceVarExprs = new ArrayList<>();
varInitExprs.add(serviceToVarInitExprFn.apply(service));
mockServiceVarExprs.add(serviceToVarExprFn.apply(service));
// Context: https://github.com/googleapis/gapic-generator-java/pull/750
for (Service mixinService : context.mixinServices().stream().sorted((s1, s2) -> s2.name().compareTo(s1.name())).collect(Collectors.toList())) {
varInitExprs.add(serviceToVarInitExprFn.apply(mixinService));
mockServiceVarExprs.add(serviceToVarExprFn.apply(mixinService));
}
MethodInvocationExpr firstArg = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("UUID")).setMethodName("randomUUID").build();
firstArg = MethodInvocationExpr.builder().setExprReferenceExpr(firstArg).setMethodName("toString").build();
MethodInvocationExpr secondArg = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Arrays")).setGenerics(Arrays.asList(FIXED_GRPC_TYPESTORE.get("MockGrpcService").reference())).setMethodName("asList").setArguments(mockServiceVarExprs).build();
Expr initServiceHelperExpr = AssignmentExpr.builder().setVariableExpr(serviceHelperVarExpr).setValueExpr(NewObjectExpr.builder().setType(serviceHelperVarExpr.type()).setArguments(Arrays.asList(firstArg, secondArg)).build()).build();
Expr startServiceHelperExpr = MethodInvocationExpr.builder().setExprReferenceExpr(serviceHelperVarExpr).setMethodName("start").build();
varInitExprs.add(initServiceHelperExpr);
varInitExprs.add(startServiceHelperExpr);
return MethodDefinition.builder().setAnnotations(Arrays.asList(AnnotationNode.withType(FIXED_TYPESTORE.get("BeforeClass")))).setScope(ScopeNode.PUBLIC).setIsStatic(true).setReturnType(TypeNode.VOID).setName("startStaticServer").setBody(varInitExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build();
}
use of com.google.api.generator.engine.ast.MethodDefinition in project gapic-generator-java by googleapis.
the class JavaWriterVisitorTest method writeMethodDefinition_basic.
@Test
public void writeMethodDefinition_basic() {
MethodDefinition methodDefinition = MethodDefinition.builder().setName("close").setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setBody(Arrays.asList(ExprStatement.withExpr(createAssignmentExpr("x", "3", TypeNode.INT)))).build();
methodDefinition.accept(writerVisitor);
assertEquals(LineFormatter.lines("public void close() {\n", "int x = 3;\n", "}\n\n"), writerVisitor.write());
}
Aggregations