use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.
the class AbstractServiceStubSettingsClassComposer method createNestedClassConstructorMethods.
private static List<MethodDefinition> createNestedClassConstructorMethods(Service service, GapicServiceConfig serviceConfig, Map<String, VariableExpr> nestedMethodSettingsMemberVarExprs, TypeStore typeStore) {
TypeNode builderType = typeStore.get(NESTED_BUILDER_CLASS_NAME);
List<MethodDefinition> ctorMethods = new ArrayList<>();
// First argument-less contructor.
ctorMethods.add(MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(builderType).setBody(Arrays.asList(ExprStatement.withExpr(ReferenceConstructorExpr.thisBuilder().setType(builderType).setArguments(CastExpr.builder().setType(FIXED_TYPESTORE.get("ClientContext")).setExpr(ValueExpr.createNullExpr()).build()).build()))).build());
// Second ctor that takes a clientContext argument.
VariableExpr clientContextVarExpr = VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("ClientContext")).setName("clientContext").build());
Reference pagedSettingsBuilderRef = ConcreteReference.withClazz(PagedCallSettings.Builder.class);
Reference batchingSettingsBuilderRef = ConcreteReference.withClazz(BatchingCallSettings.Builder.class);
Reference unaryCallSettingsBuilderRef = ConcreteReference.withClazz(UnaryCallSettings.Builder.class);
Function<TypeNode, Boolean> isUnaryCallSettingsBuilderFn = t -> t.reference().copyAndSetGenerics(ImmutableList.of()).equals(unaryCallSettingsBuilderRef);
Function<TypeNode, Boolean> isPagedCallSettingsBuilderFn = t -> t.reference().copyAndSetGenerics(ImmutableList.of()).equals(pagedSettingsBuilderRef);
Function<TypeNode, Boolean> isBatchingCallSettingsBuilderFn = t -> t.reference().copyAndSetGenerics(ImmutableList.of()).equals(batchingSettingsBuilderRef);
Function<TypeNode, TypeNode> builderToCallSettingsFn = t -> TypeNode.withReference(VaporReference.builder().setName(String.join(DOT, t.reference().enclosingClassNames())).setPakkage(t.reference().pakkage()).build());
List<Statement> ctorBodyStatements = new ArrayList<>();
ctorBodyStatements.add(ExprStatement.withExpr(ReferenceConstructorExpr.superBuilder().setType(builderType).setArguments(clientContextVarExpr).build()));
ctorBodyStatements.add(EMPTY_LINE_STATEMENT);
ctorBodyStatements.addAll(nestedMethodSettingsMemberVarExprs.entrySet().stream().map(e -> {
// TODO(miraleung): Extract this into another method.
// Name is fooBarSettings.
VariableExpr varExpr = e.getValue();
TypeNode varType = varExpr.type();
Preconditions.checkState(e.getKey().endsWith(SETTINGS_LITERAL), String.format("%s expected to end with \"Settings\"", e.getKey()));
String methodName = getMethodNameFromSettingsVarName(e.getKey());
if (!isPagedCallSettingsBuilderFn.apply(varType)) {
if (!isBatchingCallSettingsBuilderFn.apply(varType)) {
boolean isUnaryCallSettings = isUnaryCallSettingsBuilderFn.apply(varType);
Expr builderExpr = AssignmentExpr.builder().setVariableExpr(varExpr).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(builderToCallSettingsFn.apply(varExpr.type())).setMethodName(isUnaryCallSettings ? "newUnaryCallSettingsBuilder" : "newBuilder").setReturnType(varExpr.type()).build()).build();
return ExprStatement.withExpr(builderExpr);
}
Expr newBatchingSettingsExpr = MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("BatchingSettings")).setMethodName("newBuilder").build();
newBatchingSettingsExpr = MethodInvocationExpr.builder().setExprReferenceExpr(newBatchingSettingsExpr).setMethodName("build").build();
String batchingDescVarName = String.format(BATCHING_DESC_PATTERN, JavaStyle.toUpperSnakeCase(methodName));
Expr batchingSettingsBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(builderToCallSettingsFn.apply(varType)).setMethodName("newBuilder").setArguments(VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("BatchingDescriptor")).setName(batchingDescVarName).build())).build();
batchingSettingsBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(batchingSettingsBuilderExpr).setMethodName("setBatchingSettings").setArguments(newBatchingSettingsExpr).setReturnType(varType).build();
Expr builderExpr = AssignmentExpr.builder().setVariableExpr(varExpr).setValueExpr(batchingSettingsBuilderExpr).build();
return ExprStatement.withExpr(builderExpr);
}
String memberVarName = String.format(PAGED_RESPONSE_FACTORY_PATTERN, JavaStyle.toUpperSnakeCase(methodName));
VariableExpr argVar = VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("PagedListResponseFactory")).setName(memberVarName).build());
Expr builderExpr = AssignmentExpr.builder().setVariableExpr(varExpr).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(builderToCallSettingsFn.apply(varExpr.type())).setMethodName("newBuilder").setArguments(argVar).setReturnType(varExpr.type()).build()).build();
return ExprStatement.withExpr(builderExpr);
}).collect(Collectors.toList()));
Expr unaryMethodSettingsBuildersAssignExpr = AssignmentExpr.builder().setVariableExpr(NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableList")).setGenerics(NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR.type().reference().generics()).setMethodName("of").setArguments(nestedMethodSettingsMemberVarExprs.values().stream().filter(v -> isUnaryCallSettingsBuilderFn.apply(v.type()) || isPagedCallSettingsBuilderFn.apply(v.type()) || isBatchingCallSettingsBuilderFn.apply(v.type())).collect(Collectors.toList())).setReturnType(NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR.type()).build()).build();
ctorBodyStatements.add(EMPTY_LINE_STATEMENT);
ctorBodyStatements.add(ExprStatement.withExpr(unaryMethodSettingsBuildersAssignExpr));
ctorBodyStatements.add(ExprStatement.withExpr(MethodInvocationExpr.builder().setMethodName("initDefaults").setArguments(ValueExpr.withValue(ThisObjectValue.withType(builderType))).build()));
ctorMethods.add(MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(builderType).setArguments(clientContextVarExpr.toBuilder().setIsDecl(true).build()).setBody(ctorBodyStatements).build());
// Third constructor that takes a ServiceStubSettings.
TypeNode outerSettingsType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service));
VariableExpr settingsVarExpr = VariableExpr.withVariable(Variable.builder().setType(outerSettingsType).setName("settings").build());
ctorBodyStatements = new ArrayList<>();
ctorBodyStatements.add(ExprStatement.withExpr(ReferenceConstructorExpr.superBuilder().setType(builderType).setArguments(settingsVarExpr).build()));
ctorBodyStatements.add(EMPTY_LINE_STATEMENT);
// TODO(cleanup): Technically this should actually use the outer class's <method>Settings
// members to avoid decoupling variable names.
ctorBodyStatements.addAll(nestedMethodSettingsMemberVarExprs.values().stream().map(v -> ExprStatement.withExpr(AssignmentExpr.builder().setVariableExpr(v).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(VariableExpr.builder().setExprReferenceExpr(settingsVarExpr).setVariable(v.variable()).build()).setMethodName("toBuilder").setReturnType(v.type()).build()).build())).collect(Collectors.toList()));
ctorBodyStatements.add(EMPTY_LINE_STATEMENT);
ctorBodyStatements.add(ExprStatement.withExpr(unaryMethodSettingsBuildersAssignExpr));
ctorMethods.add(MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(builderType).setArguments(settingsVarExpr.toBuilder().setIsDecl(true).build()).setBody(ctorBodyStatements).build());
return ctorMethods;
}
use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.
the class AbstractServiceStubSettingsClassComposer method generate.
@Override
public GapicClass generate(GapicContext context, Service service) {
// TODO(miraleung): Robustify this against a null serviceConfig.
GapicServiceConfig serviceConfig = context.serviceConfig();
Map<String, Message> messageTypes = context.messages();
String pakkage = String.format("%s.stub", service.pakkage());
TypeStore typeStore = createDynamicTypes(service, pakkage);
List<Sample> samples = new ArrayList<>();
Set<String> deprecatedSettingVarNames = new HashSet<>();
Map<String, VariableExpr> methodSettingsMemberVarExprs = createMethodSettingsClassMemberVarExprs(service, serviceConfig, typeStore, /* isNestedClass= */
false, deprecatedSettingVarNames);
String className = ClassNames.getServiceStubSettingsClassName(service);
List<CommentStatement> classHeaderComments = createClassHeaderComments(service, typeStore.get(className), samples);
ClassDefinition classDef = ClassDefinition.builder().setPackageString(pakkage).setHeaderCommentStatements(classHeaderComments).setAnnotations(createClassAnnotations(service)).setScope(ScopeNode.PUBLIC).setName(className).setExtendsType(createExtendsType(service, typeStore)).setStatements(createClassStatements(service, serviceConfig, methodSettingsMemberVarExprs, messageTypes, typeStore)).setMethods(createClassMethods(service, methodSettingsMemberVarExprs, deprecatedSettingVarNames, typeStore)).setNestedClasses(Arrays.asList(createNestedBuilderClass(service, serviceConfig, typeStore))).build();
return GapicClass.create(GapicClass.Kind.STUB, classDef, SampleComposerUtil.handleDuplicateSamples(samples));
}
use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.
the class RetrySettingsComposer method createRetryCodesDefinitionsBlock.
public static BlockStatement createRetryCodesDefinitionsBlock(Service service, GapicServiceConfig serviceConfig, VariableExpr retryCodesDefinitionsClassMemberVarExpr) {
TypeNode definitionsType = TypeNode.withReference(ConcreteReference.builder().setClazz(ImmutableMap.Builder.class).setGenerics(retryCodesDefinitionsClassMemberVarExpr.type().reference().generics()).build());
VariableExpr definitionsVarExpr = VariableExpr.withVariable(Variable.builder().setType(definitionsType).setName("definitions").build());
List<Expr> bodyExprs = new ArrayList<>();
// Create the first expr.
bodyExprs.add(AssignmentExpr.builder().setVariableExpr(definitionsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")).setMethodName("builder").setReturnType(definitionsVarExpr.type()).build()).build());
for (Map.Entry<String, List<Code>> codeEntry : serviceConfig.getAllRetryCodes(service).entrySet()) {
bodyExprs.add(createRetryCodeDefinitionExpr(codeEntry.getKey(), codeEntry.getValue(), definitionsVarExpr));
}
// Reassign the new codes.
bodyExprs.add(AssignmentExpr.builder().setVariableExpr(retryCodesDefinitionsClassMemberVarExpr).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(definitionsVarExpr).setMethodName("build").setReturnType(retryCodesDefinitionsClassMemberVarExpr.type()).build()).build());
// Put everything together.
return BlockStatement.builder().setIsStatic(true).setBody(bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build();
}
use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.
the class RetrySettingsComposer method createRetryParamDefinitionsBlock.
public static BlockStatement createRetryParamDefinitionsBlock(Service service, GapicServiceConfig serviceConfig, VariableExpr retryParamDefinitionsClassMemberVarExpr) {
List<Expr> bodyExprs = new ArrayList<>();
TypeNode definitionsType = TypeNode.withReference(ConcreteReference.builder().setClazz(ImmutableMap.Builder.class).setGenerics(retryParamDefinitionsClassMemberVarExpr.type().reference().generics()).build());
VariableExpr definitionsVarExpr = VariableExpr.withVariable(Variable.builder().setType(definitionsType).setName("definitions").build());
VariableExpr settingsVarExpr = VariableExpr.withVariable(Variable.builder().setType(FIXED_TYPESTORE.get("RetrySettings")).setName("settings").build());
// Create the first two exprs.
bodyExprs.add(AssignmentExpr.builder().setVariableExpr(definitionsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")).setMethodName("builder").setReturnType(definitionsVarExpr.type()).build()).build());
bodyExprs.add(AssignmentExpr.builder().setVariableExpr(settingsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(ValueExpr.createNullExpr()).build());
// Build the settings object for each config.
for (Map.Entry<String, GapicRetrySettings> settingsEntry : serviceConfig.getAllGapicRetrySettings(service).entrySet()) {
bodyExprs.addAll(createRetrySettingsExprs(settingsEntry.getKey(), settingsEntry.getValue(), settingsVarExpr, definitionsVarExpr));
}
// Reassign the new settings.
bodyExprs.add(AssignmentExpr.builder().setVariableExpr(retryParamDefinitionsClassMemberVarExpr).setValueExpr(MethodInvocationExpr.builder().setExprReferenceExpr(definitionsVarExpr).setMethodName("build").setReturnType(retryParamDefinitionsClassMemberVarExpr.type()).build()).build());
// Put everything together.
return BlockStatement.builder().setIsStatic(true).setBody(bodyExprs.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList())).build();
}
use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.
the class Parser method parseMethods.
@VisibleForTesting
static List<Method> parseMethods(ServiceDescriptor serviceDescriptor, String servicePackage, Map<String, Message> messageTypes, Map<String, ResourceName> resourceNames, Optional<GapicServiceConfig> serviceConfigOpt, Set<ResourceName> outputArgResourceNames, Transport transport) {
List<Method> methods = new ArrayList<>();
for (MethodDescriptor protoMethod : serviceDescriptor.getMethods()) {
// Parse the method.
TypeNode inputType = TypeParser.parseType(protoMethod.getInputType());
Method.Builder methodBuilder = Method.builder();
if (protoMethod.getFile().toProto().hasSourceCodeInfo()) {
SourceCodeInfoLocation protoMethodLocation = SOURCE_CODE_INFO_PARSER.getLocation(protoMethod);
if (!Objects.isNull(protoMethodLocation) && !Strings.isNullOrEmpty(protoMethodLocation.getLeadingComments())) {
methodBuilder.setDescription(protoMethodLocation.getLeadingComments());
}
}
boolean isDeprecated = false;
if (protoMethod.getOptions().hasDeprecated()) {
isDeprecated = protoMethod.getOptions().getDeprecated();
}
Message inputMessage = messageTypes.get(inputType.reference().fullName());
Preconditions.checkNotNull(inputMessage, String.format("No message found for %s", inputType.reference().fullName()));
HttpBindings httpBindings = HttpRuleParser.parse(protoMethod, inputMessage, messageTypes);
boolean isBatching = !serviceConfigOpt.isPresent() ? false : serviceConfigOpt.get().hasBatchingSetting(/* protoPakkage */
protoMethod.getFile().getPackage(), serviceDescriptor.getName(), protoMethod.getName());
boolean operationPollingMethod = protoMethod.getOptions().hasExtension(ExtendedOperationsProto.operationPollingMethod) ? protoMethod.getOptions().getExtension(ExtendedOperationsProto.operationPollingMethod) : false;
RoutingHeaderRule routingHeaderRule = RoutingRuleParser.parse(protoMethod, inputMessage, messageTypes);
methods.add(methodBuilder.setName(protoMethod.getName()).setInputType(inputType).setOutputType(TypeParser.parseType(protoMethod.getOutputType())).setStream(Method.toStream(protoMethod.isClientStreaming(), protoMethod.isServerStreaming())).setLro(parseLro(servicePackage, protoMethod, messageTypes)).setMethodSignatures(MethodSignatureParser.parseMethodSignatures(protoMethod, servicePackage, inputType, messageTypes, resourceNames, outputArgResourceNames)).setHttpBindings(httpBindings).setRoutingHeaderRule(routingHeaderRule).setIsBatching(isBatching).setPageSizeFieldName(parsePageSizeFieldName(protoMethod, messageTypes, transport)).setIsDeprecated(isDeprecated).setOperationPollingMethod(operationPollingMethod).build());
// Any input type that has a resource reference will need a resource name helper class.
for (Field field : inputMessage.fields()) {
if (field.hasResourceReference()) {
String resourceTypeString = field.resourceReference().resourceTypeString();
ResourceName resourceName = null;
// versus example.com/FooBar.
if (resourceTypeString.indexOf(SLASH) < 0) {
Optional<String> actualResourceTypeNameOpt = resourceNames.keySet().stream().filter(k -> k.substring(k.lastIndexOf(SLASH) + 1).equals(resourceTypeString)).findFirst();
if (actualResourceTypeNameOpt.isPresent()) {
resourceName = resourceNames.get(actualResourceTypeNameOpt.get());
}
} else {
resourceName = resourceNames.get(resourceTypeString);
}
if (ResourceNameConstants.WILDCARD_PATTERN.equals(resourceTypeString)) {
resourceName = WILDCARD_RESOURCE_NAME;
} else {
Preconditions.checkNotNull(resourceName, String.format("Resource name %s not found; parsing field %s in message %s in method %s", resourceTypeString, field.name(), inputMessage.name(), protoMethod.getName()));
}
outputArgResourceNames.add(resourceName);
}
}
}
return methods;
}
Aggregations