use of com.google.api.generator.gapic.model.GapicContext 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.GapicContext in project gapic-generator-java by googleapis.
the class Generator method generateGapic.
public static CodeGeneratorResponse generateGapic(CodeGeneratorRequest request) {
GapicContext context = Parser.parse(request);
List<GapicClass> clazzes = Composer.composeServiceClasses(context);
GapicPackageInfo packageInfo = Composer.composePackageInfo(context);
String outputFilename = "temp-codegen.srcjar";
return Writer.write(context, clazzes, packageInfo, outputFilename);
}
use of com.google.api.generator.gapic.model.GapicContext 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.gapic.model.GapicContext in project gapic-generator-java by googleapis.
the class ServiceClientTestClassComposer method createClassMemberVarExprs.
@Override
protected Map<String, VariableExpr> createClassMemberVarExprs(Service service, GapicContext context, TypeStore typeStore) {
BiFunction<String, TypeNode, VariableExpr> varExprFn = (name, type) -> VariableExpr.withVariable(Variable.builder().setName(name).setType(type).build());
// Keep keys sorted in alphabetical order to ensure that the test output is deterministic.
Map<String, TypeNode> fields = new TreeMap<>();
fields.put(getMockServiceVarName(service), typeStore.get(ClassNames.getMockServiceClassName(service)));
for (Service mixinService : context.mixinServices()) {
fields.put(getMockServiceVarName(mixinService), typeStore.get(ClassNames.getMockServiceClassName(mixinService)));
}
fields.put(SERVICE_HELPER_VAR_NAME, FIXED_GRPC_TYPESTORE.get("MockServiceHelper"));
fields.put(CLIENT_VAR_NAME, typeStore.get(ClassNames.getServiceClientClassName(service)));
fields.put(CHANNEL_PROVIDER_VAR_NAME, FIXED_GRPC_TYPESTORE.get("LocalChannelProvider"));
return fields.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> varExprFn.apply(e.getKey(), e.getValue()), (u, v) -> {
throw new IllegalStateException();
}, TreeMap::new));
}
use of com.google.api.generator.gapic.model.GapicContext in project gapic-generator-java by googleapis.
the class Parser method parse.
public static GapicContext parse(CodeGeneratorRequest request) {
Optional<String> gapicYamlConfigPathOpt = PluginArgumentParser.parseGapicYamlConfigPath(request);
Optional<List<GapicBatchingSettings>> batchingSettingsOpt = BatchingSettingsConfigParser.parse(gapicYamlConfigPathOpt);
Optional<List<GapicLroRetrySettings>> lroRetrySettingsOpt = GapicLroRetrySettingsParser.parse(gapicYamlConfigPathOpt);
Optional<GapicLanguageSettings> languageSettingsOpt = GapicLanguageSettingsParser.parse(gapicYamlConfigPathOpt);
Optional<String> transportOpt = PluginArgumentParser.parseTransport(request);
boolean willGenerateMetadata = PluginArgumentParser.hasMetadataFlag(request);
Optional<String> serviceConfigPathOpt = PluginArgumentParser.parseJsonConfigPath(request);
Optional<GapicServiceConfig> serviceConfigOpt = ServiceConfigParser.parse(serviceConfigPathOpt.orElse(null));
if (serviceConfigOpt.isPresent()) {
GapicServiceConfig serviceConfig = serviceConfigOpt.get();
serviceConfig.setLroRetrySettings(lroRetrySettingsOpt);
serviceConfig.setBatchingSettings(batchingSettingsOpt);
serviceConfig.setLanguageSettings(languageSettingsOpt);
serviceConfigOpt = Optional.of(serviceConfig);
}
Optional<String> serviceYamlConfigPathOpt = PluginArgumentParser.parseServiceYamlConfigPath(request);
Optional<com.google.api.Service> serviceYamlProtoOpt = serviceYamlConfigPathOpt.flatMap(ServiceYamlParser::parse);
// Collect the resource references seen in messages.
Set<ResourceReference> outputResourceReferencesSeen = new HashSet<>();
// Keep message and resource name parsing separate for cleaner logic.
// While this takes an extra pass through the protobufs, the extra time is relatively trivial
// and is worth the larger reduced maintenance cost.
Map<String, Message> messages = parseMessages(request, outputResourceReferencesSeen);
Map<String, ResourceName> resourceNames = parseResourceNames(request);
messages = updateResourceNamesInMessages(messages, resourceNames.values());
// Contains only resource names that are actually used. Usage refers to the presence of a
// request message's field in an RPC's method_signature annotation. That is, resource name
// definitions
// or references that are simply defined, but not used in such a manner, will not have
// corresponding Java helper
// classes generated.
Set<ResourceName> outputArgResourceNames = new HashSet<>();
List<Service> mixinServices = new ArrayList<>();
Transport transport = Transport.parse(transportOpt.orElse(Transport.GRPC.toString()));
List<Service> services = parseServices(request, messages, resourceNames, outputArgResourceNames, serviceYamlProtoOpt, serviceConfigOpt, mixinServices, transport);
Preconditions.checkState(!services.isEmpty(), "No services found to generate");
// Temporary workaround for Ads, who still need these resource names.
if (services.get(0).protoPakkage().startsWith("google.ads.googleads.v")) {
Function<ResourceName, String> typeNameFn = r -> r.resourceTypeString().substring(r.resourceTypeString().indexOf("/") + 1);
Function<Set<ResourceName>, Set<String>> typeStringSetFn = sr -> sr.stream().map(typeNameFn).collect(Collectors.toSet());
// Include all resource names present in message types for backwards-compatibility with the
// monolith. In the future, this should be removed on a client library major semver update.
// Resolve type name collisions with the ones present in the method arguments.
final Set<String> typeStringSet = typeStringSetFn.apply(outputArgResourceNames);
outputArgResourceNames.addAll(resourceNames.values().stream().filter(r -> r.hasParentMessageName() && !typeStringSet.contains(typeNameFn.apply(r))).collect(Collectors.toSet()));
String servicePackage = services.get(0).pakkage();
Map<String, ResourceName> patternsToResourceNames = ResourceParserHelpers.createPatternResourceNameMap(resourceNames);
for (ResourceReference resourceReference : outputResourceReferencesSeen) {
final Set<String> interimTypeStringSet = typeStringSetFn.apply(outputArgResourceNames);
outputArgResourceNames.addAll(ResourceReferenceParser.parseResourceNames(resourceReference, servicePackage, null, resourceNames, patternsToResourceNames).stream().filter(r -> !interimTypeStringSet.contains(typeNameFn.apply(r))).collect(Collectors.toSet()));
}
}
return GapicContext.builder().setServices(services).setMixinServices(mixinServices).setMessages(messages).setResourceNames(resourceNames).setHelperResourceNames(outputArgResourceNames).setServiceConfig(serviceConfigOpt.orElse(null)).setGapicMetadataEnabled(willGenerateMetadata).setServiceYamlProto(serviceYamlProtoOpt.orElse(null)).setTransport(transport).build();
}
Aggregations