use of com.google.api.generator.gapic.model.ResourceName in project gapic-generator-java by googleapis.
the class AbstractServiceClientTestClassComposer method generate.
protected GapicClass generate(String className, GapicContext context, Service service) {
Map<String, ResourceName> resourceNames = context.helperResourceNames();
String pakkage = service.pakkage();
TypeStore typeStore = new TypeStore();
addDynamicTypes(context, service, typeStore);
GapicClass.Kind kind = Kind.MAIN;
Map<String, VariableExpr> classMemberVarExprs = createClassMemberVarExprs(service, context, typeStore);
ClassDefinition classDef = ClassDefinition.builder().setPackageString(pakkage).setAnnotations(createClassAnnotations()).setScope(ScopeNode.PUBLIC).setName(className).setStatements(createClassMemberFieldDecls(classMemberVarExprs)).setMethods(createClassMethods(service, context, classMemberVarExprs, typeStore, resourceNames)).build();
return GapicClass.create(kind, classDef);
}
use of com.google.api.generator.gapic.model.ResourceName in project gapic-generator-java by googleapis.
the class AbstractServiceClientTestClassComposer method createTestMethods.
private List<MethodDefinition> createTestMethods(Service service, GapicContext context, Map<String, VariableExpr> classMemberVarExprs, Map<String, ResourceName> resourceNames) {
Map<String, Message> messageTypes = context.messages();
List<MethodDefinition> javaMethods = new ArrayList<>();
for (Method method : service.methods()) {
Service matchingService = service;
if (method.isMixin()) {
int dotIndex = method.mixedInApiName().lastIndexOf(".");
String mixinServiceName = method.mixedInApiName().substring(dotIndex + 1);
String mixinServiceProtoPackage = method.mixedInApiName().substring(0, dotIndex);
Optional<Service> mixinServiceOpt = context.mixinServices().stream().filter(s -> s.name().equals(mixinServiceName) && s.protoPakkage().equals(mixinServiceProtoPackage)).findFirst();
if (mixinServiceOpt.isPresent()) {
matchingService = mixinServiceOpt.get();
}
}
// Ignore variants for streaming methods as well.
if (method.methodSignatures().isEmpty() || !method.stream().equals(Method.Stream.NONE)) {
javaMethods.add(createRpcTestMethod(method, service, matchingService, Collections.emptyList(), 0, true, classMemberVarExprs, resourceNames, messageTypes));
javaMethods.add(createRpcExceptionTestMethod(method, matchingService, Collections.emptyList(), 0, classMemberVarExprs, resourceNames, messageTypes));
} else {
for (int i = 0; i < method.methodSignatures().size(); i++) {
javaMethods.add(createRpcTestMethod(method, service, matchingService, method.methodSignatures().get(i), i, false, classMemberVarExprs, resourceNames, messageTypes));
javaMethods.add(createRpcExceptionTestMethod(method, matchingService, method.methodSignatures().get(i), i, classMemberVarExprs, resourceNames, messageTypes));
}
}
}
return javaMethods;
}
use of com.google.api.generator.gapic.model.ResourceName in project gapic-generator-java by googleapis.
the class ResourceNameHelperClassComposer method createOfOrFormatMethodHelper.
private static List<MethodDefinition> createOfOrFormatMethodHelper(ResourceName resourceName, Map<String, VariableExpr> patternTokenVarExprs, List<List<String>> tokenHierarchies, TypeStore typeStore, boolean isFormatMethod) {
List<MethodDefinition> javaMethods = new ArrayList<>();
String methodNameFormat = isFormatMethod ? "format%s" : "of%s";
String newBuilderMethodNameFormat = "new%s";
String setMethodNameFormat = "set%s";
String buildMethodName = "build";
String toStringMethodName = "toString";
AnnotationNode betaAnnotation = AnnotationNode.builder().setType(FIXED_TYPESTORE.get("BetaApi")).setDescription(String.format("The static %s methods are not stable yet and may be changed in the future.", isFormatMethod ? "format" : "create")).build();
List<AnnotationNode> annotations = Arrays.asList(betaAnnotation);
TypeNode thisClassType = typeStore.get(getThisClassName(resourceName));
TypeNode returnType = isFormatMethod ? TypeNode.STRING : thisClassType;
// Create the newBuilder and variation methods here.
// Variation example: newProjectLocationAutoscalingPolicyBuilder().
boolean hasVariants = tokenHierarchies.size() > 1;
for (int i = 0; i < tokenHierarchies.size(); i++) {
List<String> tokens = tokenHierarchies.get(i);
// PubSub special-case handling.
if (tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) {
Expr deletedTopicStringValExpr = ValueExpr.withValue(StringObjectValue.withValue(ResourceNameConstants.DELETED_TOPIC_LITERAL));
// Simply return `new TopicName("_deleted-topic_")` or the string value itself.
javaMethods.add(MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setIsStatic(true).setAnnotations(annotations).setReturnType(returnType).setName(String.format(methodNameFormat, concatToUpperCamelCaseName(tokens) + "Name")).setReturnExpr(returnType.equals(TypeNode.STRING) ? deletedTopicStringValExpr : NewObjectExpr.builder().setType(returnType).setArguments(deletedTopicStringValExpr).build()).build());
continue;
}
String builderMethodName = String.format(newBuilderMethodNameFormat, getBuilderTypeName(tokenHierarchies, i));
MethodInvocationExpr returnExpr = MethodInvocationExpr.builder().setMethodName(builderMethodName).build();
for (String token : tokens) {
String javaTokenVarName = JavaStyle.toLowerCamelCase(token);
returnExpr = MethodInvocationExpr.builder().setExprReferenceExpr(returnExpr).setMethodName(String.format(setMethodNameFormat, JavaStyle.toUpperCamelCase(token))).setArguments(Arrays.asList(VariableExpr.withVariable(Variable.builder().setName(javaTokenVarName).setType(TypeNode.STRING).build()))).build();
}
returnExpr = MethodInvocationExpr.builder().setExprReferenceExpr(returnExpr).setMethodName(buildMethodName).setReturnType(thisClassType).build();
if (isFormatMethod) {
returnExpr = MethodInvocationExpr.builder().setExprReferenceExpr(returnExpr).setMethodName(toStringMethodName).setReturnType(TypeNode.STRING).build();
}
List<VariableExpr> methodArgs = tokens.stream().map(t -> patternTokenVarExprs.get(t).toBuilder().setIsDecl(true).build()).collect(Collectors.toList());
javaMethods.add(MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setIsStatic(true).setAnnotations(i == 0 ? Collections.emptyList() : annotations).setReturnType(returnType).setName(String.format(methodNameFormat, i == 0 ? "" : concatToUpperCamelCaseName(tokens) + "Name")).setArguments(methodArgs).setReturnExpr(returnExpr).build());
if (i == 0 && hasVariants) {
javaMethods.add(MethodDefinition.builder().setScope(ScopeNode.PUBLIC).setIsStatic(true).setAnnotations(annotations).setReturnType(returnType).setName(String.format(methodNameFormat, concatToUpperCamelCaseName(tokenHierarchies.get(i)) + "Name")).setArguments(methodArgs).setReturnExpr(returnExpr).build());
}
}
return javaMethods;
}
use of com.google.api.generator.gapic.model.ResourceName 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.gapic.model.ResourceName 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