use of com.google.api.generator.gapic.model.GapicContext in project gapic-generator-java by googleapis.
the class AbstractTransportServiceStubClassComposer method createConstructorMethods.
protected List<MethodDefinition> createConstructorMethods(GapicContext context, Service service, TypeStore typeStore, Map<String, VariableExpr> classMemberVarExprs, Map<String, VariableExpr> callableClassMemberVarExprs, Map<String, VariableExpr> protoMethodNameToDescriptorVarExprs, List<Statement> classStatements) {
TypeNode stubSettingsType = typeStore.get(getTransportContext().classNames().getServiceStubSettingsClassName(service));
VariableExpr settingsVarExpr = VariableExpr.withVariable(Variable.builder().setName("settings").setType(stubSettingsType).build());
TypeNode clientContextType = FIXED_TYPESTORE.get("ClientContext");
VariableExpr clientContextVarExpr = VariableExpr.withVariable(Variable.builder().setName("clientContext").setType(clientContextType).build());
VariableExpr callableFactoryVarExpr = VariableExpr.withVariable(Variable.builder().setName("callableFactory").setType(getTransportContext().stubCallableFactoryType()).build());
TypeNode thisClassType = typeStore.get(getTransportContext().classNames().getTransportServiceStubClassName(service));
TypeNode ioExceptionType = TypeNode.withReference(ConcreteReference.withClazz(IOException.class));
BiFunction<List<VariableExpr>, List<Statement>, MethodDefinition> ctorMakerFn = (args, body) -> MethodDefinition.constructorBuilder().setScope(ScopeNode.PROTECTED).setReturnType(thisClassType).setHeaderCommentStatements(Arrays.asList(createProtectedCtorComment(service))).setArguments(args.stream().map(v -> v.toBuilder().setIsDecl(true).build()).collect(Collectors.toList())).setThrowsExceptions(Arrays.asList(ioExceptionType)).setBody(body).build();
// First constructor method.
MethodDefinition firstCtor = ctorMakerFn.apply(Arrays.asList(settingsVarExpr, clientContextVarExpr), Arrays.asList(ExprStatement.withExpr(ReferenceConstructorExpr.thisBuilder().setType(thisClassType).setArguments(settingsVarExpr, clientContextVarExpr, NewObjectExpr.builder().setType(typeStore.get(getTransportContext().classNames().getTransportServiceCallableFactoryClassName(service))).build()).build())));
Expr thisExpr = ValueExpr.withValue(ThisObjectValue.withType(typeStore.get(getTransportContext().classNames().getTransportServiceStubClassName(service))));
// Body of the second constructor method.
List<Statement> secondCtorStatements = new ArrayList<>();
List<Expr> secondCtorExprs = new ArrayList<>();
secondCtorExprs.add(AssignmentExpr.builder().setVariableExpr(classMemberVarExprs.get("callableFactory").toBuilder().setExprReferenceExpr(thisExpr).build()).setValueExpr(callableFactoryVarExpr).build());
VariableExpr operationsStubClassVarExpr = classMemberVarExprs.get(getTransportContext().transportOperationsStubNames().get(0));
// TODO: refactor this
if (generateOperationsStubLogic(service)) {
secondCtorExprs.addAll(createOperationsStubInitExpr(service, thisExpr, operationsStubClassVarExpr, clientContextVarExpr, callableFactoryVarExpr));
}
secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
secondCtorExprs.clear();
secondCtorStatements.add(EMPTY_LINE_STATEMENT);
// Transport settings local variables.
Map<String, VariableExpr> javaStyleMethodNameToTransportSettingsVarExprs = service.methods().stream().collect(Collectors.toMap(m -> JavaStyle.toLowerCamelCase(m.name()), m -> VariableExpr.withVariable(Variable.builder().setName(String.format("%sTransportSettings", JavaStyle.toLowerCamelCase(m.name()))).setType(TypeNode.withReference(ConcreteReference.builder().setClazz(getTransportContext().callSettingsClass()).setGenerics(Arrays.asList(m.inputType().reference(), m.outputType().reference())).build())).build())));
secondCtorExprs.addAll(service.methods().stream().map(m -> createTransportSettingsInitExpr(m, javaStyleMethodNameToTransportSettingsVarExprs.get(JavaStyle.toLowerCamelCase(m.name())), protoMethodNameToDescriptorVarExprs.get(m.name()), classStatements)).collect(Collectors.toList()));
secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
secondCtorExprs.clear();
secondCtorStatements.add(EMPTY_LINE_STATEMENT);
// Initialize <method>Callable variables.
secondCtorExprs.addAll(callableClassMemberVarExprs.entrySet().stream().map(e -> createCallableInitExpr(context, service, e.getKey(), e.getValue(), callableFactoryVarExpr, settingsVarExpr, clientContextVarExpr, operationsStubClassVarExpr, thisExpr, javaStyleMethodNameToTransportSettingsVarExprs)).collect(Collectors.toList()));
secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
secondCtorExprs.clear();
secondCtorStatements.add(EMPTY_LINE_STATEMENT);
secondCtorStatements.addAll(createLongRunningClient(service, typeStore));
// Instantiate backgroundResources.
MethodInvocationExpr getBackgroundResourcesMethodExpr = MethodInvocationExpr.builder().setExprReferenceExpr(clientContextVarExpr).setMethodName("getBackgroundResources").build();
VariableExpr backgroundResourcesVarExpr = classMemberVarExprs.get("backgroundResources");
secondCtorExprs.add(AssignmentExpr.builder().setVariableExpr(backgroundResourcesVarExpr.toBuilder().setExprReferenceExpr(thisExpr).build()).setValueExpr(NewObjectExpr.builder().setType(FIXED_TYPESTORE.get("BackgroundResourceAggregation")).setArguments(Arrays.asList(getBackgroundResourcesMethodExpr)).build()).build());
secondCtorStatements.addAll(secondCtorExprs.stream().map(ExprStatement::withExpr).collect(Collectors.toList()));
secondCtorExprs.clear();
// Second constructor method.
MethodDefinition secondCtor = ctorMakerFn.apply(Arrays.asList(settingsVarExpr, clientContextVarExpr, callableFactoryVarExpr), secondCtorStatements);
return Arrays.asList(firstCtor, secondCtor);
}
use of com.google.api.generator.gapic.model.GapicContext in project gapic-generator-java by googleapis.
the class ClientLibraryPackageInfoComposer method createPackageInfoJavadoc.
private static CommentStatement createPackageInfoJavadoc(GapicContext context) {
JavaDocComment.Builder javaDocCommentBuilder = JavaDocComment.builder();
if (context.hasServiceYamlProto() && !Strings.isNullOrEmpty(context.serviceYamlProto().getTitle())) {
javaDocCommentBuilder = javaDocCommentBuilder.addComment(String.format(PACKAGE_INFO_TITLE_PATTERN, context.serviceYamlProto().getTitle()));
}
javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(PACKAGE_INFO_DESCRIPTION);
for (Service service : context.services()) {
String javaClientName = ClassNames.getServiceClientClassName(service);
javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(String.format("%s %s %s", DIVIDER, javaClientName, DIVIDER));
// TODO(miraleung): Replace this with a comment converter when we support CommonMark.
if (service.hasDescription()) {
String[] descriptionParagraphs = service.description().split("\\n\\n");
for (int i = 0; i < descriptionParagraphs.length; i++) {
boolean startsWithItemizedList = descriptionParagraphs[i].startsWith(" * ");
// Split by listed items, then join newlines.
List<String> listItems = Stream.of(descriptionParagraphs[i].split("\\n \\*")).map(s -> s.replace("\n", "")).collect(Collectors.toList());
if (startsWithItemizedList) {
// Remove the first asterisk.
listItems.set(0, listItems.get(0).substring(2));
}
if (!startsWithItemizedList) {
if (i == 0) {
javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(String.format(SERVICE_DESCRIPTION_HEADER_PATTERN, listItems.get(0)));
} else {
javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(listItems.get(0));
}
}
if (listItems.size() > 1 || startsWithItemizedList) {
javaDocCommentBuilder = javaDocCommentBuilder.addUnorderedList(listItems.subList(startsWithItemizedList ? 0 : 1, listItems.size()));
}
}
}
javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(String.format(SAMPLE_CODE_HEADER_PATTERN, javaClientName));
TypeNode clientType = TypeNode.withReference(VaporReference.builder().setPakkage(service.pakkage()).setName(ClassNames.getServiceClientClassName(service)).build());
Sample packageInfoSampleCode = ServiceClientHeaderSampleComposer.composeClassHeaderSample(service, clientType, context.resourceNames(), context.messages());
javaDocCommentBuilder.addSampleCode(SampleCodeWriter.writeInlineSample(packageInfoSampleCode.body()));
}
return CommentStatement.withComment(javaDocCommentBuilder.build());
}
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 mockServiceVarExpr = classMemberVarExprs.get(MOCK_SERVICE_VAR_NAME);
VariableExpr clientVarExpr = classMemberVarExprs.get(CLIENT_VAR_NAME);
TypeNode settingsType = typeStore.get(ClassNames.getServiceSettingsClassName(service));
TypeNode transportStubType = typeStore.get(getTransportContext().classNames().getTransportServiceStubClassName(service));
Function<Expr, BiFunction<String, Expr, MethodInvocationExpr>> methodBuilderFn = methodExpr -> (mName, argExpr) -> MethodInvocationExpr.builder().setExprReferenceExpr(methodExpr).setMethodName(mName).setArguments(Arrays.asList(argExpr)).build();
Expr initMockServiceExpr = AssignmentExpr.builder().setVariableExpr(mockServiceVarExpr).setValueExpr(NewObjectExpr.builder().setType(mockServiceVarExpr.type()).setArguments(MethodInvocationExpr.builder().setStaticReferenceType(transportStubType).setMethodName("getMethodDescriptors").build(), MethodInvocationExpr.builder().setStaticReferenceType(settingsType).setMethodName("getDefaultEndpoint").build()).build()).build();
VariableExpr localSettingsVarExpr = VariableExpr.withVariable(Variable.builder().setName("settings").setType(settingsType).build());
Expr settingsBuilderExpr = MethodInvocationExpr.builder().setStaticReferenceType(settingsType).setMethodName(newBuilderMethod).build();
Expr transportChannelProviderExpr = MethodInvocationExpr.builder().setStaticReferenceType(settingsType).setMethodName("defaultHttpJsonTransportProviderBuilder").build();
transportChannelProviderExpr = methodBuilderFn.apply(transportChannelProviderExpr).apply("setHttpTransport", mockServiceVarExpr);
transportChannelProviderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(transportChannelProviderExpr).setMethodName("build").setReturnType(localSettingsVarExpr.type()).build();
settingsBuilderExpr = methodBuilderFn.apply(settingsBuilderExpr).apply("setTransportChannelProvider", transportChannelProviderExpr);
settingsBuilderExpr = methodBuilderFn.apply(settingsBuilderExpr).apply("setCredentialsProvider", MethodInvocationExpr.builder().setStaticReferenceType(FIXED_TYPESTORE.get("NoCredentialsProvider")).setMethodName("create").build());
settingsBuilderExpr = MethodInvocationExpr.builder().setExprReferenceExpr(settingsBuilderExpr).setMethodName("build").setReturnType(localSettingsVarExpr.type()).build();
Expr initLocalSettingsExpr = AssignmentExpr.builder().setVariableExpr(localSettingsVarExpr.toBuilder().setIsDecl(true).build()).setValueExpr(settingsBuilderExpr).build();
Expr initClientExpr = AssignmentExpr.builder().setVariableExpr(clientVarExpr).setValueExpr(MethodInvocationExpr.builder().setStaticReferenceType(typeStore.get(ClassNames.getServiceClientClassName(service))).setMethodName("create").setArguments(Arrays.asList(localSettingsVarExpr)).setReturnType(clientVarExpr.type()).build()).build();
return MethodDefinition.builder().setAnnotations(Arrays.asList(AnnotationNode.withType(FIXED_TYPESTORE.get("BeforeClass")))).setScope(ScopeNode.PUBLIC).setReturnType(TypeNode.VOID).setName("startStaticServer").setThrowsExceptions(Arrays.asList(FIXED_TYPESTORE.get("IOException"))).setIsStatic(true).setBody(Arrays.asList(initMockServiceExpr, initLocalSettingsExpr, initClientExpr).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 RetrySettingsComposerTest method batchingSettings_fullFlowControlSettings.
@Test
public void batchingSettings_fullFlowControlSettings() {
String filename = "logging_gapic.yaml";
Path path = Paths.get(TestProtoLoader.instance().getTestFilesDirectory(), filename);
Optional<List<GapicBatchingSettings>> batchingSettingsOpt = BatchingSettingsConfigParser.parse(Optional.of(path.toString()));
assertTrue(batchingSettingsOpt.isPresent());
String jsonFilename = "logging_grpc_service_config.json";
Path jsonPath = Paths.get(TestProtoLoader.instance().getTestFilesDirectory(), jsonFilename);
Optional<GapicServiceConfig> configOpt = ServiceConfigParser.parse(jsonPath.toString());
assertTrue(configOpt.isPresent());
GapicServiceConfig config = configOpt.get();
config.setBatchingSettings(batchingSettingsOpt);
GapicContext context = TestProtoLoader.instance().parseLogging();
Service service = context.services().get(0);
assertEquals("LoggingServiceV2", service.name());
VariableExpr builderVarExpr = createBuilderVarExpr(service);
String methodSettingsName = "writeLogEntriesSettings";
GapicBatchingSettings batchingSettings = GapicBatchingSettings.builder().setProtoPakkage("com.google.logging.v2").setServiceName("LoggingServiceV2").setMethodName("WriteLogEntries").setElementCountThreshold(1000).setRequestByteThreshold(1048576).setDelayThresholdMillis(50).setFlowControlElementLimit(100000).setFlowControlByteLimit(10485760).setFlowControlLimitExceededBehavior(GapicBatchingSettings.FlowControlLimitExceededBehavior.THROW_EXCEPTION).setBatchedFieldName("entries").setDiscriminatorFieldNames(Arrays.asList("log_name", "resource", "labels")).build();
Expr builderExpr = RetrySettingsComposer.createBatchingBuilderSettingsExpr(methodSettingsName, batchingSettings, builderVarExpr);
builderExpr.accept(writerVisitor);
String expected = "builder" + ".writeLogEntriesSettings()" + ".setBatchingSettings(" + "BatchingSettings.newBuilder()" + ".setElementCountThreshold(1000L)" + ".setRequestByteThreshold(1048576L)" + ".setDelayThreshold(Duration.ofMillis(50L))" + ".setFlowControlSettings(" + "FlowControlSettings.newBuilder()" + ".setMaxOutstandingElementCount(100000L)" + ".setMaxOutstandingRequestBytes(10485760L)" + ".setLimitExceededBehavior(FlowController.LimitExceededBehavior.ThrowException)" + ".build())" + ".build())";
assertEquals(expected, writerVisitor.write());
}
use of com.google.api.generator.gapic.model.GapicContext in project gapic-generator-java by googleapis.
the class RetrySettingsComposerTest method paramDefinitionsBlock_noConfigsFound.
@Test
public void paramDefinitionsBlock_noConfigsFound() {
GapicContext context = TestProtoLoader.instance().parseShowcaseEcho();
Service service = context.services().get(0);
String jsonFilename = "retrying_grpc_service_config.json";
Path jsonPath = Paths.get(TestProtoLoader.instance().getTestFilesDirectory(), jsonFilename);
Optional<GapicServiceConfig> serviceConfigOpt = ServiceConfigParser.parse(jsonPath.toString());
assertTrue(serviceConfigOpt.isPresent());
GapicServiceConfig serviceConfig = serviceConfigOpt.get();
BlockStatement paramDefinitionsBlock = RetrySettingsComposer.createRetryParamDefinitionsBlock(service, serviceConfig, RETRY_PARAM_DEFINITIONS_VAR_EXPR);
paramDefinitionsBlock.accept(writerVisitor);
String expected = LineFormatter.lines("static {\n", "ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();\n", "RetrySettings settings = null;\n", "settings = RetrySettings.newBuilder().setRpcTimeoutMultiplier(1.0).build();\n", "definitions.put(\"no_retry_params\", settings);\n", "RETRY_PARAM_DEFINITIONS = definitions.build();\n", "}\n");
assertEquals(expected, writerVisitor.write());
}
Aggregations