use of com.google.api.generator.engine.ast.Statement 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.Statement 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.Statement in project gapic-generator-java by googleapis.
the class MockServiceImplClassComposer method createOnNextJavaMethod.
private static MethodDefinition createOnNextJavaMethod(Method protoMethod, VariableExpr responseObserverVarExpr, VariableExpr localResponseVarExpr) {
VariableExpr valueVarExpr = VariableExpr.withVariable(Variable.builder().setName("value").setType(protoMethod.inputType()).build());
TypeNode objectType = TypeNode.withReference(javaObjectReference);
Statement addValueToRequestsStatement = ExprStatement.withExpr(MethodInvocationExpr.builder().setMethodName("add").setArguments(Arrays.asList(valueVarExpr)).setExprReferenceExpr(requestsVarExpr).build());
Statement removeObjectStatement = ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(localResponseVarExpr.toBuilder().setIsDecl(true).setIsFinal(true).build()).setValueExpr(MethodInvocationExpr.builder().setMethodName("remove").setExprReferenceExpr(responsesVarExpr).setReturnType(objectType).build()).build());
Statement handleObjectStatement = createHandleObjectStatement(protoMethod, null, responseObserverVarExpr, localResponseVarExpr);
return MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName("onNext").setArguments(Arrays.asList(valueVarExpr.toBuilder().setIsDecl(true).build())).setBody(Arrays.asList(addValueToRequestsStatement, removeObjectStatement, handleObjectStatement)).build();
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class ServiceClientTestClassComposer method createRpcLroExceptionTestCatchBody.
@Override
protected List<Statement> createRpcLroExceptionTestCatchBody(VariableExpr exceptionExpr, boolean isStreaming) {
List<Expr> catchBodyExprs = new ArrayList<>();
Expr testExpectedValueExpr = VariableExpr.builder().setVariable(Variable.builder().setType(TypeNode.CLASS_OBJECT).setName("class").build()).setStaticReferenceType(FIXED_TYPESTORE.get("InvalidArgumentException")).build();
Expr getCauseExpr = MethodInvocationExpr.builder().setExprReferenceExpr(exceptionExpr).setMethodName("getCause").setReturnType(TypeNode.withReference(ConcreteReference.withClazz(Throwable.class))).build();
Expr testActualValueExpr = MethodInvocationExpr.builder().setExprReferenceExpr(getCauseExpr).setMethodName("getClass").build();
if (isStreaming) {
InstanceofExpr checkInstanceExpr = InstanceofExpr.builder().setExpr(getCauseExpr).setCheckType(FIXED_TYPESTORE.get("InvalidArgumentException")).build();
catchBodyExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertTrue").setArguments(checkInstanceExpr).build());
} else {
// Constructs `Assert.assertEquals(InvalidArgumentException.class, e.getCaus().getClass());`.
catchBodyExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(testExpectedValueExpr, testActualValueExpr).build());
}
// Construct the apiException variable.
VariableExpr apiExceptionVarExpr = VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("InvalidArgumentException")).setName("apiException").build());
Expr castedCauseExpr = CastExpr.builder().setType(FIXED_TYPESTORE.get("InvalidArgumentException")).setExpr(getCauseExpr).build();
catchBodyExprs.add(AssignmentExpr.builder().setVariableExpr(apiExceptionVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(castedCauseExpr).build());
// Construct the last assert statement.
testExpectedValueExpr = EnumRefExpr.builder().setType(TypeNode.withReference(ConcreteReference.builder().setClazz(StatusCode.Code.class).setIsStaticImport(false).build())).setName("INVALID_ARGUMENT").build();
testActualValueExpr = MethodInvocationExpr.builder().setExprReferenceExpr(apiExceptionVarExpr).setMethodName("getStatusCode").build();
testActualValueExpr = MethodInvocationExpr.builder().setExprReferenceExpr(testActualValueExpr).setMethodName("getCode").build();
catchBodyExprs.add(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("Assert")).setMethodName("assertEquals").setArguments(testExpectedValueExpr, testActualValueExpr).build());
return catchBodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList());
}
use of com.google.api.generator.engine.ast.Statement in project gapic-generator-java by googleapis.
the class GrpcServiceStubClassComposer method createRequestParamsExtractorBodyForRoutingHeaders.
private void createRequestParamsExtractorBodyForRoutingHeaders(Method method, VariableExpr requestVarExpr, List<Statement> classStatements, List<Statement> bodyStatements, MethodInvocationExpr.Builder returnExprBuilder) {
TypeNode routingHeadersBuilderType = TypeNode.withReference(ConcreteReference.builder().setClazz(RequestParamsBuilder.class).build());
VariableExpr routingHeadersBuilderVarExpr = VariableExpr.builder().setVariable(Variable.builder().setName("builder").setType(routingHeadersBuilderType).build()).setIsDecl(true).build();
MethodInvocationExpr routingHeaderBuilderInvokeExpr = MethodInvocationExpr.builder().setStaticReferenceType(routingHeadersBuilderType).setMethodName("create").setReturnType(routingHeadersBuilderType).build();
Expr routingHeadersBuilderInitExpr = AssignmentExpr.builder().setVariableExpr(routingHeadersBuilderVarExpr).setValueExpr(routingHeaderBuilderInvokeExpr).build();
bodyStatements.add(ExprStatement.withExpr(routingHeadersBuilderInitExpr));
List<RoutingHeaderParam> routingHeaderParams = method.routingHeaderRule().routingHeaderParams();
VariableExpr routingHeadersBuilderVarNonDeclExpr = VariableExpr.builder().setVariable(Variable.builder().setName("builder").setType(routingHeadersBuilderType).build()).build();
for (int i = 0; i < routingHeaderParams.size(); i++) {
RoutingHeaderParam routingHeaderParam = routingHeaderParams.get(i);
MethodInvocationExpr requestFieldGetterExpr = createRequestFieldGetterExpr(requestVarExpr, routingHeaderParam.fieldName());
Expr routingHeaderKeyExpr = ValueExpr.withValue(StringObjectValue.withValue(routingHeaderParam.key()));
String pathTemplateName = String.format("%s_%s_PATH_TEMPLATE", JavaStyle.toUpperSnakeCase(method.name()), i);
TypeNode pathTemplateType = TypeNode.withReference(ConcreteReference.withClazz(PathTemplate.class));
Variable pathTemplateVar = Variable.builder().setType(pathTemplateType).setName(pathTemplateName).build();
Expr routingHeaderPatternExpr = VariableExpr.withVariable(pathTemplateVar);
Statement pathTemplateClassVar = createPathTemplateClassStatement(routingHeaderParam, pathTemplateType, pathTemplateVar);
classStatements.add(pathTemplateClassVar);
MethodInvocationExpr addParamMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(routingHeadersBuilderVarNonDeclExpr).setMethodName("add").setArguments(requestFieldGetterExpr, routingHeaderKeyExpr, routingHeaderPatternExpr).build();
ExprStatement addParamStatement = ExprStatement.withExpr(addParamMethodExpr);
// No need to add null check if there is no nested fields
if (routingHeaderParam.getDescendantFieldNames().size() == 1) {
bodyStatements.add(addParamStatement);
} else {
IfStatement ifStatement = IfStatement.builder().setConditionExpr(fieldValuesNotNullConditionExpr(requestVarExpr, routingHeaderParam.getDescendantFieldNames())).setBody(ImmutableList.of(addParamStatement)).build();
bodyStatements.add(ifStatement);
}
}
returnExprBuilder.setExprReferenceExpr(routingHeadersBuilderVarNonDeclExpr).setMethodName("build");
}
Aggregations