From 8bc63f4e5645dc626e502c3a5d2546dfd0286d61 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Wed, 2 Dec 2020 13:27:08 -0800 Subject: [PATCH 01/11] fix: fix dep ordering in Bazel dedupe rules --- rules_java_gapic/java_gapic.bzl | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/rules_java_gapic/java_gapic.bzl b/rules_java_gapic/java_gapic.bzl index 96e482907c..d265f8c676 100644 --- a/rules_java_gapic/java_gapic.bzl +++ b/rules_java_gapic/java_gapic.bzl @@ -189,7 +189,7 @@ def java_gapic_library( ) # General additional deps. - actual_deps = resource_name_deps + [ + actual_deps = deps + resource_name_deps + [ "@com_google_googleapis//google/rpc:rpc_java_proto", "@com_google_googleapis//google/longrunning:longrunning_java_proto", "@com_google_protobuf//:protobuf_java", @@ -207,7 +207,6 @@ def java_gapic_library( "@com_google_http_client_google_http_client//jar", "@javax_annotation_javax_annotation_api//jar", ] - _append_dep_without_duplicates(actual_deps, deps) native.java_library( name = name, From c2e56c125fcd495052c67a22bb9cc4a6ef64c2d5 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Mon, 21 Dec 2020 11:26:52 -0800 Subject: [PATCH 02/11] fix: filter out unbound vars in HttpRuleParser --- .../api/generator/gapic/protoparser/HttpRuleParser.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java b/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java index 6998f3c26b..488bc52cea 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java @@ -31,6 +31,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; public class HttpRuleParser { private static final String ASTERISK = "*"; @@ -115,7 +116,10 @@ private static Set getPatternBindings(HttpRule httpRule) { } PathTemplate template = PathTemplate.create(pattern); - Set bindings = new HashSet(template.vars()); + Set bindings = + new HashSet( + // Filter out any unbound variable like "$0, $1, etc. + template.vars().stream().filter(s -> !s.contains("$")).collect(Collectors.toList())); return bindings; } From a14a1b1c8fa40fefea4be133f8023d91fc5d04c4 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Mon, 21 Dec 2020 13:12:30 -0800 Subject: [PATCH 03/11] fix: use nested types in message store key, filter out subtypes in typestore --- .../composer/ServiceClientClassComposer.java | 5 +++++ .../gapic/composer/ServiceStubClassComposer.java | 9 +++++++++ .../gapic/protoparser/HttpRuleParser.java | 7 +++++-- .../api/generator/gapic/protoparser/Parser.java | 16 +++++++++++----- .../goldens/logging/MetricsClientTest.java | 7 +++++++ 5 files changed, 37 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java index 4c72ed80a3..6e3e7fc76c 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java @@ -1511,6 +1511,11 @@ private static Map createProtoMessageTypes( String pakkage, Map messageTypes) { // Vapor message types. return messageTypes.entrySet().stream() + // Short-term hack for messages that have nested subtypes with colliding names. This + // should work as long as there isn't heavy usage of fully-qualified nested subtypes in + // general. A long-term fix would involve adding a custom type-store that handles + // fully-qualified types. + .filter(e -> e.getValue().outerNestedTypes().isEmpty()) .collect( Collectors.toMap( e -> e.getValue().name(), diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java index 590c589e23..47a3c7a19e 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java @@ -40,6 +40,7 @@ import com.google.longrunning.Operation; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -230,8 +231,16 @@ private static Map createTypes( c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); // Vapor message types. + List msgs = new ArrayList(messageTypes.keySet()); + Collections.sort(msgs); + // Preconditions.checkState(false, "DEL: mesgs: " + msgs); types.putAll( messageTypes.entrySet().stream() + // Short-term hack for messages that have nested subtypes with colliding names. This + // should work as long as there isn't heavy usage of fully-qualified nested subtypes in + // general. A long-term fix would involve adding a custom type-store that handles + // fully-qualified types. + .filter(e -> e.getValue().outerNestedTypes().isEmpty()) .collect( Collectors.toMap( e -> e.getValue().name(), diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java b/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java index 488bc52cea..b55aaa263a 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/HttpRuleParser.java @@ -130,8 +130,11 @@ private static void checkHttpFieldIsValid(String binding, Message inputMessage, Preconditions.checkState( inputMessage.fieldMap().containsKey(binding), String.format( - "Expected message %s to contain field %s but none found", - inputMessage.name(), binding)); + "Expected message %s to contain field %s but none found" + + ", DEL: " + + inputMessage.fieldMap().keySet(), + inputMessage.name(), + binding)); Field field = inputMessage.fieldMap().get(binding); boolean fieldCondition = !field.isRepeated(); if (!isBody) { diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java index 86b66bb91a..832420374d 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java @@ -361,13 +361,18 @@ private static Map parseMessages( if (isMapType(nestedMessage)) { continue; } - outerNestedTypes.add(messageName); + List currentNestedTypes = new ArrayList<>(outerNestedTypes); + currentNestedTypes.add(messageName); messages.putAll( - parseMessages(nestedMessage, outputResourceReferencesSeen, outerNestedTypes)); + parseMessages(nestedMessage, outputResourceReferencesSeen, currentNestedTypes)); } } + String messageKey = + outerNestedTypes.isEmpty() || outerNestedTypes.get(0).equals(messageName) + ? messageName + : String.format("%s.%s", String.join(".", outerNestedTypes), messageName); messages.put( - messageName, + messageKey, Message.builder() .setType(TypeParser.parseType(messageDescriptor)) .setName(messageName) @@ -564,8 +569,9 @@ static LongrunningOperation parseLro( Preconditions.checkNotNull( metadataMessage, String.format( - "LRO metadata message %s not found in method %s", - metadataTypeName, methodDescriptor.getName())); + "LRO metadata message %s not found in method %s" + ", DEL: " + messageTypes.keySet(), + metadataTypeName, + methodDescriptor.getName())); return LongrunningOperation.withTypes(responseMessage.type(), metadataMessage.type()); } diff --git a/test/integration/goldens/logging/MetricsClientTest.java b/test/integration/goldens/logging/MetricsClientTest.java index e6a0289905..02973ea7db 100644 --- a/test/integration/goldens/logging/MetricsClientTest.java +++ b/test/integration/goldens/logging/MetricsClientTest.java @@ -18,6 +18,7 @@ import static com.google.cloud.logging.v2.MetricsClient.ListLogMetricsPagedResponse; +import com.google.api.Distribution; import com.google.api.MetricDescriptor; import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.gax.grpc.GaxGrpcProperties; @@ -189,6 +190,7 @@ public void getLogMetricTest() throws Exception { .setMetricDescriptor(MetricDescriptor.newBuilder().build()) .setValueExtractor("valueExtractor-1867420749") .putAllLabelExtractors(new HashMap()) + .setBucketOptions(Distribution.BucketOptions.newBuilder().build()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .build(); @@ -234,6 +236,7 @@ public void getLogMetricTest2() throws Exception { .setMetricDescriptor(MetricDescriptor.newBuilder().build()) .setValueExtractor("valueExtractor-1867420749") .putAllLabelExtractors(new HashMap()) + .setBucketOptions(Distribution.BucketOptions.newBuilder().build()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .build(); @@ -279,6 +282,7 @@ public void createLogMetricTest() throws Exception { .setMetricDescriptor(MetricDescriptor.newBuilder().build()) .setValueExtractor("valueExtractor-1867420749") .putAllLabelExtractors(new HashMap()) + .setBucketOptions(Distribution.BucketOptions.newBuilder().build()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .build(); @@ -327,6 +331,7 @@ public void createLogMetricTest2() throws Exception { .setMetricDescriptor(MetricDescriptor.newBuilder().build()) .setValueExtractor("valueExtractor-1867420749") .putAllLabelExtractors(new HashMap()) + .setBucketOptions(Distribution.BucketOptions.newBuilder().build()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .build(); @@ -375,6 +380,7 @@ public void updateLogMetricTest() throws Exception { .setMetricDescriptor(MetricDescriptor.newBuilder().build()) .setValueExtractor("valueExtractor-1867420749") .putAllLabelExtractors(new HashMap()) + .setBucketOptions(Distribution.BucketOptions.newBuilder().build()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .build(); @@ -423,6 +429,7 @@ public void updateLogMetricTest2() throws Exception { .setMetricDescriptor(MetricDescriptor.newBuilder().build()) .setValueExtractor("valueExtractor-1867420749") .putAllLabelExtractors(new HashMap()) + .setBucketOptions(Distribution.BucketOptions.newBuilder().build()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .build(); From af420ac164742b418e54c8551392e86716e8a1e2 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Mon, 21 Dec 2020 15:37:05 -0800 Subject: [PATCH 04/11] refactor: make TypeNode map a TypeStore class --- .../google/api/generator/gapic/BUILD.bazel | 2 + .../api/generator/gapic/composer/BUILD.bazel | 1 + ...pcServiceCallableFactoryClassComposer.java | 100 +++--- .../GrpcServiceStubClassComposer.java | 135 ++++--- .../composer/MockServiceClassComposer.java | 104 +++--- .../MockServiceImplClassComposer.java | 65 ++-- .../ResourceNameHelperClassComposer.java | 167 ++++----- .../gapic/composer/RetrySettingsComposer.java | 41 +-- .../composer/ServiceClientClassComposer.java | 337 +++++++----------- .../ServiceClientTestClassComposer.java | 218 +++++------ .../ServiceSettingsClassComposer.java | 224 ++++++------ .../composer/ServiceStubClassComposer.java | 136 +++---- .../ServiceStubSettingsClassComposer.java | 261 ++++++-------- .../composer/samplecode/SampleCodeWriter.java | 2 +- .../gapic/composer/store/BUILD.bazel | 38 ++ .../gapic/composer/store/TypeStore.java | 98 +++++ 16 files changed, 885 insertions(+), 1044 deletions(-) create mode 100644 src/main/java/com/google/api/generator/gapic/composer/store/BUILD.bazel create mode 100644 src/main/java/com/google/api/generator/gapic/composer/store/TypeStore.java diff --git a/src/main/java/com/google/api/generator/gapic/BUILD.bazel b/src/main/java/com/google/api/generator/gapic/BUILD.bazel index 986b6d595b..93e9d3077a 100644 --- a/src/main/java/com/google/api/generator/gapic/BUILD.bazel +++ b/src/main/java/com/google/api/generator/gapic/BUILD.bazel @@ -6,6 +6,8 @@ filegroup( name = "gapic_files", srcs = glob(["*.java"]) + [ "//src/main/java/com/google/api/generator/gapic/composer:composer_files", + "//src/main/java/com/google/api/generator/gapic/composer/samplecode:samplecode_files", + "//src/main/java/com/google/api/generator/gapic/composer/store:store_files", "//src/main/java/com/google/api/generator/gapic/model:model_files", "//src/main/java/com/google/api/generator/gapic/protoparser:protoparser_files", "//src/main/java/com/google/api/generator/gapic/protowriter:protowriter_files", diff --git a/src/main/java/com/google/api/generator/gapic/composer/BUILD.bazel b/src/main/java/com/google/api/generator/gapic/composer/BUILD.bazel index 9e5bbfd444..4e5946c30f 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/BUILD.bazel +++ b/src/main/java/com/google/api/generator/gapic/composer/BUILD.bazel @@ -18,6 +18,7 @@ java_library( "//src/main/java/com/google/api/generator/engine/writer", "//src/main/java/com/google/api/generator/gapic:status_java_proto", "//src/main/java/com/google/api/generator/gapic/composer/samplecode", + "//src/main/java/com/google/api/generator/gapic/composer/store", "//src/main/java/com/google/api/generator/gapic/model", "//src/main/java/com/google/api/generator/gapic/utils", "@com_google_api_api_common//jar", diff --git a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposer.java index b2c4a88432..da761c834c 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposer.java @@ -31,14 +31,13 @@ import com.google.api.gax.rpc.UnaryCallable; import com.google.api.generator.engine.ast.AnnotationNode; import com.google.api.generator.engine.ast.ClassDefinition; -import com.google.api.generator.engine.ast.ConcreteReference; import com.google.api.generator.engine.ast.MethodDefinition; import com.google.api.generator.engine.ast.MethodInvocationExpr; import com.google.api.generator.engine.ast.ScopeNode; import com.google.api.generator.engine.ast.TypeNode; -import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; @@ -65,7 +64,7 @@ public static GrpcServiceCallableFactoryClassComposer instance() { @Override public GapicClass generate(Service service, Map ignore) { - Map types = createTypes(service); + TypeStore typeStore = createTypes(service); String className = ClassNames.getGrpcServiceCallableFactoryClassName(service); GapicClass.Kind kind = Kind.STUB; String pakkage = String.format("%s.stub", service.pakkage()); @@ -76,45 +75,45 @@ public GapicClass generate(Service service, Map ignore) { .setHeaderCommentStatements( StubCommentComposer.createGrpcServiceCallableFactoryClassHeaderComments( service.name())) - .setAnnotations(createClassAnnotations(types)) - .setImplementsTypes(createClassImplements(types)) + .setAnnotations(createClassAnnotations(typeStore)) + .setImplementsTypes(createClassImplements(typeStore)) .setName(className) - .setMethods(createClassMethods(types)) + .setMethods(createClassMethods(typeStore)) .setScope(ScopeNode.PUBLIC) .build(); return GapicClass.create(kind, classDef); } - private static List createClassAnnotations(Map types) { + private static List createClassAnnotations(TypeStore typeStore) { return Arrays.asList( AnnotationNode.builder() - .setType(types.get("Generated")) + .setType(typeStore.get("Generated")) .setDescription("by gapic-generator") .build()); } - private static List createClassImplements(Map types) { - return Arrays.asList(types.get("GrpcStubCallableFactory")); + private static List createClassImplements(TypeStore typeStore) { + return Arrays.asList(typeStore.get("GrpcStubCallableFactory")); } - private static List createClassMethods(Map types) { + private static List createClassMethods(TypeStore typeStore) { return Arrays.asList( - createUnaryCallableMethod(types), - createPagedCallableMethod(types), - createBatchingCallableMethod(types), - createOperationCallableMethod(types), - createBidiStreamingCallableMethod(types), - createServerStreamingCallableMethod(types), - createClientStreamingCallableMethod(types)); + createUnaryCallableMethod(typeStore), + createPagedCallableMethod(typeStore), + createBatchingCallableMethod(typeStore), + createOperationCallableMethod(typeStore), + createBidiStreamingCallableMethod(typeStore), + createServerStreamingCallableMethod(typeStore), + createClientStreamingCallableMethod(typeStore)); } - private static MethodDefinition createUnaryCallableMethod(Map types) { + private static MethodDefinition createUnaryCallableMethod(TypeStore typeStore) { String methodVariantName = "Unary"; String requestTemplateName = "RequestT"; String responseTemplateName = "ResponseT"; List methodTemplateNames = Arrays.asList(requestTemplateName, responseTemplateName); return createGenericCallableMethod( - types, + typeStore, /*methodTemplateNames=*/ methodTemplateNames, /*returnCallableKindName=*/ methodVariantName, /*returnCallableTemplateNames=*/ methodTemplateNames, @@ -128,7 +127,7 @@ private static MethodDefinition createUnaryCallableMethod(Map .collect(Collectors.toList())); } - private static MethodDefinition createPagedCallableMethod(Map types) { + private static MethodDefinition createPagedCallableMethod(TypeStore typeStore) { String methodVariantName = "Paged"; String requestTemplateName = "RequestT"; String pagedResponseTemplateName = "PagedListResponseT"; @@ -136,7 +135,7 @@ private static MethodDefinition createPagedCallableMethod(Map List methodTemplateNames = Arrays.asList(requestTemplateName, responseTemplateName, pagedResponseTemplateName); return createGenericCallableMethod( - types, + typeStore, /*methodTemplateNames=*/ methodTemplateNames, /*returnCallableKindName=*/ "Unary", /*returnCallableTemplateNames=*/ Arrays.asList( @@ -150,13 +149,13 @@ private static MethodDefinition createPagedCallableMethod(Map .collect(Collectors.toList())); } - private static MethodDefinition createBatchingCallableMethod(Map types) { + private static MethodDefinition createBatchingCallableMethod(TypeStore typeStore) { String methodVariantName = "Batching"; String requestTemplateName = "RequestT"; String responseTemplateName = "ResponseT"; List methodTemplateNames = Arrays.asList(requestTemplateName, responseTemplateName); return createGenericCallableMethod( - types, + typeStore, /*methodTemplateNames=*/ methodTemplateNames, /*returnCallableKindName=*/ "Unary", /*returnCallableTemplateNames=*/ methodTemplateNames, @@ -170,33 +169,33 @@ private static MethodDefinition createBatchingCallableMethod(Map types) { + private static MethodDefinition createOperationCallableMethod(TypeStore typeStore) { String methodVariantName = "Operation"; String requestTemplateName = "RequestT"; String responseTemplateName = "ResponseT"; List methodTemplateNames = Arrays.asList(requestTemplateName, responseTemplateName, "MetadataT"); return createGenericCallableMethod( - types, + typeStore, /*methodTemplateNames=*/ methodTemplateNames, /*returnCallableKindName=*/ methodVariantName, /*returnCallableTemplateNames=*/ methodTemplateNames, /*methodVariantName=*/ methodVariantName, /*grpcCallSettingsTemplateObjects=*/ Arrays.asList( - requestTemplateName, types.get("Operation")), + requestTemplateName, typeStore.get("Operation")), /*callSettingsVariantName=*/ methodVariantName, /*callSettingsTemplateObjects=*/ methodTemplateNames.stream() .map(n -> (Object) n) .collect(Collectors.toList())); } - private static MethodDefinition createBidiStreamingCallableMethod(Map types) { + private static MethodDefinition createBidiStreamingCallableMethod(TypeStore typeStore) { String methodVariantName = "BidiStreaming"; String requestTemplateName = "RequestT"; String responseTemplateName = "ResponseT"; List methodTemplateNames = Arrays.asList(requestTemplateName, responseTemplateName); return createGenericCallableMethod( - types, + typeStore, /*methodTemplateNames=*/ methodTemplateNames, /*returnCallableKindName=*/ methodVariantName, /*returnCallableTemplateNames=*/ methodTemplateNames, @@ -210,13 +209,13 @@ private static MethodDefinition createBidiStreamingCallableMethod(Map types) { + private static MethodDefinition createServerStreamingCallableMethod(TypeStore typeStore) { String methodVariantName = "ServerStreaming"; String requestTemplateName = "RequestT"; String responseTemplateName = "ResponseT"; List methodTemplateNames = Arrays.asList(requestTemplateName, responseTemplateName); return createGenericCallableMethod( - types, + typeStore, /*methodTemplateNames=*/ methodTemplateNames, /*returnCallableKindName=*/ methodVariantName, /*returnCallableTemplateNames=*/ methodTemplateNames, @@ -230,13 +229,13 @@ private static MethodDefinition createServerStreamingCallableMethod(Map types) { + private static MethodDefinition createClientStreamingCallableMethod(TypeStore typeStore) { String methodVariantName = "ClientStreaming"; String requestTemplateName = "RequestT"; String responseTemplateName = "ResponseT"; List methodTemplateNames = Arrays.asList(requestTemplateName, responseTemplateName); return createGenericCallableMethod( - types, + typeStore, /*methodTemplateNames=*/ methodTemplateNames, /*returnCallableKindName=*/ methodVariantName, /*returnCallableTemplateNames=*/ methodTemplateNames, @@ -251,7 +250,7 @@ private static MethodDefinition createClientStreamingCallableMethod(Map types, + TypeStore typeStore, List methodTemplateNames, String returnCallableKindName, List returnCallableTemplateNames, @@ -272,7 +271,7 @@ private static MethodDefinition createGenericCallableMethod( .setVariable( Variable.builder() .setName("grpcCallSettings") - .setType(types.get(grpcCallSettingsTypeName)) + .setType(typeStore.get(grpcCallSettingsTypeName)) .build()) .setIsDecl(true) .setTemplateObjects(grpcCallSettingsTemplateObjects) @@ -282,7 +281,7 @@ private static MethodDefinition createGenericCallableMethod( .setVariable( Variable.builder() .setName("callSettings") - .setType(types.get(callSettingsTypeName)) + .setType(typeStore.get(callSettingsTypeName)) .build()) .setIsDecl(true) .setTemplateObjects(callSettingsTemplateObjects) @@ -292,7 +291,7 @@ private static MethodDefinition createGenericCallableMethod( .setVariable( Variable.builder() .setName("clientContext") - .setType(types.get("ClientContext")) + .setType(typeStore.get("ClientContext")) .build()) .setIsDecl(true) .build()); @@ -302,18 +301,18 @@ private static MethodDefinition createGenericCallableMethod( .setVariable( Variable.builder() .setName("operationsStub") - .setType(types.get("OperationsStub")) + .setType(typeStore.get("OperationsStub")) .build()) .setIsDecl(true) .build()); } String grpcCallableFactoryTypeName = "GrpcCallableFactory"; - TypeNode grpcCallableFactoryType = types.get(grpcCallableFactoryTypeName); + TypeNode grpcCallableFactoryType = typeStore.get(grpcCallableFactoryTypeName); Preconditions.checkNotNull( grpcCallableFactoryType, String.format("Type %s not found", grpcCallableFactoryTypeName)); - TypeNode returnType = types.get(returnTypeName); + TypeNode returnType = typeStore.get(returnTypeName); MethodInvocationExpr returnExpr = MethodInvocationExpr.builder() .setMethodName(methodName) @@ -337,7 +336,7 @@ private static MethodDefinition createGenericCallableMethod( .build(); } - private static Map createTypes(Service service) { + private static TypeStore createTypes(Service service) { List concreteClazzes = Arrays.asList( // Gax-java classes. @@ -360,21 +359,8 @@ private static Map createTypes(Service service) { Generated.class, Operation.class, UnsupportedOperationException.class); - Map types = - concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); - - // Vapor dependency types. - types.put( - "OperationsStub", - TypeNode.withReference( - VaporReference.builder() - .setName("OperationsStub") - .setPakkage("com.google.longrunning.stub") - .build())); - return types; + TypeStore typeStore = new TypeStore(concreteClazzes); + typeStore.put("com.google.longrunning.stub", "OperationsStub"); + return typeStore; } } diff --git a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java index 7686f679df..3f22fc65b0 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java @@ -46,9 +46,9 @@ import com.google.api.generator.engine.ast.ThisObjectValue; import com.google.api.generator.engine.ast.TypeNode; import com.google.api.generator.engine.ast.ValueExpr; -import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; @@ -64,7 +64,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -97,7 +96,7 @@ public class GrpcServiceStubClassComposer implements ClassComposer { private static final GrpcServiceStubClassComposer INSTANCE = new GrpcServiceStubClassComposer(); - private static final Map STATIC_TYPES = createStaticTypes(); + private static final TypeStore FIXED_TYPESTORE = createStaticTypes(); // Legacy support for the original reroute_to_grpc_interface option in gapic.yaml. These two APIs // predate the modern way, which is to add the RPCs directly into the proto. @@ -115,7 +114,7 @@ public static GrpcServiceStubClassComposer instance() { @Override public GapicClass generate(Service service, Map ignore) { String pakkage = service.pakkage() + ".stub"; - Map types = createDynamicTypes(service, pakkage); + TypeStore typeStore = createDynamicTypes(service, pakkage); String className = ClassNames.getGrpcServiceStubClassName(service); GapicClass.Kind kind = Kind.STUB; @@ -123,7 +122,7 @@ public GapicClass generate(Service service, Map ignore) { createProtoMethodNameToDescriptorClassMembers(service); Map callableClassMemberVarExprs = - createCallableClassMembers(service, types); + createCallableClassMembers(service, typeStore); Map classMemberVarExprs = new LinkedHashMap<>(); classMemberVarExprs.put( @@ -131,21 +130,21 @@ public GapicClass generate(Service service, Map ignore) { VariableExpr.withVariable( Variable.builder() .setName(BACKGROUND_RESOURCES_MEMBER_NAME) - .setType(STATIC_TYPES.get("BackgroundResource")) + .setType(FIXED_TYPESTORE.get("BackgroundResource")) .build())); classMemberVarExprs.put( OPERATIONS_STUB_MEMBER_NAME, VariableExpr.withVariable( Variable.builder() .setName(OPERATIONS_STUB_MEMBER_NAME) - .setType(STATIC_TYPES.get("GrpcOperationsStub")) + .setType(FIXED_TYPESTORE.get("GrpcOperationsStub")) .build())); classMemberVarExprs.put( CALLABLE_FACTORY_MEMBER_NAME, VariableExpr.withVariable( Variable.builder() .setName(CALLABLE_FACTORY_MEMBER_NAME) - .setType(STATIC_TYPES.get("GrpcStubCallableFactory")) + .setType(FIXED_TYPESTORE.get("GrpcStubCallableFactory")) .build())); List classStatements = @@ -163,12 +162,12 @@ public GapicClass generate(Service service, Map ignore) { .setAnnotations(createClassAnnotations()) .setScope(ScopeNode.PUBLIC) .setName(className) - .setExtendsType(types.get(ClassNames.getServiceStubClassName(service))) + .setExtendsType(typeStore.get(ClassNames.getServiceStubClassName(service))) .setStatements(classStatements) .setMethods( createClassMethods( service, - types, + typeStore, classMemberVarExprs, callableClassMemberVarExprs, protoMethodNameToDescriptorVarExprs)) @@ -210,7 +209,7 @@ private static Statement createMethodDescriptorVariableDecl( MethodInvocationExpr methodDescriptorMaker = MethodInvocationExpr.builder() .setMethodName("newBuilder") - .setStaticReferenceType(STATIC_TYPES.get("MethodDescriptor")) + .setStaticReferenceType(FIXED_TYPESTORE.get("MethodDescriptor")) .setGenerics(methodDescriptorVarExpr.variable().type().reference().generics()) .build(); @@ -239,7 +238,7 @@ private static Statement createMethodDescriptorVariableDecl( Function protoUtilsMarshallerFn = m -> MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("ProtoUtils")) + .setStaticReferenceType(FIXED_TYPESTORE.get("ProtoUtils")) .setMethodName("marshaller") .setArguments(Arrays.asList(m)) .build(); @@ -325,7 +324,7 @@ private static Map createProtoMethodNameToDescriptorClassM } private static Map createCallableClassMembers( - Service service, Map types) { + Service service, TypeStore typeStore) { Map callableClassMembers = new LinkedHashMap<>(); // Using a for-loop because the output cardinality is not a 1:1 mapping to the input set. for (Method protoMethod : service.methods()) { @@ -372,7 +371,7 @@ private static Map createCallableClassMembers( .copyAndSetGenerics( Arrays.asList( protoMethod.inputType().reference(), - types + typeStore .get( String.format( PAGED_RESPONSE_TYPE_NAME_PATTERN, @@ -387,23 +386,23 @@ private static Map createCallableClassMembers( private static List createClassAnnotations() { return Arrays.asList( AnnotationNode.builder() - .setType(STATIC_TYPES.get("Generated")) + .setType(FIXED_TYPESTORE.get("Generated")) .setDescription("by gapic-generator-java") .build()); } private static List createClassMethods( Service service, - Map types, + TypeStore typeStore, Map classMemberVarExprs, Map callableClassMemberVarExprs, Map protoMethodNameToDescriptorVarExprs) { List javaMethods = new ArrayList<>(); - javaMethods.addAll(createStaticCreatorMethods(service, types)); + javaMethods.addAll(createStaticCreatorMethods(service, typeStore)); javaMethods.addAll( createConstructorMethods( service, - types, + typeStore, classMemberVarExprs, callableClassMemberVarExprs, protoMethodNameToDescriptorVarExprs)); @@ -416,8 +415,9 @@ private static List createClassMethods( } private static List createStaticCreatorMethods( - Service service, Map types) { - TypeNode creatorMethodReturnType = types.get(ClassNames.getGrpcServiceStubClassName(service)); + Service service, TypeStore typeStore) { + TypeNode creatorMethodReturnType = + typeStore.get(ClassNames.getGrpcServiceStubClassName(service)); Function, MethodDefinition.Builder> creatorMethodStarterFn = argList -> MethodDefinition.builder() @@ -438,12 +438,12 @@ private static List createStaticCreatorMethods( argList -> NewObjectExpr.builder().setType(creatorMethodReturnType).setArguments(argList).build(); - TypeNode stubSettingsType = types.get(ClassNames.getServiceStubSettingsClassName(service)); + TypeNode stubSettingsType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service)); VariableExpr settingsVarExpr = VariableExpr.withVariable( Variable.builder().setName("settings").setType(stubSettingsType).build()); - TypeNode clientContextType = STATIC_TYPES.get("ClientContext"); + TypeNode clientContextType = FIXED_TYPESTORE.get("ClientContext"); VariableExpr clientContextVarExpr = VariableExpr.withVariable( Variable.builder().setName("clientContext").setType(clientContextType).build()); @@ -452,7 +452,7 @@ private static List createStaticCreatorMethods( VariableExpr.withVariable( Variable.builder() .setName("callableFactory") - .setType(STATIC_TYPES.get("GrpcStubCallableFactory")) + .setType(FIXED_TYPESTORE.get("GrpcStubCallableFactory")) .build()); MethodInvocationExpr clientContextCreateMethodExpr = @@ -496,16 +496,16 @@ private static List createStaticCreatorMethods( private static List createConstructorMethods( Service service, - Map types, + TypeStore typeStore, Map classMemberVarExprs, Map callableClassMemberVarExprs, Map protoMethodNameToDescriptorVarExprs) { - TypeNode stubSettingsType = types.get(ClassNames.getServiceStubSettingsClassName(service)); + TypeNode stubSettingsType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service)); VariableExpr settingsVarExpr = VariableExpr.withVariable( Variable.builder().setName("settings").setType(stubSettingsType).build()); - TypeNode clientContextType = STATIC_TYPES.get("ClientContext"); + TypeNode clientContextType = FIXED_TYPESTORE.get("ClientContext"); VariableExpr clientContextVarExpr = VariableExpr.withVariable( Variable.builder().setName("clientContext").setType(clientContextType).build()); @@ -514,10 +514,10 @@ private static List createConstructorMethods( VariableExpr.withVariable( Variable.builder() .setName("callableFactory") - .setType(STATIC_TYPES.get("GrpcStubCallableFactory")) + .setType(FIXED_TYPESTORE.get("GrpcStubCallableFactory")) .build()); - TypeNode thisClassType = types.get(ClassNames.getGrpcServiceStubClassName(service)); + TypeNode thisClassType = typeStore.get(ClassNames.getGrpcServiceStubClassName(service)); TypeNode ioExceptionType = TypeNode.withReference(ConcreteReference.withClazz(IOException.class)); @@ -548,14 +548,15 @@ private static List createConstructorMethods( clientContextVarExpr, NewObjectExpr.builder() .setType( - types.get( + typeStore.get( ClassNames.getGrpcServiceCallableFactoryClassName(service))) .build()) .build()))); Expr thisExpr = ValueExpr.withValue( - ThisObjectValue.withType(types.get(ClassNames.getGrpcServiceStubClassName(service)))); + ThisObjectValue.withType( + typeStore.get(ClassNames.getGrpcServiceStubClassName(service)))); // Body of the second constructor method. List secondCtorStatements = new ArrayList<>(); List secondCtorExprs = new ArrayList<>(); @@ -576,7 +577,7 @@ private static List createConstructorMethods( operationsStubClassVarExpr.toBuilder().setExprReferenceExpr(thisExpr).build()) .setValueExpr( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("GrpcOperationsStub")) + .setStaticReferenceType(FIXED_TYPESTORE.get("GrpcOperationsStub")) .setMethodName("create") .setArguments(Arrays.asList(clientContextVarExpr, callableFactoryVarExpr)) .setReturnType(operationsStubClassVarExpr.type()) @@ -659,7 +660,7 @@ private static List createConstructorMethods( backgroundResourcesVarExpr.toBuilder().setExprReferenceExpr(thisExpr).build()) .setValueExpr( NewObjectExpr.builder() - .setType(STATIC_TYPES.get("BackgroundResourceAggregation")) + .setType(FIXED_TYPESTORE.get("BackgroundResourceAggregation")) .setArguments(Arrays.asList(getBackgroundResourcesMethodExpr)) .build()) .build()); @@ -680,7 +681,7 @@ private static Expr createTransportSettingsInitExpr( Method method, VariableExpr transportSettingsVarExpr, VariableExpr methodDescriptorVarExpr) { MethodInvocationExpr callSettingsBuilderExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("GrpcCallSettings")) + .setStaticReferenceType(FIXED_TYPESTORE.get("GrpcCallSettings")) .setGenerics(transportSettingsVarExpr.type().reference().generics()) .setMethodName("newBuilder") .build(); @@ -734,7 +735,7 @@ private static AnonymousClassExpr createRequestParamsExtractorAnonClass(Method m .setVariableExpr(paramsVarExpr.toBuilder().setIsDecl(true).build()) .setValueExpr( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("ImmutableMap")) + .setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")) .setMethodName("builder") .setReturnType(paramsVarType) .build()) @@ -989,7 +990,10 @@ private static List createStubOverrideMethods( VariableExpr.withVariable( Variable.builder().setName("duration").setType(TypeNode.LONG).build()), VariableExpr.withVariable( - Variable.builder().setName("unit").setType(STATIC_TYPES.get("TimeUnit")).build())); + Variable.builder() + .setName("unit") + .setType(FIXED_TYPESTORE.get("TimeUnit")) + .build())); javaMethods.add( methodMakerStarterFn .apply("awaitTermination") @@ -998,7 +1002,7 @@ private static List createStubOverrideMethods( awaitTerminationArgs.stream() .map(v -> v.toBuilder().setIsDecl(true).build()) .collect(Collectors.toList())) - .setThrowsExceptions(Arrays.asList(STATIC_TYPES.get("InterruptedException"))) + .setThrowsExceptions(Arrays.asList(FIXED_TYPESTORE.get("InterruptedException"))) .setReturnExpr( MethodInvocationExpr.builder() .setExprReferenceExpr(backgroundResourcesVarExpr) @@ -1013,7 +1017,7 @@ private static List createStubOverrideMethods( return javaMethods; } - private static Map createStaticTypes() { + private static TypeStore createStaticTypes() { List concreteClazzes = Arrays.asList( BackgroundResource.class, @@ -1036,58 +1040,41 @@ private static Map createStaticTypes() { ServerStreamingCallable.class, TimeUnit.class, UnaryCallable.class); - return concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); + return new TypeStore(concreteClazzes); } - private static Map createDynamicTypes(Service service, String stubPakkage) { - Map types = new HashMap<>(); - types.putAll( + private static TypeStore createDynamicTypes(Service service, String stubPakkage) { + TypeStore typeStore = new TypeStore(); + typeStore.putAll( + stubPakkage, Arrays.asList( - ClassNames.getGrpcServiceStubClassName(service), - ClassNames.getServiceStubSettingsClassName(service), - ClassNames.getServiceStubClassName(service), - ClassNames.getGrpcServiceCallableFactoryClassName(service)) - .stream() - .collect( - Collectors.toMap( - n -> n, - n -> - TypeNode.withReference( - VaporReference.builder().setName(n).setPakkage(stubPakkage).build())))); + ClassNames.getGrpcServiceStubClassName(service), + ClassNames.getServiceStubSettingsClassName(service), + ClassNames.getServiceStubClassName(service), + ClassNames.getGrpcServiceCallableFactoryClassName(service))); // Pagination types. - types.putAll( + typeStore.putAll( + service.pakkage(), service.methods().stream() .filter(m -> m.isPaged()) - .collect( - Collectors.toMap( - m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name()), - m -> - TypeNode.withReference( - VaporReference.builder() - .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) - .setPakkage(service.pakkage()) - .setEnclosingClassNames( - ClassNames.getServiceClientClassName(service)) - .setIsStaticImport(true) - .build())))); - return types; + .map(m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) + .collect(Collectors.toList()), + true, + ClassNames.getServiceClientClassName(service)); + return typeStore; } private static TypeNode getCallableType(Method protoMethod) { - TypeNode callableType = STATIC_TYPES.get("UnaryCallable"); + TypeNode callableType = FIXED_TYPESTORE.get("UnaryCallable"); switch (protoMethod.stream()) { case CLIENT: - callableType = STATIC_TYPES.get("ClientStreamingCallable"); + callableType = FIXED_TYPESTORE.get("ClientStreamingCallable"); break; case SERVER: - callableType = STATIC_TYPES.get("ServerStreamingCallable"); + callableType = FIXED_TYPESTORE.get("ServerStreamingCallable"); break; case BIDI: - callableType = STATIC_TYPES.get("BidiStreamingCallable"); + callableType = FIXED_TYPESTORE.get("BidiStreamingCallable"); break; case NONE: // Fall through diff --git a/src/main/java/com/google/api/generator/gapic/composer/MockServiceClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/MockServiceClassComposer.java index 1e1c00d5f4..c9af986535 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/MockServiceClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/MockServiceClassComposer.java @@ -27,9 +27,9 @@ import com.google.api.generator.engine.ast.ScopeNode; import com.google.api.generator.engine.ast.Statement; import com.google.api.generator.engine.ast.TypeNode; -import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; @@ -39,7 +39,6 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import javax.annotation.Generated; public class MockServiceClassComposer implements ClassComposer { @@ -54,7 +53,7 @@ public static MockServiceClassComposer instance() { @Override public GapicClass generate(Service service, Map ignore) { - Map types = createTypes(service); + TypeStore typeStore = createTypes(service); String className = ClassNames.getMockServiceClassName(service); GapicClass.Kind kind = Kind.TEST; String pakkage = service.pakkage(); @@ -62,77 +61,75 @@ public GapicClass generate(Service service, Map ignore) { ClassDefinition classDef = ClassDefinition.builder() .setPackageString(pakkage) - .setAnnotations(createClassAnnotations(types)) + .setAnnotations(createClassAnnotations(typeStore)) .setScope(ScopeNode.PUBLIC) .setName(className) - .setImplementsTypes(createClassImplements(types)) - .setStatements(createFieldDeclarations(service, types)) - .setMethods(createClassMethods(service, types)) + .setImplementsTypes(createClassImplements(typeStore)) + .setStatements(createFieldDeclarations(service, typeStore)) + .setMethods(createClassMethods(service, typeStore)) .build(); return GapicClass.create(kind, classDef); } - private static List createFieldDeclarations( - Service service, Map types) { + private static List createFieldDeclarations(Service service, TypeStore typeStore) { return Arrays.asList( ExprStatement.withExpr( VariableExpr.builder() - .setVariable(getServiceImplVariable(service, types)) + .setVariable(getServiceImplVariable(service, typeStore)) .setScope(ScopeNode.PRIVATE) .setIsFinal(true) .setIsDecl(true) .build())); } - private static List createClassAnnotations(Map types) { + private static List createClassAnnotations(TypeStore typeStore) { return Arrays.asList( - AnnotationNode.builder().setType(types.get("BetaApi")).build(), + AnnotationNode.builder().setType(typeStore.get("BetaApi")).build(), AnnotationNode.builder() - .setType(types.get("Generated")) + .setType(typeStore.get("Generated")) .setDescription("by gapic-generator-java") .build()); } - private static List createClassImplements(Map types) { - return Arrays.asList(types.get("MockGrpcService")); + private static List createClassImplements(TypeStore typeStore) { + return Arrays.asList(typeStore.get("MockGrpcService")); } - private static List createClassMethods( - Service service, Map types) { + private static List createClassMethods(Service service, TypeStore typeStore) { VariableExpr serviceImplVarExpr = - VariableExpr.withVariable(getServiceImplVariable(service, types)); + VariableExpr.withVariable(getServiceImplVariable(service, typeStore)); return Arrays.asList( - createConstructor(service, serviceImplVarExpr, types), - createGetRequestsMethod(serviceImplVarExpr, types), - createAddResponseMethod(serviceImplVarExpr, types), + createConstructor(service, serviceImplVarExpr, typeStore), + createGetRequestsMethod(serviceImplVarExpr, typeStore), + createAddResponseMethod(serviceImplVarExpr, typeStore), createAddExceptionMethod(serviceImplVarExpr), - createGetServiceDefinitionMethod(serviceImplVarExpr, types), + createGetServiceDefinitionMethod(serviceImplVarExpr, typeStore), createResetMethod(serviceImplVarExpr)); } private static MethodDefinition createConstructor( - Service service, VariableExpr serviceImplVarExpr, Map types) { + Service service, VariableExpr serviceImplVarExpr, TypeStore typeStore) { String mockImplName = ClassNames.getMockServiceImplClassName(service); Expr serviceImplAssignExpr = AssignmentExpr.builder() .setVariableExpr(serviceImplVarExpr) - .setValueExpr(NewObjectExpr.builder().setType(types.get(mockImplName)).build()) + .setValueExpr(NewObjectExpr.builder().setType(typeStore.get(mockImplName)).build()) .build(); return MethodDefinition.constructorBuilder() .setScope(ScopeNode.PUBLIC) .setBody(Arrays.asList(ExprStatement.withExpr(serviceImplAssignExpr))) - .setReturnType(types.get(ClassNames.getMockServiceClassName(service))) + .setReturnType(typeStore.get(ClassNames.getMockServiceClassName(service))) .build(); } private static MethodDefinition createGetRequestsMethod( - VariableExpr serviceImplVarExpr, Map types) { + VariableExpr serviceImplVarExpr, TypeStore typeStore) { TypeNode returnType = TypeNode.withReference( ConcreteReference.builder() .setClazz(List.class) - .setGenerics(Arrays.asList(types.get("AbstractMessage").reference())) + .setGenerics(Arrays.asList(typeStore.get("AbstractMessage").reference())) .build()); String methodName = "getRequests"; Expr returnExpr = @@ -151,11 +148,14 @@ private static MethodDefinition createGetRequestsMethod( } private static MethodDefinition createAddResponseMethod( - VariableExpr serviceImplVarExpr, Map types) { + VariableExpr serviceImplVarExpr, TypeStore typeStore) { String methodName = "addResponse"; VariableExpr responseArgExpr = VariableExpr.withVariable( - Variable.builder().setName("response").setType(types.get("AbstractMessage")).build()); + Variable.builder() + .setName("response") + .setType(typeStore.get("AbstractMessage")) + .build()); Expr methodInvocationExpr = MethodInvocationExpr.builder() @@ -198,8 +198,8 @@ private static MethodDefinition createAddExceptionMethod(VariableExpr serviceImp } private static MethodDefinition createGetServiceDefinitionMethod( - VariableExpr serviceImplVarExpr, Map types) { - TypeNode returnType = types.get("ServerServiceDefinition"); + VariableExpr serviceImplVarExpr, TypeStore typeStore) { + TypeNode returnType = typeStore.get("ServerServiceDefinition"); Expr methodInvocationExpr = MethodInvocationExpr.builder() .setMethodName("bindService") @@ -232,45 +232,25 @@ private static MethodDefinition createResetMethod(VariableExpr serviceImplVarExp .build(); } - private static Map createTypes(Service service) { + private static TypeStore createTypes(Service service) { List concreteClazzes = Arrays.asList( AbstractMessage.class, BetaApi.class, Generated.class, ServerServiceDefinition.class); - Map types = - concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); - - // Vapor dependency types. - String mockGrpcServiceName = "MockGrpcService"; - types.put( - mockGrpcServiceName, - TypeNode.withReference( - VaporReference.builder() - .setName(mockGrpcServiceName) - .setPakkage("com.google.api.gax.grpc.testing") - .build())); - // Vapor same-package deps. - String mockImplName = ClassNames.getMockServiceImplClassName(service); - types.put( - mockImplName, - TypeNode.withReference( - VaporReference.builder().setName(mockImplName).setPakkage(service.pakkage()).build())); + TypeStore typeStore = new TypeStore(concreteClazzes); - String className = ClassNames.getMockServiceClassName(service); - types.put( - className, - TypeNode.withReference( - VaporReference.builder().setName(className).setPakkage(service.pakkage()).build())); - return types; + typeStore.put("com.google.api.gax.grpc.testing", "MockGrpcService"); + typeStore.putAll( + service.pakkage(), + Arrays.asList( + ClassNames.getMockServiceImplClassName(service), + ClassNames.getMockServiceClassName(service))); + return typeStore; } - private static Variable getServiceImplVariable(Service service, Map types) { + private static Variable getServiceImplVariable(Service service, TypeStore typeStore) { return Variable.builder() .setName(SERVICE_IMPL_VAR_NAME) - .setType(types.get(ClassNames.getMockServiceImplClassName(service))) + .setType(typeStore.get(ClassNames.getMockServiceImplClassName(service))) .build(); } } diff --git a/src/main/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposer.java index 565f6f2030..ab7e03a52a 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposer.java @@ -37,6 +37,7 @@ import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; @@ -50,7 +51,6 @@ import io.grpc.stub.StreamObserver; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -61,7 +61,7 @@ public class MockServiceImplClassComposer implements ClassComposer { private static final MockServiceImplClassComposer INSTANCE = new MockServiceImplClassComposer(); private static final String IMPL_BASE_PATTERN = "%sImplBase"; - private static final Map staticTypes = createStaticTypes(); + private static final TypeStore FIXED_TYPESTORE = createStaticTypes(); private static final VariableExpr requestsVarExpr = VariableExpr.withVariable( Variable.builder() @@ -71,7 +71,7 @@ public class MockServiceImplClassComposer implements ClassComposer { ConcreteReference.builder() .setClazz(List.class) .setGenerics( - Arrays.asList(staticTypes.get("AbstractMessage").reference())) + Arrays.asList(FIXED_TYPESTORE.get("AbstractMessage").reference())) .build())) .build()); private static final VariableExpr responsesVarExpr = @@ -94,7 +94,7 @@ public static MockServiceImplClassComposer instance() { @Override public GapicClass generate(Service service, Map ignore) { - Map types = createDynamicTypes(service); + TypeStore typeStore = createDynamicTypes(service); String className = ClassNames.getMockServiceImplClassName(service); GapicClass.Kind kind = Kind.TEST; String pakkage = service.pakkage(); @@ -105,9 +105,9 @@ public GapicClass generate(Service service, Map ignore) { .setAnnotations(createClassAnnotations()) .setScope(ScopeNode.PUBLIC) .setName(className) - .setExtendsType(types.get(String.format(IMPL_BASE_PATTERN, service.name()))) + .setExtendsType(typeStore.get(String.format(IMPL_BASE_PATTERN, service.name()))) .setStatements(createFieldDeclarations()) - .setMethods(createClassMethods(service, types)) + .setMethods(createClassMethods(service, typeStore)) .build(); return GapicClass.create(kind, classDef); } @@ -122,17 +122,17 @@ private static List createFieldDeclarations() { private static List createClassAnnotations() { return Arrays.asList( - AnnotationNode.builder().setType(staticTypes.get("BetaApi")).build(), + AnnotationNode.builder().setType(FIXED_TYPESTORE.get("BetaApi")).build(), AnnotationNode.builder() - .setType(staticTypes.get("Generated")) + .setType(FIXED_TYPESTORE.get("Generated")) .setDescription("by gapic-generator-java") .build()); } - private static List createClassMethods( - Service service, Map types) { + private static List createClassMethods(Service service, TypeStore typeStore) { List javaMethods = new ArrayList<>(); - javaMethods.add(createConstructor(types.get(ClassNames.getMockServiceImplClassName(service)))); + javaMethods.add( + createConstructor(typeStore.get(ClassNames.getMockServiceImplClassName(service)))); javaMethods.add(createGetRequestsMethod()); javaMethods.add(createAddResponseMethod()); javaMethods.add(createSetResponsesMethod(service)); @@ -164,7 +164,7 @@ private static MethodDefinition createAddResponseMethod() { VariableExpr.withVariable( Variable.builder() .setName("response") - .setType(staticTypes.get("AbstractMessage")) + .setType(FIXED_TYPESTORE.get("AbstractMessage")) .build()); Expr methodInvocationExpr = MethodInvocationExpr.builder() @@ -191,7 +191,7 @@ private static MethodDefinition createSetResponsesMethod(Service service) { ConcreteReference.builder() .setClazz(List.class) .setGenerics( - Arrays.asList(staticTypes.get("AbstractMessage").reference())) + Arrays.asList(FIXED_TYPESTORE.get("AbstractMessage").reference())) .build())) .build()); Expr responseAssignExpr = @@ -528,7 +528,7 @@ private static Statement createHandleObjectStatement( .build(); } - private static Map createStaticTypes() { + private static TypeStore createStaticTypes() { List concreteClazzes = Arrays.asList( AbstractMessage.class, @@ -539,36 +539,17 @@ private static Map createStaticTypes() { Operation.class, ServerServiceDefinition.class, StreamObserver.class); - return concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); + return new TypeStore(concreteClazzes); } - private static Map createDynamicTypes(Service service) { - Map types = new HashMap<>(); - // Vapor dependency types. - String implBase = String.format(IMPL_BASE_PATTERN, service.name()); - types.put( - implBase, - TypeNode.withReference( - VaporReference.builder() - .setName(implBase) - // Hack: This should be a nested class and perhaps a static import or something. - .setPakkage( - String.format("%s.%sGrpc", service.originalJavaPackage(), service.name())) - .build())); - String className = ClassNames.getMockServiceImplClassName(service); - types.put( - className, - TypeNode.withReference( - VaporReference.builder() - .setName(className) - // Hack: This should be a nested class and perhaps a static import or something. - .setPakkage(service.pakkage()) - .build())); - return types; + private static TypeStore createDynamicTypes(Service service) { + TypeStore typeStore = new TypeStore(); + // Hack: This two should be nested classes and perhaps a static import or something. + typeStore.put( + String.format("%s.%sGrpc", service.originalJavaPackage(), service.name()), + String.format(IMPL_BASE_PATTERN, service.name())); + typeStore.put(service.pakkage(), ClassNames.getMockServiceImplClassName(service)); + return typeStore; } private static TypeNode getThisClassType(Service service) { diff --git a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java index a791064865..2270c2b3be 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java @@ -44,9 +44,9 @@ import com.google.api.generator.engine.ast.ThrowExpr; import com.google.api.generator.engine.ast.TypeNode; import com.google.api.generator.engine.ast.ValueExpr; -import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.utils.JavaStyle; @@ -77,7 +77,7 @@ public class ResourceNameHelperClassComposer { private static final ResourceNameHelperClassComposer INSTANCE = new ResourceNameHelperClassComposer(); - private static final Map STATIC_TYPES = createStaticTypes(); + private static final TypeStore FIXED_TYPESTORE = createStaticTypes(); private static Map FIXED_CLASS_VARS = createFixedClassMemberVariables(); @@ -90,7 +90,7 @@ public static ResourceNameHelperClassComposer instance() { public GapicClass generate(ResourceName resourceName) { List> tokenHierarchies = ResourceNameTokenizer.parseTokenHierarchy(resourceName.patterns()); - Map types = createDynamicTypes(resourceName, tokenHierarchies); + TypeStore typeStore = createDynamicTypes(resourceName, tokenHierarchies); List templateFinalVarExprs = createTemplateClassMembers(tokenHierarchies); Map patternTokenVarExprs = createPatternTokenClassMembers(tokenHierarchies); @@ -129,10 +129,10 @@ public GapicClass generate(ResourceName resourceName) { templateFinalVarExprs, patternTokenVarExprs, tokenHierarchies, - types)) + typeStore)) .setNestedClasses( createNestedBuilderClasses( - resourceName, tokenHierarchies, templateFinalVarExprs, types)) + resourceName, tokenHierarchies, templateFinalVarExprs, typeStore)) .build(); return GapicClass.create(GapicClass.Kind.PROTO, classDef); } @@ -140,13 +140,13 @@ public GapicClass generate(ResourceName resourceName) { private static List createClassAnnotations() { return Arrays.asList( AnnotationNode.builder() - .setType(STATIC_TYPES.get("Generated")) + .setType(FIXED_TYPESTORE.get("Generated")) .setDescription("by gapic-generator-java") .build()); } private static List createImplementsTypes() { - return Arrays.asList(STATIC_TYPES.get("ResourceName")); + return Arrays.asList(FIXED_TYPESTORE.get("ResourceName")); } private static List createTemplateClassMembers( @@ -157,7 +157,7 @@ private static List createTemplateClassMembers( VariableExpr.withVariable( Variable.builder() .setName(concatToUpperSnakeCaseName(ts)) - .setType(STATIC_TYPES.get("PathTemplate")) + .setType(FIXED_TYPESTORE.get("PathTemplate")) .build())) .collect(Collectors.toList()); } @@ -200,11 +200,11 @@ private static List createClassStatements( .build(); Expr createWithoutUrlEncodingExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("PathTemplate")) + .setStaticReferenceType(FIXED_TYPESTORE.get("PathTemplate")) .setMethodName("createWithoutUrlEncoding") .setArguments( Arrays.asList(ValueExpr.withValue(StringObjectValue.withValue(patterns.get(i))))) - .setReturnType(STATIC_TYPES.get("PathTemplate")) + .setReturnType(FIXED_TYPESTORE.get("PathTemplate")) .build(); memberVars.add( AssignmentExpr.builder() @@ -246,32 +246,38 @@ private static List createClassMethods( List templateFinalVarExprs, Map patternTokenVarExprs, List> tokenHierarchies, - Map types) { + TypeStore typeStore) { // TODO(summerji): Add equals and hashCode overrides. List javaMethods = new ArrayList<>(); javaMethods.addAll( createConstructorMethods( - resourceName, templateFinalVarExprs, patternTokenVarExprs, tokenHierarchies, types)); + resourceName, + templateFinalVarExprs, + patternTokenVarExprs, + tokenHierarchies, + typeStore)); javaMethods.addAll(createTokenGetterMethods(patternTokenVarExprs, tokenHierarchies)); - javaMethods.addAll(createBuilderCreatorMethods(resourceName, tokenHierarchies, types)); + javaMethods.addAll(createBuilderCreatorMethods(resourceName, tokenHierarchies, typeStore)); javaMethods.addAll( - createOfCreatorMethods(resourceName, patternTokenVarExprs, tokenHierarchies, types)); + createOfCreatorMethods(resourceName, patternTokenVarExprs, tokenHierarchies, typeStore)); javaMethods.addAll( - createFormatCreatorMethods(resourceName, patternTokenVarExprs, tokenHierarchies, types)); + createFormatCreatorMethods( + resourceName, patternTokenVarExprs, tokenHierarchies, typeStore)); javaMethods.addAll( createParsingAndSplittingMethods( - resourceName, templateFinalVarExprs, tokenHierarchies, types)); + resourceName, templateFinalVarExprs, tokenHierarchies, typeStore)); javaMethods.addAll( - createFieldValueGetterMethods(resourceName, patternTokenVarExprs, tokenHierarchies, types)); + createFieldValueGetterMethods( + resourceName, patternTokenVarExprs, tokenHierarchies, typeStore)); javaMethods.add( createToStringMethod(templateFinalVarExprs, patternTokenVarExprs, tokenHierarchies)); - javaMethods.add(createEqualsMethod(resourceName, tokenHierarchies, types)); + javaMethods.add(createEqualsMethod(resourceName, tokenHierarchies, typeStore)); javaMethods.add(createHashCodeMethod(tokenHierarchies)); return javaMethods; } @@ -281,9 +287,9 @@ private static List createConstructorMethods( List templateFinalVarExprs, Map patternTokenVarExprs, List> tokenHierarchies, - Map types) { + TypeStore typeStore) { String thisClassName = getThisClassName(resourceName); - TypeNode thisClassType = types.get(thisClassName); + TypeNode thisClassType = typeStore.get(thisClassName); boolean hasVariants = tokenHierarchies.size() > 1; List javaMethods = new ArrayList<>(); @@ -313,13 +319,13 @@ private static List createConstructorMethods( for (int i = 0; i < tokenHierarchies.size(); i++) { List tokens = tokenHierarchies.get(i); List bodyExprs = new ArrayList<>(); - TypeNode argType = getBuilderType(types, tokenHierarchies, i); + TypeNode argType = getBuilderType(typeStore, tokenHierarchies, i); VariableExpr builderArgExpr = VariableExpr.withVariable(Variable.builder().setName("builder").setType(argType).build()); for (String token : tokens) { MethodInvocationExpr checkNotNullExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Preconditions")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Preconditions")) .setMethodName("checkNotNull") .setReturnType(TypeNode.STRING) .setArguments( @@ -384,12 +390,12 @@ private static List createTokenGetterMethods( } private static List createBuilderCreatorMethods( - ResourceName resourceName, List> tokenHierarchies, Map types) { + ResourceName resourceName, List> tokenHierarchies, TypeStore typeStore) { List javaMethods = new ArrayList<>(); String newMethodNameFormat = "new%s"; AnnotationNode betaAnnotation = AnnotationNode.builder() - .setType(STATIC_TYPES.get("BetaApi")) + .setType(FIXED_TYPESTORE.get("BetaApi")) .setDescription( "The per-pattern Builders are not stable yet and may be changed in the future.") .build(); @@ -398,7 +404,7 @@ private static List createBuilderCreatorMethods( // Create the newBuilder and variation methods here. // Variation example: newProjectLocationAutoscalingPolicyBuilder(). for (int i = 0; i < tokenHierarchies.size(); i++) { - final TypeNode returnType = getBuilderType(types, tokenHierarchies, i); + final TypeNode returnType = getBuilderType(typeStore, tokenHierarchies, i); final Expr returnExpr = NewObjectExpr.withType(returnType); Function methodDefStarterFn = @@ -429,8 +435,8 @@ private static List createBuilderCreatorMethods( // TODO(miraleung, v2): It seems weird that we currently generate a toBuilder method only for // the default class, and none for the Builder variants. - TypeNode toBuilderReturnType = getBuilderType(types, tokenHierarchies, 0); - TypeNode thisClassType = types.get(getThisClassName(resourceName)); + TypeNode toBuilderReturnType = getBuilderType(typeStore, tokenHierarchies, 0); + TypeNode thisClassType = typeStore.get(getThisClassName(resourceName)); javaMethods.add( MethodDefinition.builder() .setScope(ScopeNode.PUBLIC) @@ -450,25 +456,25 @@ private static List createOfCreatorMethods( ResourceName resourceName, Map patternTokenVarExprs, List> tokenHierarchies, - Map types) { + TypeStore typeStore) { return createOfOrFormatMethodHelper( - resourceName, patternTokenVarExprs, tokenHierarchies, types, /*isFormatMethod=*/ false); + resourceName, patternTokenVarExprs, tokenHierarchies, typeStore, /*isFormatMethod=*/ false); } private static List createFormatCreatorMethods( ResourceName resourceName, Map patternTokenVarExprs, List> tokenHierarchies, - Map types) { + TypeStore typeStore) { return createOfOrFormatMethodHelper( - resourceName, patternTokenVarExprs, tokenHierarchies, types, /*isFormatMethod=*/ true); + resourceName, patternTokenVarExprs, tokenHierarchies, typeStore, /*isFormatMethod=*/ true); } private static List createOfOrFormatMethodHelper( ResourceName resourceName, Map patternTokenVarExprs, List> tokenHierarchies, - Map types, + TypeStore typeStore, boolean isFormatMethod) { List javaMethods = new ArrayList<>(); String methodNameFormat = isFormatMethod ? "format%s" : "of%s"; @@ -478,7 +484,7 @@ private static List createOfOrFormatMethodHelper( String toStringMethodName = "toString"; AnnotationNode betaAnnotation = AnnotationNode.builder() - .setType(STATIC_TYPES.get("BetaApi")) + .setType(FIXED_TYPESTORE.get("BetaApi")) .setDescription( String.format( "The static %s methods are not stable yet and may be changed in the future.", @@ -486,7 +492,7 @@ private static List createOfOrFormatMethodHelper( .build(); List annotations = Arrays.asList(betaAnnotation); - TypeNode thisClassType = types.get(getThisClassName(resourceName)); + TypeNode thisClassType = typeStore.get(getThisClassName(resourceName)); TypeNode returnType = isFormatMethod ? TypeNode.STRING : thisClassType; // Create the newBuilder and variation methods here. // Variation example: newProjectLocationAutoscalingPolicyBuilder(). @@ -569,11 +575,11 @@ private static List createParsingAndSplittingMethods( ResourceName resourceName, List templateFinalVarExprs, List> tokenHierarchies, - Map types) { + TypeStore typeStore) { List javaMethods = new ArrayList<>(); - TypeNode thisClassType = types.get(getThisClassName(resourceName)); + TypeNode thisClassType = typeStore.get(getThisClassName(resourceName)); javaMethods.add( - createParseMethod(thisClassType, templateFinalVarExprs, tokenHierarchies, types)); + createParseMethod(thisClassType, templateFinalVarExprs, tokenHierarchies, typeStore)); javaMethods.add(createParseListMethod(thisClassType)); javaMethods.add(createToStringListMethod(thisClassType)); javaMethods.add(createIsParseableFromMethod(templateFinalVarExprs)); @@ -585,7 +591,7 @@ private static MethodDefinition createParseMethod( TypeNode thisClassType, List templateFinalVarExprs, List> tokenHierarchies, - Map types) { + TypeStore typeStore) { String formattedStringArgName = "formattedString"; VariableExpr formattedStringArgExpr = VariableExpr.withVariable( @@ -736,7 +742,7 @@ private static MethodDefinition createParseMethod( body.add( ExprStatement.withExpr( ThrowExpr.builder() - .setType(STATIC_TYPES.get("ValidationException")) + .setType(FIXED_TYPESTORE.get("ValidationException")) .setMessageExpr(exceptionMessageString) .build())); return MethodDefinition.builder() @@ -946,9 +952,9 @@ private static List createFieldValueGetterMethods( ResourceName resourceName, Map patternTokenVarExprs, List> tokenHierarchies, - Map types) { + TypeStore typeStore) { List javaMethods = new ArrayList<>(); - TypeNode thisClassType = types.get(getThisClassName(resourceName)); + TypeNode thisClassType = typeStore.get(getThisClassName(resourceName)); javaMethods.add( createGetFieldValuesMapMethod( resourceName, thisClassType, patternTokenVarExprs, tokenHierarchies)); @@ -978,7 +984,7 @@ private static MethodDefinition createGetFieldValuesMapMethod( .setVariableExpr(fieldMapBuilderVarExpr.toBuilder().setIsDecl(true).build()) .setValueExpr( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("ImmutableMap")) + .setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")) .setMethodName("builder") .setReturnType(mapBuilderType) .build()) @@ -1147,12 +1153,12 @@ private static MethodDefinition createToStringMethod( } private static MethodDefinition createEqualsMethod( - ResourceName resourceName, List> tokenHierarchies, Map types) { + ResourceName resourceName, List> tokenHierarchies, TypeStore typeStore) { // Create method definition variables. Variable oVariable = Variable.builder().setType(TypeNode.OBJECT).setName("o").build(); VariableExpr argVarExpr = VariableExpr.builder().setIsDecl(false).setVariable(oVariable).build(); - TypeNode thisClassType = types.get(getThisClassName(resourceName)); + TypeNode thisClassType = typeStore.get(getThisClassName(resourceName)); ValueExpr thisValueExpr = ValueExpr.withValue(ThisObjectValue.withType(thisClassType)); ValueExpr trueValueExpr = ValueExpr.withValue( @@ -1250,7 +1256,7 @@ private static MethodInvocationExpr createObjectsEqualsForTokenMethodExpr( VariableExpr varThatExpr = VariableExpr.builder().setVariable(tokenVar).setExprReferenceExpr(thatExpr).build(); return MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Objects")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Objects")) .setMethodName("equals") .setArguments(Arrays.asList(varThisExpr, varThatExpr)) .setReturnType(TypeNode.BOOLEAN) @@ -1319,7 +1325,7 @@ private static MethodInvocationExpr createObjectsHashCodeForVarMethod(VariableEx // code: Objects.hashCode(varExpr) return MethodInvocationExpr.builder() .setMethodName("hashCode") - .setStaticReferenceType(STATIC_TYPES.get("Objects")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Objects")) .setArguments(varExpr) .setReturnType(TypeNode.INT) .build(); @@ -1329,9 +1335,9 @@ private static List createNestedBuilderClasses( ResourceName resourceName, List> tokenHierarchies, List templateFinalVarExprs, - Map types) { + TypeStore typeStore) { String thisClassName = getThisClassName(resourceName); - TypeNode outerThisClassType = types.get(thisClassName); + TypeNode outerThisClassType = typeStore.get(thisClassName); boolean hasVariants = tokenHierarchies.size() > 1; return IntStream.range(0, tokenHierarchies.size()) .mapToObj( @@ -1341,7 +1347,7 @@ private static List createNestedBuilderClasses( tokenHierarchies.get(i), templateFinalVarExprs.get(i), resourceName.patterns().get(i), - types, + typeStore, hasVariants, i == 0)) .collect(Collectors.toList()); @@ -1352,7 +1358,7 @@ private static ClassDefinition createNestedBuilderClass( List tokens, VariableExpr templateFinalVarExpr, String resourceNamePattern, - Map types, + TypeStore typeStore, boolean hasVariants, boolean isDefaultClass) { String className = isDefaultClass ? "Builder" : getBuilderTypeName(tokens); @@ -1377,7 +1383,7 @@ private static ClassDefinition createNestedBuilderClass( // Constructor. List nestedClassMethods = new ArrayList<>(); - TypeNode thisClassType = types.get(className); + TypeNode thisClassType = typeStore.get(className); MethodDefinition ctor = MethodDefinition.constructorBuilder() .setScope(ScopeNode.PROTECTED) @@ -1442,7 +1448,7 @@ private static ClassDefinition createNestedBuilderClass( // TODO(miraleung): Use eq operator instead. MethodInvocationExpr equalsCheckExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Objects")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Objects")) .setMethodName("equals") .setArguments( FIXED_CLASS_VARS @@ -1455,7 +1461,7 @@ private static ClassDefinition createNestedBuilderClass( builderCtorBodyExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Preconditions")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Preconditions")) .setMethodName("checkArgument") .setArguments( equalsCheckExpr, @@ -1509,7 +1515,7 @@ private static ClassDefinition createNestedBuilderClass( // Return the class. AnnotationNode betaAnnotation = AnnotationNode.builder() - .setType(STATIC_TYPES.get("BetaApi")) + .setType(FIXED_TYPESTORE.get("BetaApi")) .setDescription( "The per-pattern Builders are not stable yet and may be changed in the future.") .build(); @@ -1531,7 +1537,7 @@ private static ClassDefinition createNestedBuilderClass( .build(); } - private static Map createStaticTypes() { + private static TypeStore createStaticTypes() { List concreteClazzes = Arrays.asList( ArrayList.class, @@ -1545,51 +1551,24 @@ private static Map createStaticTypes() { Preconditions.class, com.google.api.resourcenames.ResourceName.class, ValidationException.class); - return concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); + return new TypeStore(concreteClazzes); } - private static Map createDynamicTypes( + private static TypeStore createDynamicTypes( ResourceName resourceName, List> tokenHierarchies) { String thisClassName = getThisClassName(resourceName); - Map dynamicTypes = new HashMap<>(); - dynamicTypes.put( - thisClassName, - TypeNode.withReference( - VaporReference.builder() - .setName(thisClassName) - .setPakkage(resourceName.pakkage()) - .build())); - dynamicTypes.put( - "Builder", - TypeNode.withReference( - VaporReference.builder() - .setName("Builder") - .setPakkage(resourceName.pakkage()) - .setEnclosingClassNames(thisClassName) - .setIsStaticImport(true) - .build())); + TypeStore typeStore = new TypeStore(); + typeStore.put(resourceName.pakkage(), thisClassName); + typeStore.put(resourceName.pakkage(), "Builder", true, thisClassName); if (tokenHierarchies.size() > 1) { - dynamicTypes.putAll( + typeStore.putAll( + resourceName.pakkage(), tokenHierarchies.subList(1, tokenHierarchies.size()).stream() .map(ts -> getBuilderTypeName(ts)) - .collect( - Collectors.toMap( - s -> s, - s -> - TypeNode.withReference( - VaporReference.builder() - .setName(s) - .setPakkage(resourceName.pakkage()) - .setEnclosingClassNames(thisClassName) - .setIsStaticImport(true) - .build())))); + .collect(Collectors.toList())); } - return dynamicTypes; + return typeStore; } private static Map createFixedClassMemberVariables() { @@ -1624,10 +1603,10 @@ private static String getBuilderTypeName(List tokens) { } private static TypeNode getBuilderType( - Map types, List> tokenHierarchies, int index) { + TypeStore typeStore, List> tokenHierarchies, int index) { return index == 0 - ? types.get("Builder") - : types.get(getBuilderTypeName(tokenHierarchies, index)); + ? typeStore.get("Builder") + : typeStore.get(getBuilderTypeName(tokenHierarchies, index)); } @VisibleForTesting diff --git a/src/main/java/com/google/api/generator/gapic/composer/RetrySettingsComposer.java b/src/main/java/com/google/api/generator/gapic/composer/RetrySettingsComposer.java index e2d0cb4080..0118d43eb1 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/RetrySettingsComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/RetrySettingsComposer.java @@ -36,6 +36,7 @@ import com.google.api.generator.engine.ast.ValueExpr; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.GapicBatchingSettings; import com.google.api.generator.gapic.model.GapicLroRetrySettings; import com.google.api.generator.gapic.model.GapicRetrySettings; @@ -60,7 +61,7 @@ import java.util.stream.Collectors; public class RetrySettingsComposer { - private static final Map STATIC_TYPES = createStaticTypes(); + private static final TypeStore FIXED_TYPESTORE = createStaticTypes(); private static final TypeNode STATUS_CODE_CODE_TYPE = TypeNode.withReference(ConcreteReference.withClazz(StatusCode.Code.class)); @@ -89,7 +90,7 @@ public static BlockStatement createRetryParamDefinitionsBlock( VariableExpr settingsVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(STATIC_TYPES.get("RetrySettings")) + .setType(FIXED_TYPESTORE.get("RetrySettings")) .setName("settings") .build()); @@ -99,7 +100,7 @@ public static BlockStatement createRetryParamDefinitionsBlock( .setVariableExpr(definitionsVarExpr.toBuilder().setIsDecl(true).build()) .setValueExpr( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("ImmutableMap")) + .setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")) .setMethodName("builder") .setReturnType(definitionsVarExpr.type()) .build()) @@ -162,7 +163,7 @@ public static BlockStatement createRetryCodesDefinitionsBlock( .setVariableExpr(definitionsVarExpr.toBuilder().setIsDecl(true).build()) .setValueExpr( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("ImmutableMap")) + .setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")) .setMethodName("builder") .setReturnType(definitionsVarExpr.type()) .build()) @@ -264,11 +265,11 @@ public static Expr createLroSettingsBuilderExpr( // Argument for setInitialCallSettings. Expr unaryCallSettingsExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("UnaryCallSettings")) + .setStaticReferenceType(FIXED_TYPESTORE.get("UnaryCallSettings")) .setGenerics( Arrays.asList( method.inputType().reference(), - STATIC_TYPES.get("OperationSnapshot").reference())) + FIXED_TYPESTORE.get("OperationSnapshot").reference())) .setMethodName("newUnaryCallSettingsBuilder") .build(); unaryCallSettingsExpr = @@ -353,7 +354,7 @@ public static Expr createLroSettingsBuilderExpr( Expr lroRetrySettingsExpr = createLroRetrySettingsExpr(service, method, serviceConfig); Expr pollAlgoExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("OperationTimedPollAlgorithm")) + .setStaticReferenceType(FIXED_TYPESTORE.get("OperationTimedPollAlgorithm")) .setMethodName("create") .setArguments(lroRetrySettingsExpr) .build(); @@ -375,7 +376,7 @@ public static Expr createBatchingBuilderSettingsExpr( Expr batchingSettingsBuilderExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("BatchingSettings")) + .setStaticReferenceType(FIXED_TYPESTORE.get("BatchingSettings")) .setMethodName("newBuilder") .build(); @@ -404,7 +405,7 @@ public static Expr createBatchingBuilderSettingsExpr( // FlowControlSettings. Expr flowControlSettingsExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("FlowControlSettings")) + .setStaticReferenceType(FIXED_TYPESTORE.get("FlowControlSettings")) .setMethodName("newBuilder") .build(); if (batchingSettings.flowControlElementLimit() != null) { @@ -429,7 +430,7 @@ public static Expr createBatchingBuilderSettingsExpr( .setMethodName("setLimitExceededBehavior") .setArguments( EnumRefExpr.builder() - .setType(STATIC_TYPES.get("LimitExceededBehavior")) + .setType(FIXED_TYPESTORE.get("LimitExceededBehavior")) .setName( JavaStyle.toUpperCamelCase( batchingSettings @@ -476,7 +477,7 @@ private static Expr createRetryCodeDefinitionExpr( // ImmutableSet.copYOf(Lists.newArrayList()));` MethodInvocationExpr codeListExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Lists")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Lists")) .setGenerics(Arrays.asList(STATUS_CODE_CODE_TYPE.reference())) .setMethodName("newArrayList") .setArguments( @@ -487,7 +488,7 @@ private static Expr createRetryCodeDefinitionExpr( MethodInvocationExpr codeSetExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("ImmutableSet")) + .setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableSet")) .setMethodName("copyOf") .setArguments(codeListExpr) .build(); @@ -505,7 +506,7 @@ private static List createRetrySettingsExprs( VariableExpr definitionsVarExpr) { Expr settingsBuilderExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("RetrySettings")) + .setStaticReferenceType(FIXED_TYPESTORE.get("RetrySettings")) .setMethodName("newBuilder") .build(); @@ -597,7 +598,7 @@ private static Expr createLroRetrySettingsExpr( Service service, Method method, GapicServiceConfig serviceConfig) { Expr lroRetrySettingsExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("RetrySettings")) + .setStaticReferenceType(FIXED_TYPESTORE.get("RetrySettings")) .setMethodName("newBuilder") .build(); @@ -639,7 +640,7 @@ private static Expr createLroRetrySettingsExpr( .build(); Expr zeroDurationExpr = - EnumRefExpr.builder().setType(STATIC_TYPES.get("Duration")).setName("ZERO").build(); + EnumRefExpr.builder().setType(FIXED_TYPESTORE.get("Duration")).setName("ZERO").build(); // TODO(miraleung): Add an "// ignored" comment here. lroRetrySettingsExpr = MethodInvocationExpr.builder() @@ -710,13 +711,13 @@ private static ValueExpr toValExpr(Duration duration) { private static MethodInvocationExpr createDurationOfMillisExpr(ValueExpr valExpr) { return MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Duration")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Duration")) .setMethodName("ofMillis") .setArguments(valExpr) .build(); } - private static Map createStaticTypes() { + private static TypeStore createStaticTypes() { List concreteClazzes = Arrays.asList( BatchingSettings.class, @@ -732,10 +733,6 @@ private static Map createStaticTypes() { RetrySettings.class, StatusCode.class, UnaryCallSettings.class); - return concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); + return new TypeStore(concreteClazzes); } } diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java index 6e3e7fc76c..3436257a60 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java @@ -51,9 +51,9 @@ import com.google.api.generator.engine.ast.ThisObjectValue; import com.google.api.generator.engine.ast.TypeNode; import com.google.api.generator.engine.ast.ValueExpr; -import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.Field; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; @@ -110,7 +110,7 @@ public static ServiceClientClassComposer instance() { @Override public GapicClass generate(Service service, Map messageTypes) { - Map types = createTypes(service, messageTypes); + TypeStore typeStore = createTypes(service, messageTypes); String className = ClassNames.getServiceClientClassName(service); GapicClass.Kind kind = Kind.MAIN; String pakkage = service.pakkage(); @@ -121,44 +121,44 @@ public GapicClass generate(Service service, Map messageTypes) { .setHeaderCommentStatements( ServiceClientCommentComposer.createClassHeaderComments( service, - types.get(ClassNames.getServiceClientClassName(service)), - types.get(ClassNames.getServiceSettingsClassName(service)))) + typeStore.get(ClassNames.getServiceClientClassName(service)), + typeStore.get(ClassNames.getServiceSettingsClassName(service)))) .setPackageString(pakkage) - .setAnnotations(createClassAnnotations(types)) + .setAnnotations(createClassAnnotations(typeStore)) .setScope(ScopeNode.PUBLIC) .setName(className) - .setImplementsTypes(createClassImplements(types)) - .setStatements(createFieldDeclarations(service, types, hasLroClient)) - .setMethods(createClassMethods(service, messageTypes, types, hasLroClient)) - .setNestedClasses(createNestedPagingClasses(service, messageTypes, types)) + .setImplementsTypes(createClassImplements(typeStore)) + .setStatements(createFieldDeclarations(service, typeStore, hasLroClient)) + .setMethods(createClassMethods(service, messageTypes, typeStore, hasLroClient)) + .setNestedClasses(createNestedPagingClasses(service, messageTypes, typeStore)) .build(); return GapicClass.create(kind, classDef); } - private static List createClassAnnotations(Map types) { + private static List createClassAnnotations(TypeStore typeStore) { return Arrays.asList( - AnnotationNode.withType(types.get("BetaApi")), + AnnotationNode.withType(typeStore.get("BetaApi")), AnnotationNode.builder() - .setType(types.get("Generated")) + .setType(typeStore.get("Generated")) .setDescription("by gapic-generator") .build()); } - private static List createClassImplements(Map types) { - return Arrays.asList(types.get("BackgroundResource")); + private static List createClassImplements(TypeStore typeStore) { + return Arrays.asList(typeStore.get("BackgroundResource")); } private static List createClassMethods( Service service, Map messageTypes, - Map types, + TypeStore typeStore, boolean hasLroClient) { List methods = new ArrayList<>(); - methods.addAll(createStaticCreatorMethods(service, types)); - methods.addAll(createConstructorMethods(service, types, hasLroClient)); - methods.addAll(createGetterMethods(service, types, hasLroClient)); - methods.addAll(createServiceMethods(service, messageTypes, types)); - methods.addAll(createBackgroundResourceMethods(service, types)); + methods.addAll(createStaticCreatorMethods(service, typeStore)); + methods.addAll(createConstructorMethods(service, typeStore, hasLroClient)); + methods.addAll(createGetterMethods(service, typeStore, hasLroClient)); + methods.addAll(createServiceMethods(service, messageTypes, typeStore)); + methods.addAll(createBackgroundResourceMethods(service, typeStore)); return methods; } @@ -172,12 +172,13 @@ private static boolean hasLroMethods(Service service) { } private static List createFieldDeclarations( - Service service, Map types, boolean hasLroClient) { + Service service, TypeStore typeStore, boolean hasLroClient) { Map fieldNameToTypes = new HashMap<>(); - fieldNameToTypes.put("settings", types.get(ClassNames.getServiceSettingsClassName(service))); - fieldNameToTypes.put("stub", types.get(ClassNames.getServiceStubClassName(service))); + fieldNameToTypes.put( + "settings", typeStore.get(ClassNames.getServiceSettingsClassName(service))); + fieldNameToTypes.put("stub", typeStore.get(ClassNames.getServiceStubClassName(service))); if (hasLroClient) { - fieldNameToTypes.put("operationsClient", types.get("OperationsClient")); + fieldNameToTypes.put("operationsClient", typeStore.get("OperationsClient")); } return fieldNameToTypes.entrySet().stream() @@ -199,14 +200,14 @@ private static List createFieldDeclarations( } private static List createStaticCreatorMethods( - Service service, Map types) { + Service service, TypeStore typeStore) { List methods = new ArrayList<>(); String thisClientName = ClassNames.getServiceClientClassName(service); String settingsName = ClassNames.getServiceSettingsClassName(service); - TypeNode thisClassType = types.get(thisClientName); - TypeNode exceptionType = types.get("IOException"); + TypeNode thisClassType = typeStore.get(thisClientName); + TypeNode exceptionType = typeStore.get("IOException"); - TypeNode settingsType = types.get(settingsName); + TypeNode settingsType = typeStore.get(settingsName); Preconditions.checkNotNull(settingsType, String.format("Type %s not found", settingsName)); MethodInvocationExpr newBuilderExpr = @@ -223,7 +224,7 @@ private static List createStaticCreatorMethods( MethodInvocationExpr.builder() .setMethodName("create") .setArguments(Arrays.asList(buildExpr)) - .setReturnType(types.get(thisClientName)) + .setReturnType(typeStore.get(thisClientName)) .build(); MethodDefinition createMethodOne = @@ -244,7 +245,7 @@ private static List createStaticCreatorMethods( // Second create(ServiceSettings settings) method. VariableExpr settingsVarExpr = VariableExpr.withVariable( - Variable.builder().setName("settings").setType(types.get(settingsName)).build()); + Variable.builder().setName("settings").setType(typeStore.get(settingsName)).build()); methods.add( MethodDefinition.builder() @@ -269,12 +270,12 @@ private static List createStaticCreatorMethods( VariableExpr stubVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(types.get(ClassNames.getServiceStubClassName(service))) + .setType(typeStore.get(ClassNames.getServiceStubClassName(service))) .setName("stub") .build()); AnnotationNode betaAnnotation = AnnotationNode.builder() - .setType(types.get("BetaApi")) + .setType(typeStore.get("BetaApi")) .setDescription( "A restructuring of stub classes is planned, so this may break in the future") .build(); @@ -298,23 +299,23 @@ private static List createStaticCreatorMethods( } private static List createConstructorMethods( - Service service, Map types, boolean hasLroClient) { + Service service, TypeStore typeStore, boolean hasLroClient) { List methods = new ArrayList<>(); String thisClientName = ClassNames.getServiceClientClassName(service); String settingsName = ClassNames.getServiceSettingsClassName(service); - TypeNode thisClassType = types.get(thisClientName); - TypeNode stubSettingsType = types.get(ClassNames.getServiceStubSettingsClassName(service)); - TypeNode operationsClientType = types.get("OperationsClient"); - TypeNode exceptionType = types.get("IOException"); + TypeNode thisClassType = typeStore.get(thisClientName); + TypeNode stubSettingsType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service)); + TypeNode operationsClientType = typeStore.get("OperationsClient"); + TypeNode exceptionType = typeStore.get("IOException"); - TypeNode settingsType = types.get(settingsName); + TypeNode settingsType = typeStore.get(settingsName); VariableExpr settingsVarExpr = VariableExpr.withVariable( - Variable.builder().setName("settings").setType(types.get(settingsName)).build()); + Variable.builder().setName("settings").setType(typeStore.get(settingsName)).build()); VariableExpr stubVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(types.get(ClassNames.getServiceStubClassName(service))) + .setType(typeStore.get(ClassNames.getServiceStubClassName(service))) .setName("stub") .build()); VariableExpr operationsClientVarExpr = @@ -402,7 +403,7 @@ private static List createConstructorMethods( } AnnotationNode betaAnnotation = AnnotationNode.builder() - .setType(types.get("BetaApi")) + .setType(typeStore.get("BetaApi")) .setDescription( "A restructuring of stub classes is planned, so this may break in the future") .build(); @@ -422,18 +423,18 @@ private static List createConstructorMethods( } private static List createGetterMethods( - Service service, Map types, boolean hasLroClient) { + Service service, TypeStore typeStore, boolean hasLroClient) { Map methodNameToTypes = new LinkedHashMap<>(); methodNameToTypes.put( - "getSettings", types.get(ClassNames.getServiceSettingsClassName(service))); - methodNameToTypes.put("getStub", types.get(ClassNames.getServiceStubClassName(service))); + "getSettings", typeStore.get(ClassNames.getServiceSettingsClassName(service))); + methodNameToTypes.put("getStub", typeStore.get(ClassNames.getServiceStubClassName(service))); String getOperationsClientMethodName = "getOperationsClient"; if (hasLroClient) { - methodNameToTypes.put(getOperationsClientMethodName, types.get("OperationsClient")); + methodNameToTypes.put(getOperationsClientMethodName, typeStore.get("OperationsClient")); } AnnotationNode betaStubAnnotation = AnnotationNode.builder() - .setType(types.get("BetaApi")) + .setType(typeStore.get("BetaApi")) .setDescription( "A restructuring of stub classes is planned, so this may break in the future") .build(); @@ -473,38 +474,38 @@ private static List createGetterMethods( } private static List createServiceMethods( - Service service, Map messageTypes, Map types) { + Service service, Map messageTypes, TypeStore typeStore) { List javaMethods = new ArrayList<>(); for (Method method : service.methods()) { if (method.stream().equals(Stream.NONE)) { - javaMethods.addAll(createMethodVariants(method, messageTypes, types)); - javaMethods.add(createMethodDefaultMethod(method, types)); + javaMethods.addAll(createMethodVariants(method, messageTypes, typeStore)); + javaMethods.add(createMethodDefaultMethod(method, typeStore)); } if (method.hasLro()) { - javaMethods.add(createLroCallableMethod(service, method, types)); + javaMethods.add(createLroCallableMethod(service, method, typeStore)); } if (method.isPaged()) { - javaMethods.add(createPagedCallableMethod(service, method, types)); + javaMethods.add(createPagedCallableMethod(service, method, typeStore)); } - javaMethods.add(createCallableMethod(service, method, types)); + javaMethods.add(createCallableMethod(service, method, typeStore)); } return javaMethods; } private static List createMethodVariants( - Method method, Map messageTypes, Map types) { + Method method, Map messageTypes, TypeStore typeStore) { List javaMethods = new ArrayList<>(); String methodName = JavaStyle.toLowerCamelCase(method.name()); TypeNode methodInputType = method.inputType(); TypeNode methodOutputType = method.isPaged() - ? types.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) + ? typeStore.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) : method.outputType(); if (method.hasLro()) { LongrunningOperation lro = method.lro(); methodOutputType = TypeNode.withReference( - types + typeStore .get("OperationFuture") .reference() .copyAndSetGenerics( @@ -536,7 +537,7 @@ private static List createMethodVariants( .setIsDecl(true) .build(); - Expr requestBuilderExpr = createRequestBuilderExpr(method, signature, types); + Expr requestBuilderExpr = createRequestBuilderExpr(method, signature, typeStore); AssignmentExpr requestAssignmentExpr = AssignmentExpr.builder() @@ -577,19 +578,18 @@ private static List createMethodVariants( return javaMethods; } - private static MethodDefinition createMethodDefaultMethod( - Method method, Map types) { + private static MethodDefinition createMethodDefaultMethod(Method method, TypeStore typeStore) { String methodName = JavaStyle.toLowerCamelCase(method.name()); TypeNode methodInputType = method.inputType(); TypeNode methodOutputType = method.isPaged() - ? types.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) + ? typeStore.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) : method.outputType(); if (method.hasLro()) { LongrunningOperation lro = method.lro(); methodOutputType = TypeNode.withReference( - types + typeStore .get("OperationFuture") .reference() .copyAndSetGenerics( @@ -642,43 +642,40 @@ private static MethodDefinition createMethodDefaultMethod( } private static MethodDefinition createLroCallableMethod( - Service service, Method method, Map types) { - return createCallableMethod(service, method, types, CallableMethodKind.LRO); + Service service, Method method, TypeStore typeStore) { + return createCallableMethod(service, method, typeStore, CallableMethodKind.LRO); } private static MethodDefinition createCallableMethod( - Service service, Method method, Map types) { - return createCallableMethod(service, method, types, CallableMethodKind.REGULAR); + Service service, Method method, TypeStore typeStore) { + return createCallableMethod(service, method, typeStore, CallableMethodKind.REGULAR); } private static MethodDefinition createPagedCallableMethod( - Service service, Method method, Map types) { - return createCallableMethod(service, method, types, CallableMethodKind.PAGED); + Service service, Method method, TypeStore typeStore) { + return createCallableMethod(service, method, typeStore, CallableMethodKind.PAGED); } private static MethodDefinition createCallableMethod( - Service service, - Method method, - Map types, - CallableMethodKind callableMethodKind) { + Service service, Method method, TypeStore typeStore, CallableMethodKind callableMethodKind) { TypeNode rawCallableReturnType = null; if (callableMethodKind.equals(CallableMethodKind.LRO)) { - rawCallableReturnType = types.get("OperationCallable"); + rawCallableReturnType = typeStore.get("OperationCallable"); } else { switch (method.stream()) { case CLIENT: - rawCallableReturnType = types.get("ClientStreamingCallable"); + rawCallableReturnType = typeStore.get("ClientStreamingCallable"); break; case SERVER: - rawCallableReturnType = types.get("ServerStreamingCallable"); + rawCallableReturnType = typeStore.get("ServerStreamingCallable"); break; case BIDI: - rawCallableReturnType = types.get("BidiStreamingCallable"); + rawCallableReturnType = typeStore.get("BidiStreamingCallable"); break; case NONE: // Fall through. default: - rawCallableReturnType = types.get("UnaryCallable"); + rawCallableReturnType = typeStore.get("UnaryCallable"); } } @@ -687,11 +684,11 @@ private static MethodDefinition createCallableMethod( TypeNode.withReference( rawCallableReturnType .reference() - .copyAndSetGenerics(getGenericsForCallable(callableMethodKind, method, types))); + .copyAndSetGenerics(getGenericsForCallable(callableMethodKind, method, typeStore))); String rawMethodName = JavaStyle.toLowerCamelCase(method.name()); String methodName = getCallableName(callableMethodKind, rawMethodName); - TypeNode stubType = types.get(ClassNames.getServiceStubClassName(service)); + TypeNode stubType = typeStore.get(ClassNames.getServiceStubClassName(service)); MethodInvocationExpr returnExpr = MethodInvocationExpr.builder() .setExprReferenceExpr( @@ -714,13 +711,13 @@ private static MethodDefinition createCallableMethod( } private static List createBackgroundResourceMethods( - Service service, Map types) { + Service service, TypeStore typeStore) { List methods = new ArrayList<>(); VariableExpr stubVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(types.get(ClassNames.getServiceStubClassName(service))) + .setType(typeStore.get(ClassNames.getServiceStubClassName(service))) .setName("stub") .build()); MethodDefinition closeMethod = @@ -806,7 +803,7 @@ private static List createBackgroundResourceMethods( Arrays.asList( VariableExpr.builder().setVariable(createVariable("duration", TypeNode.LONG)).build(), VariableExpr.builder() - .setVariable(createVariable("unit", types.get("TimeUnit"))) + .setVariable(createVariable("unit", typeStore.get("TimeUnit"))) .build()); MethodDefinition awaitTerminationMethod = @@ -819,7 +816,7 @@ private static List createBackgroundResourceMethods( arguments.stream() .map(v -> v.toBuilder().setIsDecl(true).build()) .collect(Collectors.toList())) - .setThrowsExceptions(Arrays.asList(types.get("InterruptedException"))) + .setThrowsExceptions(Arrays.asList(typeStore.get("InterruptedException"))) .setReturnExpr( MethodInvocationExpr.builder() .setExprReferenceExpr(stubVarExpr) @@ -835,7 +832,7 @@ private static List createBackgroundResourceMethods( } private static List createNestedPagingClasses( - Service service, Map messageTypes, Map types) { + Service service, Map messageTypes, TypeStore typeStore) { List nestedClasses = new ArrayList<>(); for (Method method : service.methods()) { if (!method.isPaged()) { @@ -853,12 +850,12 @@ private static List createNestedPagingClasses( TypeNode repeatedResponseType = repeatedPagedResultsField.type(); nestedClasses.add( - createNestedRpcPagedResponseClass(method, repeatedResponseType, messageTypes, types)); + createNestedRpcPagedResponseClass(method, repeatedResponseType, messageTypes, typeStore)); nestedClasses.add( - createNestedRpcPageClass(method, repeatedResponseType, messageTypes, types)); + createNestedRpcPageClass(method, repeatedResponseType, messageTypes, typeStore)); nestedClasses.add( createNestedRpcFixedSizeCollectionClass( - method, repeatedResponseType, messageTypes, types)); + method, repeatedResponseType, messageTypes, typeStore)); } return nestedClasses; @@ -868,15 +865,15 @@ private static ClassDefinition createNestedRpcPagedResponseClass( Method method, TypeNode repeatedResponseType, Map messageTypes, - Map types) { + TypeStore typeStore) { Preconditions.checkState( method.isPaged(), String.format("Expected method %s to be paged", method.name())); String className = String.format("%sPagedResponse", JavaStyle.toUpperCamelCase(method.name())); - TypeNode thisClassType = types.get(className); + TypeNode thisClassType = typeStore.get(className); String upperJavaMethodName = JavaStyle.toUpperCamelCase(method.name()); - TypeNode methodPageType = types.get(String.format("%sPage", upperJavaMethodName)); + TypeNode methodPageType = typeStore.get(String.format("%sPage", upperJavaMethodName)); TypeNode classExtendsType = TypeNode.withReference( ConcreteReference.builder() @@ -887,7 +884,8 @@ private static ClassDefinition createNestedRpcPagedResponseClass( method.outputType(), repeatedResponseType, methodPageType, - types.get(String.format("%sFixedSizeCollection", upperJavaMethodName))) + typeStore.get( + String.format("%sFixedSizeCollection", upperJavaMethodName))) .stream() .map(t -> t.reference()) .collect(Collectors.toList())) @@ -989,17 +987,17 @@ private static ClassDefinition createNestedRpcPagedResponseClass( TypeNode.withReference( ConcreteReference.builder() .setClazz(ApiFuture.class) - .setGenerics(Arrays.asList(types.get(className).reference())) + .setGenerics(Arrays.asList(typeStore.get(className).reference())) .build()); Expr returnExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(types.get("ApiFutures")) + .setStaticReferenceType(typeStore.get("ApiFutures")) .setMethodName("transform") .setArguments( futurePageVarExpr, pageToTransformExpr, MethodInvocationExpr.builder() - .setStaticReferenceType(types.get("MoreExecutors")) + .setStaticReferenceType(typeStore.get("MoreExecutors")) .setMethodName("directExecutor") .build()) .setReturnType(returnType) @@ -1038,7 +1036,7 @@ private static ClassDefinition createNestedRpcPagedResponseClass( pageVarExpr, MethodInvocationExpr.builder() .setStaticReferenceType( - types.get( + typeStore.get( String.format( "%sFixedSizeCollection", upperJavaMethodName))) .setMethodName("createEmptyCollection") @@ -1064,13 +1062,13 @@ private static ClassDefinition createNestedRpcPageClass( Method method, TypeNode repeatedResponseType, Map messageTypes, - Map types) { + TypeStore typeStore) { Preconditions.checkState( method.isPaged(), String.format("Expected method %s to be paged", method.name())); String upperJavaMethodName = JavaStyle.toUpperCamelCase(method.name()); String className = String.format("%sPage", upperJavaMethodName); - TypeNode classType = types.get(className); + TypeNode classType = typeStore.get(className); TypeNode classExtendsType = TypeNode.withReference( ConcreteReference.builder() @@ -1211,11 +1209,11 @@ private static ClassDefinition createNestedRpcFixedSizeCollectionClass( Method method, TypeNode repeatedResponseType, Map messageTypes, - Map types) { + TypeStore typeStore) { String upperJavaMethodName = JavaStyle.toUpperCamelCase(method.name()); String className = String.format("%sFixedSizeCollection", upperJavaMethodName); - TypeNode classType = types.get(className); - TypeNode methodPageType = types.get(String.format("%sPage", upperJavaMethodName)); + TypeNode classType = typeStore.get(className); + TypeNode methodPageType = typeStore.get(String.format("%sPage", upperJavaMethodName)); TypeNode classExtendsType = TypeNode.withReference( @@ -1318,7 +1316,7 @@ private static ClassDefinition createNestedRpcFixedSizeCollectionClass( @VisibleForTesting static Expr createRequestBuilderExpr( - Method method, List signature, Map types) { + Method method, List signature, TypeStore typeStore) { TypeNode methodInputType = method.inputType(); MethodInvocationExpr newBuilderExpr = MethodInvocationExpr.builder() @@ -1387,16 +1385,7 @@ private static String typeToSetterMethodName(TypeNode type) { return setterMethodVariantPattern; } - private static Map createTypes( - Service service, Map messageTypes) { - Map types = new HashMap<>(); - types.putAll(createConcreteTypes()); - types.putAll(createVaporTypes(service)); - types.putAll(createProtoMessageTypes(service.pakkage(), messageTypes)); - return types; - } - - private static Map createConcreteTypes() { + private static TypeStore createTypes(Service service, Map messageTypes) { List concreteClazzes = Arrays.asList( AbstractPagedListResponse.class, @@ -1420,111 +1409,51 @@ private static Map createConcreteTypes() { Strings.class, TimeUnit.class, UnaryCallable.class); - return concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); + TypeStore typeStore = new TypeStore(concreteClazzes); + typeStore.putMessageTypes(service.pakkage(), messageTypes); + createVaporTypes(service, typeStore); + return typeStore; } - private static Map createVaporTypes(Service service) { - // Client stub types. - Map types = + private static void createVaporTypes(Service service, TypeStore typeStore) { + // Client stub typeStore. + typeStore.putAll( + String.format("%s.stub", service.pakkage()), Arrays.asList( - ClassNames.getServiceStubClassName(service), - ClassNames.getServiceStubSettingsClassName(service)) - .stream() - .collect( - Collectors.toMap( - n -> n, - n -> - TypeNode.withReference( - VaporReference.builder() - .setName(n) - .setPakkage(String.format("%s.stub", service.pakkage())) - .build()))); - // Client ServiceClient and ServiceSettings types. - types.putAll( + ClassNames.getServiceStubClassName(service), + ClassNames.getServiceStubSettingsClassName(service))); + + // Client ServiceClient and ServiceSettings typeStore. + typeStore.putAll( + service.pakkage(), Arrays.asList( - ClassNames.getServiceClientClassName(service), - ClassNames.getServiceSettingsClassName(service)) - .stream() - .collect( - Collectors.toMap( - n -> n, - n -> - TypeNode.withReference( - VaporReference.builder() - .setName(n) - .setPakkage(service.pakkage()) - .build())))); - - // Nested class types. + ClassNames.getServiceClientClassName(service), + ClassNames.getServiceSettingsClassName(service))); + + // Nested class typeStore. for (Method method : service.methods()) { if (!method.isPaged()) { continue; } - types.putAll( + typeStore.putAll( + service.pakkage(), Arrays.asList("%sPagedResponse", "%sPage", "%sFixedSizeCollection").stream() - .collect( - Collectors.toMap( - t -> String.format(t, JavaStyle.toUpperCamelCase(method.name())), - t -> - TypeNode.withReference( - VaporReference.builder() - .setName( - String.format(t, JavaStyle.toUpperCamelCase(method.name()))) - .setEnclosingClassNames( - ClassNames.getServiceClientClassName(service)) - .setPakkage(service.pakkage()) - .setIsStaticImport(true) // Same class, so they won't be imported. - .build())))); + .map(p -> String.format(p, JavaStyle.toUpperCamelCase(method.name()))) + .collect(Collectors.toList()), + true, + ClassNames.getServiceClientClassName(service)); } - // LRO Gapic-generated types. - types.put( - "OperationsClient", - TypeNode.withReference( - VaporReference.builder() - .setName("OperationsClient") - .setPakkage("com.google.longrunning") - .build())); + // LRO Gapic-generated typeStore. + typeStore.put("com.google.longrunning", "OperationsClient"); // Pagination types. - types.putAll( + typeStore.putAll( + service.pakkage(), service.methods().stream() .filter(m -> m.isPaged()) - .collect( - Collectors.toMap( - m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name()), - m -> - TypeNode.withReference( - VaporReference.builder() - .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) - .setPakkage(service.pakkage()) - .setEnclosingClassNames( - ClassNames.getServiceClientClassName(service)) - .setIsStaticImport(true) - .build())))); - return types; - } - - private static Map createProtoMessageTypes( - String pakkage, Map messageTypes) { - // Vapor message types. - return messageTypes.entrySet().stream() - // Short-term hack for messages that have nested subtypes with colliding names. This - // should work as long as there isn't heavy usage of fully-qualified nested subtypes in - // general. A long-term fix would involve adding a custom type-store that handles - // fully-qualified types. - .filter(e -> e.getValue().outerNestedTypes().isEmpty()) - .collect( - Collectors.toMap( - e -> e.getValue().name(), - e -> - TypeNode.withReference( - VaporReference.builder() - .setName(e.getValue().name()) - .setPakkage(pakkage) - .build()))); + .map(m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) + .collect(Collectors.toList()), + true, + ClassNames.getServiceClientClassName(service)); } private static Variable createVariable(String name, TypeNode type) { @@ -1532,7 +1461,7 @@ private static Variable createVariable(String name, TypeNode type) { } private static List getGenericsForCallable( - CallableMethodKind kind, Method method, Map types) { + CallableMethodKind kind, Method method, TypeStore typeStore) { if (kind.equals(CallableMethodKind.LRO)) { return Arrays.asList( method.inputType().reference(), @@ -1542,7 +1471,9 @@ private static List getGenericsForCallable( if (kind.equals(CallableMethodKind.PAGED)) { return Arrays.asList( method.inputType().reference(), - types.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())).reference()); + typeStore + .get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) + .reference()); } return Arrays.asList(method.inputType().reference(), method.outputType().reference()); } diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java index 266efa242b..a1d6fa7912 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java @@ -57,6 +57,7 @@ import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.Field; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; @@ -76,7 +77,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -109,7 +109,7 @@ public class ServiceClientTestClassComposer { private static final ServiceClientTestClassComposer INSTANCE = new ServiceClientTestClassComposer(); - private static final Map STATIC_TYPES = createStaticTypes(); + private static final TypeStore FIXED_TYPESTORE = createStaticTypes(); private static final TypeNode LIST_TYPE = TypeNode.withReference(ConcreteReference.withClazz(List.class)); private static final TypeNode MAP_TYPE = @@ -119,7 +119,7 @@ public class ServiceClientTestClassComposer { ConcreteReference.withClazz(com.google.api.resourcenames.ResourceName.class)); private static final AnnotationNode TEST_ANNOTATION = - AnnotationNode.withType(STATIC_TYPES.get("Test")); + AnnotationNode.withType(FIXED_TYPESTORE.get("Test")); // Avoid conflicting types with com.google.rpc.Status. private static final TypeNode GRPC_STATUS_TYPE = TypeNode.withReference( @@ -134,11 +134,11 @@ public static ServiceClientTestClassComposer instance() { public GapicClass generate( Service service, Map resourceNames, Map messageTypes) { String pakkage = service.pakkage(); - Map types = createDynamicTypes(service); + TypeStore typeStore = createDynamicTypes(service); String className = ClassNames.getServiceClientTestClassName(service); GapicClass.Kind kind = Kind.MAIN; - Map classMemberVarExprs = createClassMemberVarExprs(service, types); + Map classMemberVarExprs = createClassMemberVarExprs(service, typeStore); ClassDefinition classDef = ClassDefinition.builder() @@ -149,7 +149,7 @@ public GapicClass generate( .setStatements(createClassMemberFieldDecls(classMemberVarExprs)) .setMethods( createClassMethods( - service, classMemberVarExprs, types, resourceNames, messageTypes)) + service, classMemberVarExprs, typeStore, resourceNames, messageTypes)) .build(); return GapicClass.create(kind, classDef); } @@ -157,22 +157,22 @@ public GapicClass generate( private static List createClassAnnotations() { return Arrays.asList( AnnotationNode.builder() - .setType(STATIC_TYPES.get("Generated")) + .setType(FIXED_TYPESTORE.get("Generated")) .setDescription("by gapic-generator-java") .build()); } private static Map createClassMemberVarExprs( - Service service, Map types) { + Service service, TypeStore typeStore) { BiFunction varExprFn = (name, type) -> VariableExpr.withVariable(Variable.builder().setName(name).setType(type).build()); Map fields = new LinkedHashMap<>(); fields.put( - getMockServiceVarName(service), types.get(ClassNames.getMockServiceClassName(service))); - fields.put(SERVICE_HELPER_VAR_NAME, STATIC_TYPES.get("MockServiceHelper")); - fields.put(CLIENT_VAR_NAME, types.get(ClassNames.getServiceClientClassName(service))); - fields.put(CHANNEL_PROVIDER_VAR_NAME, STATIC_TYPES.get("LocalChannelProvider")); + getMockServiceVarName(service), typeStore.get(ClassNames.getMockServiceClassName(service))); + fields.put(SERVICE_HELPER_VAR_NAME, FIXED_TYPESTORE.get("MockServiceHelper")); + fields.put(CLIENT_VAR_NAME, typeStore.get(ClassNames.getServiceClientClassName(service))); + fields.put(CHANNEL_PROVIDER_VAR_NAME, FIXED_TYPESTORE.get("LocalChannelProvider")); return fields.entrySet().stream() .collect(Collectors.toMap(e -> e.getKey(), e -> varExprFn.apply(e.getKey(), e.getValue()))); } @@ -194,22 +194,22 @@ private static List createClassMemberFieldDecls( private static List createClassMethods( Service service, Map classMemberVarExprs, - Map types, + TypeStore typeStore, Map resourceNames, Map messageTypes) { List javaMethods = new ArrayList<>(); - javaMethods.addAll(createTestAdminMethods(service, classMemberVarExprs, types)); + javaMethods.addAll(createTestAdminMethods(service, classMemberVarExprs, typeStore)); javaMethods.addAll( createTestMethods(service, classMemberVarExprs, resourceNames, messageTypes)); return javaMethods; } private static List createTestAdminMethods( - Service service, Map classMemberVarExprs, Map types) { + Service service, Map classMemberVarExprs, TypeStore typeStore) { List javaMethods = new ArrayList<>(); javaMethods.add(createStartStaticServerMethod(service, classMemberVarExprs)); javaMethods.add(createStopServerMethod(service, classMemberVarExprs)); - javaMethods.add(createSetUpMethod(service, classMemberVarExprs, types)); + javaMethods.add(createSetUpMethod(service, classMemberVarExprs, typeStore)); javaMethods.add(createTearDownMethod(service, classMemberVarExprs)); return javaMethods; } @@ -226,7 +226,7 @@ private static MethodDefinition createStartStaticServerMethod( MethodInvocationExpr firstArg = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("UUID")) + .setStaticReferenceType(FIXED_TYPESTORE.get("UUID")) .setMethodName("randomUUID") .build(); firstArg = @@ -237,8 +237,8 @@ private static MethodDefinition createStartStaticServerMethod( MethodInvocationExpr secondArg = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Arrays")) - .setGenerics(Arrays.asList(STATIC_TYPES.get("MockGrpcService").reference())) + .setStaticReferenceType(FIXED_TYPESTORE.get("Arrays")) + .setGenerics(Arrays.asList(FIXED_TYPESTORE.get("MockGrpcService").reference())) .setMethodName("asList") .setArguments(Arrays.asList(mockServiceVarExpr)) .build(); @@ -260,7 +260,7 @@ private static MethodDefinition createStartStaticServerMethod( .build(); return MethodDefinition.builder() - .setAnnotations(Arrays.asList(AnnotationNode.withType(STATIC_TYPES.get("BeforeClass")))) + .setAnnotations(Arrays.asList(AnnotationNode.withType(FIXED_TYPESTORE.get("BeforeClass")))) .setScope(ScopeNode.PUBLIC) .setIsStatic(true) .setReturnType(TypeNode.VOID) @@ -276,7 +276,7 @@ private static MethodDefinition createStartStaticServerMethod( private static MethodDefinition createStopServerMethod( Service service, Map classMemberVarExprs) { return MethodDefinition.builder() - .setAnnotations(Arrays.asList(AnnotationNode.withType(STATIC_TYPES.get("AfterClass")))) + .setAnnotations(Arrays.asList(AnnotationNode.withType(FIXED_TYPESTORE.get("AfterClass")))) .setScope(ScopeNode.PUBLIC) .setIsStatic(true) .setReturnType(TypeNode.VOID) @@ -292,7 +292,7 @@ private static MethodDefinition createStopServerMethod( } private static MethodDefinition createSetUpMethod( - Service service, Map classMemberVarExprs, Map types) { + Service service, Map classMemberVarExprs, TypeStore typeStore) { VariableExpr clientVarExpr = classMemberVarExprs.get(CLIENT_VAR_NAME); VariableExpr serviceHelperVarExpr = classMemberVarExprs.get(SERVICE_HELPER_VAR_NAME); VariableExpr channelProviderVarExpr = classMemberVarExprs.get(CHANNEL_PROVIDER_VAR_NAME); @@ -313,7 +313,7 @@ private static MethodDefinition createSetUpMethod( .build()) .build(); - TypeNode settingsType = types.get(ClassNames.getServiceSettingsClassName(service)); + TypeNode settingsType = typeStore.get(ClassNames.getServiceSettingsClassName(service)); VariableExpr localSettingsVarExpr = VariableExpr.withVariable( Variable.builder().setName("settings").setType(settingsType).build()); @@ -342,7 +342,7 @@ private static MethodDefinition createSetUpMethod( .apply( "setCredentialsProvider", MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("NoCredentialsProvider")) + .setStaticReferenceType(FIXED_TYPESTORE.get("NoCredentialsProvider")) .setMethodName("create") .build()); settingsBuilderExpr = @@ -364,7 +364,7 @@ private static MethodDefinition createSetUpMethod( .setValueExpr( MethodInvocationExpr.builder() .setStaticReferenceType( - types.get(ClassNames.getServiceClientClassName(service))) + typeStore.get(ClassNames.getServiceClientClassName(service))) .setMethodName("create") .setArguments(Arrays.asList(localSettingsVarExpr)) .setReturnType(clientVarExpr.type()) @@ -372,11 +372,11 @@ private static MethodDefinition createSetUpMethod( .build(); return MethodDefinition.builder() - .setAnnotations(Arrays.asList(AnnotationNode.withType(STATIC_TYPES.get("Before")))) + .setAnnotations(Arrays.asList(AnnotationNode.withType(FIXED_TYPESTORE.get("Before")))) .setScope(ScopeNode.PUBLIC) .setReturnType(TypeNode.VOID) .setName("setUp") - .setThrowsExceptions(Arrays.asList(STATIC_TYPES.get("IOException"))) + .setThrowsExceptions(Arrays.asList(FIXED_TYPESTORE.get("IOException"))) .setBody( Arrays.asList( resetServiceHelperExpr, @@ -392,7 +392,7 @@ private static MethodDefinition createSetUpMethod( private static MethodDefinition createTearDownMethod( Service service, Map classMemberVarExprs) { return MethodDefinition.builder() - .setAnnotations(Arrays.asList(AnnotationNode.withType(STATIC_TYPES.get("After")))) + .setAnnotations(Arrays.asList(AnnotationNode.withType(FIXED_TYPESTORE.get("After")))) .setScope(ScopeNode.PUBLIC) .setReturnType(TypeNode.VOID) .setName("tearDown") @@ -554,7 +554,7 @@ private static MethodDefinition createRpcTestMethod( VariableExpr resultOperationVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(STATIC_TYPES.get("Operation")) + .setType(FIXED_TYPESTORE.get("Operation")) .setName("resultOperation") .build()); methodExprs.add( @@ -680,7 +680,7 @@ private static MethodDefinition createRpcTestMethod( .build(); Expr resourcesValExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Lists")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Lists")) .setMethodName("newArrayList") .setArguments(iterateAllExpr) .setReturnType(resourcesVarExpr.type()) @@ -702,7 +702,7 @@ private static MethodDefinition createRpcTestMethod( // Assert the size is equivalent. methodExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertEquals") .setArguments( ValueExpr.withValue( @@ -747,14 +747,14 @@ private static MethodDefinition createRpcTestMethod( methodExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertEquals") .setArguments(expectedPagedResponseExpr, actualPagedResponseExpr) .build()); } else if (!returnsVoid) { methodExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertEquals") .setArguments(expectedResponseVarExpr, actualResponseVarExpr) .build()); @@ -790,7 +790,7 @@ private static MethodDefinition createRpcTestMethod( methodExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertEquals") .setArguments( ValueExpr.withValue( @@ -811,7 +811,7 @@ private static MethodDefinition createRpcTestMethod( .setArguments( ValueExpr.withValue( PrimitiveValue.builder().setType(TypeNode.INT).setValue("0").build())) - .setReturnType(STATIC_TYPES.get("AbstractMessage")) + .setReturnType(FIXED_TYPESTORE.get("AbstractMessage")) .build(); getFirstRequestExpr = CastExpr.builder().setType(method.inputType()).setExpr(getFirstRequestExpr).build(); @@ -860,7 +860,7 @@ private static MethodDefinition createRpcTestMethod( } methodExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertEquals") .setArguments(assertEqualsArguments) .build()); @@ -892,7 +892,7 @@ private static MethodDefinition createRpcTestMethod( } methodExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertEquals") .setArguments(expectedFieldExpr, actualFieldExpr) .build()); @@ -902,12 +902,12 @@ private static MethodDefinition createRpcTestMethod( // Assert header equality. Expr headerKeyExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("ApiClientHeaderProvider")) + .setStaticReferenceType(FIXED_TYPESTORE.get("ApiClientHeaderProvider")) .setMethodName("getDefaultApiClientHeaderKey") .build(); Expr headerPatternExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("GaxGrpcProperties")) + .setStaticReferenceType(FIXED_TYPESTORE.get("GaxGrpcProperties")) .setMethodName("getDefaultApiClientHeaderPattern") .build(); Expr headerSentExpr = @@ -918,7 +918,7 @@ private static MethodDefinition createRpcTestMethod( .build(); methodExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertTrue") .setArguments(headerSentExpr) .build()); @@ -979,7 +979,7 @@ private static MethodDefinition createStreamingRpcTestMethod( VariableExpr resultOperationVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(STATIC_TYPES.get("Operation")) + .setType(FIXED_TYPESTORE.get("Operation")) .setName("resultOperation") .build()); methodExprs.add( @@ -1032,7 +1032,7 @@ private static MethodDefinition createStreamingRpcTestMethod( Variable.builder() .setType( TypeNode.withReference( - STATIC_TYPES + FIXED_TYPESTORE .get("MockStreamObserver") .reference() .copyAndSetGenerics(Arrays.asList(method.outputType().reference())))) @@ -1045,7 +1045,7 @@ private static MethodDefinition createStreamingRpcTestMethod( .setVariableExpr(responseObserverVarExpr.toBuilder().setIsDecl(true).build()) .setValueExpr( NewObjectExpr.builder() - .setType(STATIC_TYPES.get("MockStreamObserver")) + .setType(FIXED_TYPESTORE.get("MockStreamObserver")) .setIsGeneric(true) .build()) .build())); @@ -1081,7 +1081,7 @@ private static MethodDefinition createStreamingRpcTestMethod( Variable.builder() .setType( TypeNode.withReference( - STATIC_TYPES + FIXED_TYPESTORE .get("ApiStreamObserver") .reference() .copyAndSetGenerics(Arrays.asList(method.inputType().reference())))) @@ -1160,7 +1160,7 @@ private static MethodDefinition createStreamingRpcTestMethod( // Assert the size is equivalent. methodExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertEquals") .setArguments( ValueExpr.withValue( @@ -1184,7 +1184,7 @@ private static MethodDefinition createStreamingRpcTestMethod( methodExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertEquals") .setArguments(expectedResponseVarExpr, actualResponseExpr) .build()); @@ -1217,7 +1217,7 @@ private static MethodDefinition createRpcExceptionTestMethod( VariableExpr exceptionVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(STATIC_TYPES.get("StatusRuntimeException")) + .setType(FIXED_TYPESTORE.get("StatusRuntimeException")) .setName("exception") .build()); @@ -1227,7 +1227,7 @@ private static MethodDefinition createRpcExceptionTestMethod( .setVariableExpr(exceptionVarExpr.toBuilder().setIsDecl(true).build()) .setValueExpr( NewObjectExpr.builder() - .setType(STATIC_TYPES.get("StatusRuntimeException")) + .setType(FIXED_TYPESTORE.get("StatusRuntimeException")) .setArguments( EnumRefExpr.builder() .setType(GRPC_STATUS_TYPE) @@ -1302,7 +1302,7 @@ private static List createStreamingRpcExceptionTestStatements( Variable.builder() .setType( TypeNode.withReference( - STATIC_TYPES + FIXED_TYPESTORE .get("MockStreamObserver") .reference() .copyAndSetGenerics(Arrays.asList(method.outputType().reference())))) @@ -1315,7 +1315,7 @@ private static List createStreamingRpcExceptionTestStatements( .setVariableExpr(responseObserverVarExpr.toBuilder().setIsDecl(true).build()) .setValueExpr( NewObjectExpr.builder() - .setType(STATIC_TYPES.get("MockStreamObserver")) + .setType(FIXED_TYPESTORE.get("MockStreamObserver")) .setIsGeneric(true) .build()) .build())); @@ -1353,7 +1353,7 @@ private static List createStreamingRpcExceptionTestStatements( Variable.builder() .setType( TypeNode.withReference( - STATIC_TYPES + FIXED_TYPESTORE .get("ApiStreamObserver") .reference() .copyAndSetGenerics(Arrays.asList(method.inputType().reference())))) @@ -1428,7 +1428,7 @@ private static List createStreamingRpcExceptionTestStatements( // Assert a failure if no exception was raised. tryBodyExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("fail") .setArguments(ValueExpr.withValue(StringObjectValue.withValue("No exception thrown"))) .build()); @@ -1535,7 +1535,7 @@ private static List createRpcExceptionTestStatements( // Assert a failure if no exception was raised. tryBodyExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("fail") .setArguments(ValueExpr.withValue(StringObjectValue.withValue("No exception raised"))) .build()); @@ -1564,7 +1564,7 @@ private static List createRpcLroExceptionTestCatchBody( .setType(TypeNode.withReference(ConcreteReference.withClazz(Class.class))) .setName("class") .build()) - .setStaticReferenceType(STATIC_TYPES.get("InvalidArgumentException")) + .setStaticReferenceType(FIXED_TYPESTORE.get("InvalidArgumentException")) .build(); Expr getCauseExpr = MethodInvocationExpr.builder() @@ -1582,11 +1582,11 @@ private static List createRpcLroExceptionTestCatchBody( InstanceofExpr checkInstanceExpr = InstanceofExpr.builder() .setExpr(getCauseExpr) - .setCheckType(STATIC_TYPES.get("InvalidArgumentException")) + .setCheckType(FIXED_TYPESTORE.get("InvalidArgumentException")) .build(); catchBodyExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertTrue") .setArguments(checkInstanceExpr) .build()); @@ -1594,7 +1594,7 @@ private static List createRpcLroExceptionTestCatchBody( // Constructs `Assert.assertEquals(InvalidArgumentException.class, e.getCaus().getClass());`. catchBodyExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertEquals") .setArguments(testExpectedValueExpr, testActualValueExpr) .build()); @@ -1604,12 +1604,12 @@ private static List createRpcLroExceptionTestCatchBody( VariableExpr apiExceptionVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(STATIC_TYPES.get("InvalidArgumentException")) + .setType(FIXED_TYPESTORE.get("InvalidArgumentException")) .setName("apiException") .build()); Expr castedCauseExpr = CastExpr.builder() - .setType(STATIC_TYPES.get("InvalidArgumentException")) + .setType(FIXED_TYPESTORE.get("InvalidArgumentException")) .setExpr(getCauseExpr) .build(); catchBodyExprs.add( @@ -1641,7 +1641,7 @@ private static List createRpcLroExceptionTestCatchBody( .build(); catchBodyExprs.add( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("Assert")) + .setStaticReferenceType(FIXED_TYPESTORE.get("Assert")) .setMethodName("assertEquals") .setArguments(testExpectedValueExpr, testActualValueExpr) .build()); @@ -1654,7 +1654,7 @@ private static List createRpcLroExceptionTestCatchBody( * ========================================= */ - private static Map createStaticTypes() { + private static TypeStore createStaticTypes() { List concreteClazzes = Arrays.asList( AbstractMessage.class, @@ -1683,30 +1683,12 @@ private static Map createStaticTypes() { StatusRuntimeException.class, Test.class, UUID.class); - Map STATIC_TYPES = - concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); - - STATIC_TYPES.putAll( + TypeStore typeStore = new TypeStore(concreteClazzes); + typeStore.putAll( + GRPC_TESTING_PACKAGE, Arrays.asList( - "LocalChannelProvider", - "MockGrpcService", - "MockServiceHelper", - "MockStreamObserver") - .stream() - .collect( - Collectors.toMap( - n -> n, - n -> - TypeNode.withReference( - VaporReference.builder() - .setName(n) - .setPakkage(GRPC_TESTING_PACKAGE) - .build())))); - return STATIC_TYPES; + "LocalChannelProvider", "MockGrpcService", "MockServiceHelper", "MockStreamObserver")); + return typeStore; } private static Map createDefaultMethodNamesToTypes() { @@ -1731,54 +1713,29 @@ private static Map createDefaultMethodNamesToTypes() { "defaultGrpcTransportProviderBuilder", typeMakerFn.apply(InstantiatingGrpcChannelProvider.Builder.class)); javaMethodNameToReturnType.put( - "defaultTransportChannelProvider", STATIC_TYPES.get("TransportChannelProvider")); + "defaultTransportChannelProvider", FIXED_TYPESTORE.get("TransportChannelProvider")); return javaMethodNameToReturnType; } - private static Map createDynamicTypes(Service service) { - Map types = new HashMap<>(); - - types.put( - ClassNames.getMockServiceClassName(service), - TypeNode.withReference( - VaporReference.builder() - .setName(ClassNames.getMockServiceClassName(service)) - .setPakkage(String.format("%s", service.pakkage())) - .build())); - - // Classes in the same package. - types.putAll( + private static TypeStore createDynamicTypes(Service service) { + TypeStore typeStore = new TypeStore(); + typeStore.putAll( + service.pakkage(), Arrays.asList( - ClassNames.getServiceClientClassName(service), - ClassNames.getServiceSettingsClassName(service)) - .stream() - .collect( - Collectors.toMap( - n -> n, - n -> - TypeNode.withReference( - VaporReference.builder() - .setName(n) - .setPakkage(service.pakkage()) - .build())))); + ClassNames.getMockServiceClassName(service), + ClassNames.getServiceClientClassName(service), + ClassNames.getServiceSettingsClassName(service))); // Pagination types. - types.putAll( + typeStore.putAll( + service.pakkage(), service.methods().stream() .filter(m -> m.isPaged()) - .collect( - Collectors.toMap( - m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name()), - m -> - TypeNode.withReference( - VaporReference.builder() - .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) - .setPakkage(service.pakkage()) - .setEnclosingClassNames( - ClassNames.getServiceClientClassName(service)) - .setIsStaticImport(true) - .build())))); - return types; + .map(m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) + .collect(Collectors.toList()), + true, + ClassNames.getServiceClientClassName(service)); + return typeStore; } private static TypeNode getOperationCallSettingsType(Method protoMethod) { @@ -1807,17 +1764,16 @@ private static TypeNode getOperationCallSettingsTypeHelper( .build()); } - private static TypeNode getCallSettingsType(Method protoMethod, Map types) { - return getCallSettingsTypeHelper(protoMethod, types, false); + private static TypeNode getCallSettingsType(Method protoMethod, TypeStore typeStore) { + return getCallSettingsTypeHelper(protoMethod, typeStore, false); } - private static TypeNode getCallSettingsBuilderType( - Method protoMethod, Map types) { - return getCallSettingsTypeHelper(protoMethod, types, true); + private static TypeNode getCallSettingsBuilderType(Method protoMethod, TypeStore typeStore) { + return getCallSettingsTypeHelper(protoMethod, typeStore, true); } private static TypeNode getCallSettingsTypeHelper( - Method protoMethod, Map types, boolean isBuilder) { + Method protoMethod, TypeStore typeStore, boolean isBuilder) { Class callSettingsClazz = isBuilder ? UnaryCallSettings.Builder.class : UnaryCallSettings.class; if (protoMethod.isPaged()) { callSettingsClazz = isBuilder ? PagedCallSettings.Builder.class : PagedCallSettings.class; @@ -1847,7 +1803,7 @@ private static TypeNode getCallSettingsTypeHelper( generics.add(protoMethod.outputType().reference()); if (protoMethod.isPaged()) { generics.add( - types + typeStore .get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, protoMethod.name())) .reference()); } diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java index b850e4801c..861a1a2f73 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java @@ -51,6 +51,7 @@ import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; import com.google.api.generator.gapic.composer.samplecode.SettingsSampleCodeComposer; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; @@ -63,7 +64,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -82,7 +82,7 @@ public class ServiceSettingsClassComposer implements ClassComposer { private static final ServiceSettingsClassComposer INSTANCE = new ServiceSettingsClassComposer(); - private static final Map staticTypes = createStaticTypes(); + private static final TypeStore FIXED_TYPESTORE = createStaticTypes(); private ServiceSettingsClassComposer() {} @@ -93,29 +93,30 @@ public static ServiceSettingsClassComposer instance() { @Override public GapicClass generate(Service service, Map ignore) { String pakkage = service.pakkage(); - Map types = createDynamicTypes(service); + TypeStore typeStore = createDynamicTypes(service); String className = ClassNames.getServiceSettingsClassName(service); GapicClass.Kind kind = Kind.MAIN; ClassDefinition classDef = ClassDefinition.builder() .setPackageString(pakkage) - .setHeaderCommentStatements(createClassHeaderComments(service, types.get(className))) + .setHeaderCommentStatements( + createClassHeaderComments(service, typeStore.get(className))) .setAnnotations(createClassAnnotations()) .setScope(ScopeNode.PUBLIC) .setName(className) .setExtendsType( TypeNode.withReference( - staticTypes + FIXED_TYPESTORE .get("ClientSettings") .reference() .copyAndSetGenerics( Arrays.asList( - types + typeStore .get(ClassNames.getServiceSettingsClassName(service)) .reference())))) - .setMethods(createClassMethods(service, types)) - .setNestedClasses(Arrays.asList(createNestedBuilderClass(service, types))) + .setMethods(createClassMethods(service, typeStore)) + .setNestedClasses(Arrays.asList(createNestedBuilderClass(service, typeStore))) .build(); return GapicClass.create(kind, classDef); } @@ -147,49 +148,47 @@ private static List createClassHeaderComments( private static List createClassAnnotations() { return Arrays.asList( AnnotationNode.builder() - .setType(staticTypes.get("Generated")) + .setType(FIXED_TYPESTORE.get("Generated")) .setDescription("by gapic-generator-java") .build()); } - private static List createClassMethods( - Service service, Map types) { + private static List createClassMethods(Service service, TypeStore typeStore) { List javaMethods = new ArrayList<>(); - javaMethods.addAll(createSettingsGetterMethods(service, types)); - javaMethods.add(createCreatorMethod(service, types)); - javaMethods.addAll(createDefaultGetterMethods(service, types)); - javaMethods.addAll(createBuilderHelperMethods(service, types)); - javaMethods.add(createConstructorMethod(service, types)); + javaMethods.addAll(createSettingsGetterMethods(service, typeStore)); + javaMethods.add(createCreatorMethod(service, typeStore)); + javaMethods.addAll(createDefaultGetterMethods(service, typeStore)); + javaMethods.addAll(createBuilderHelperMethods(service, typeStore)); + javaMethods.add(createConstructorMethod(service, typeStore)); return javaMethods; } - private static MethodDefinition createConstructorMethod( - Service service, Map types) { + private static MethodDefinition createConstructorMethod(Service service, TypeStore typeStore) { VariableExpr settingsBuilderVarExpr = VariableExpr.withVariable( Variable.builder() .setName("settingsBuilder") - .setType(types.get(BUILDER_CLASS_NAME)) + .setType(typeStore.get(BUILDER_CLASS_NAME)) .build()); - TypeNode thisClassType = types.get(ClassNames.getServiceSettingsClassName(service)); + TypeNode thisClassType = typeStore.get(ClassNames.getServiceSettingsClassName(service)); return MethodDefinition.constructorBuilder() .setScope(ScopeNode.PROTECTED) .setReturnType(thisClassType) .setArguments(Arrays.asList(settingsBuilderVarExpr.toBuilder().setIsDecl(true).build())) - .setThrowsExceptions(Arrays.asList(staticTypes.get("IOException"))) + .setThrowsExceptions(Arrays.asList(FIXED_TYPESTORE.get("IOException"))) .setBody( Arrays.asList( ExprStatement.withExpr( ReferenceConstructorExpr.superBuilder() - .setType(staticTypes.get("ClientSettings")) + .setType(FIXED_TYPESTORE.get("ClientSettings")) .setArguments(settingsBuilderVarExpr) .build()))) .build(); } private static List createSettingsGetterMethods( - Service service, Map types) { - TypeNode stubSettingsType = types.get(ClassNames.getServiceStubSettingsClassName(service)); + Service service, TypeStore typeStore) { + TypeNode stubSettingsType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service)); BiFunction methodMakerFn = (retType, methodName) -> MethodDefinition.builder() @@ -207,7 +206,7 @@ private static List createSettingsGetterMethods( .setExpr( MethodInvocationExpr.builder() .setMethodName("getStubSettings") - .setReturnType(staticTypes.get("StubSettings")) + .setReturnType(FIXED_TYPESTORE.get("StubSettings")) .build()) .build()) .setMethodName(methodName) @@ -219,7 +218,8 @@ private static List createSettingsGetterMethods( String javaStyleName = JavaStyle.toLowerCamelCase(protoMethod.name()); javaMethods.add( methodMakerFn.apply( - getCallSettingsType(protoMethod, types), String.format("%sSettings", javaStyleName))); + getCallSettingsType(protoMethod, typeStore), + String.format("%sSettings", javaStyleName))); if (protoMethod.hasLro()) { javaMethods.add( methodMakerFn.apply( @@ -230,14 +230,13 @@ private static List createSettingsGetterMethods( return javaMethods; } - private static MethodDefinition createCreatorMethod( - Service service, Map types) { - TypeNode stubClassType = types.get(ClassNames.getServiceStubSettingsClassName(service)); + private static MethodDefinition createCreatorMethod(Service service, TypeStore typeStore) { + TypeNode stubClassType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service)); VariableExpr stubVarExpr = VariableExpr.withVariable( Variable.builder().setName("stub").setType(stubClassType).build()); - TypeNode thisClassType = types.get(ClassNames.getServiceSettingsClassName(service)); + TypeNode thisClassType = typeStore.get(ClassNames.getServiceSettingsClassName(service)); MethodInvocationExpr stubBuilderMethodExpr = MethodInvocationExpr.builder() .setExprReferenceExpr(stubVarExpr) @@ -269,13 +268,13 @@ private static MethodDefinition createCreatorMethod( .setReturnType(thisClassType) .setName("create") .setArguments(Arrays.asList(stubVarExpr.toBuilder().setIsDecl(true).build())) - .setThrowsExceptions(Arrays.asList(staticTypes.get("IOException"))) + .setThrowsExceptions(Arrays.asList(FIXED_TYPESTORE.get("IOException"))) .setReturnExpr(returnMethodExpr) .build(); } private static List createDefaultGetterMethods( - Service service, Map types) { + Service service, TypeStore typeStore) { BiFunction methodStarterFn = (mName, retType) -> MethodDefinition.builder() @@ -286,7 +285,7 @@ private static List createDefaultGetterMethods( .setReturnExpr( MethodInvocationExpr.builder() .setStaticReferenceType( - types.get(ClassNames.getServiceStubSettingsClassName(service))) + typeStore.get(ClassNames.getServiceStubSettingsClassName(service))) .setMethodName(mName) .setReturnType(retType) .build()); @@ -345,7 +344,7 @@ private static List createDefaultGetterMethods( .setAnnotations( Arrays.asList( AnnotationNode.builder() - .setType(staticTypes.get("BetaApi")) + .setType(FIXED_TYPESTORE.get("BetaApi")) .setDescription( "The surface for customizing headers is not stable yet and may" + " change in the future.") @@ -355,8 +354,8 @@ private static List createDefaultGetterMethods( } private static List createBuilderHelperMethods( - Service service, Map types) { - TypeNode builderType = types.get(BUILDER_CLASS_NAME); + Service service, TypeStore typeStore) { + TypeNode builderType = typeStore.get(BUILDER_CLASS_NAME); MethodDefinition newBuilderMethodOne = MethodDefinition.builder() .setHeaderCommentStatements(SettingsCommentComposer.NEW_BUILDER_METHOD_COMMENT) @@ -376,7 +375,7 @@ private static List createBuilderHelperMethods( VariableExpr.withVariable( Variable.builder() .setName("clientContext") - .setType(staticTypes.get("ClientContext")) + .setType(FIXED_TYPESTORE.get("ClientContext")) .build()); MethodDefinition newBuilderMethodTwo = @@ -406,15 +405,14 @@ private static List createBuilderHelperMethods( .setArguments( ValueExpr.withValue( ThisObjectValue.withType( - types.get(ClassNames.getServiceSettingsClassName(service))))) + typeStore.get(ClassNames.getServiceSettingsClassName(service))))) .build()) .build(); return Arrays.asList(newBuilderMethodOne, newBuilderMethodTwo, toBuilderMethod); } - private static ClassDefinition createNestedBuilderClass( - Service service, Map types) { + private static ClassDefinition createNestedBuilderClass(Service service, TypeStore typeStore) { return ClassDefinition.builder() .setHeaderCommentStatements( SettingsCommentComposer.createBuilderClassComment( @@ -429,33 +427,35 @@ private static ClassDefinition createNestedBuilderClass( .setClazz(ClientSettings.Builder.class) .setGenerics( Arrays.asList( - types.get(ClassNames.getServiceSettingsClassName(service)).reference(), - types.get(BUILDER_CLASS_NAME).reference())) + typeStore + .get(ClassNames.getServiceSettingsClassName(service)) + .reference(), + typeStore.get(BUILDER_CLASS_NAME).reference())) .build())) - .setMethods(createNestedBuilderClassMethods(service, types)) + .setMethods(createNestedBuilderClassMethods(service, typeStore)) .build(); } private static List createNestedBuilderClassMethods( - Service service, Map types) { + Service service, TypeStore typeStore) { List javaMethods = new ArrayList<>(); - javaMethods.addAll(createNestedBuilderConstructorMethods(service, types)); - javaMethods.add(createNestedBuilderCreatorMethod(service, types)); - javaMethods.add(createNestedBuilderStubSettingsBuilderMethod(service, types)); - javaMethods.add(createNestedBuilderApplyToAllUnaryMethod(service, types)); - javaMethods.addAll(createNestedBuilderSettingsGetterMethods(service, types)); - javaMethods.add(createNestedBuilderClassBuildMethod(service, types)); + javaMethods.addAll(createNestedBuilderConstructorMethods(service, typeStore)); + javaMethods.add(createNestedBuilderCreatorMethod(service, typeStore)); + javaMethods.add(createNestedBuilderStubSettingsBuilderMethod(service, typeStore)); + javaMethods.add(createNestedBuilderApplyToAllUnaryMethod(service, typeStore)); + javaMethods.addAll(createNestedBuilderSettingsGetterMethods(service, typeStore)); + javaMethods.add(createNestedBuilderClassBuildMethod(service, typeStore)); return javaMethods; } private static List createNestedBuilderConstructorMethods( - Service service, Map types) { - TypeNode builderType = types.get(BUILDER_CLASS_NAME); + Service service, TypeStore typeStore) { + TypeNode builderType = typeStore.get(BUILDER_CLASS_NAME); MethodDefinition noArgCtor = MethodDefinition.constructorBuilder() .setScope(ScopeNode.PROTECTED) .setReturnType(builderType) - .setThrowsExceptions(Arrays.asList(staticTypes.get("IOException"))) + .setThrowsExceptions(Arrays.asList(FIXED_TYPESTORE.get("IOException"))) .setBody( Arrays.asList( ExprStatement.withExpr( @@ -463,7 +463,7 @@ private static List createNestedBuilderConstructorMethods( .setType(builderType) .setArguments( CastExpr.builder() - .setType(staticTypes.get("ClientContext")) + .setType(FIXED_TYPESTORE.get("ClientContext")) .setExpr(ValueExpr.createNullExpr()) .build()) .build()))) @@ -479,7 +479,7 @@ private static List createNestedBuilderConstructorMethods( Arrays.asList( ExprStatement.withExpr( ReferenceConstructorExpr.superBuilder() - .setType(staticTypes.get("ClientSettings")) + .setType(FIXED_TYPESTORE.get("ClientSettings")) .setArguments(superArg) .build()))) .build(); @@ -488,14 +488,14 @@ private static List createNestedBuilderConstructorMethods( VariableExpr.withVariable( Variable.builder() .setName("clientContext") - .setType(staticTypes.get("ClientContext")) + .setType(FIXED_TYPESTORE.get("ClientContext")) .build()); MethodDefinition clientContextCtor = ctorMakerFn.apply( clientContextVarExpr, MethodInvocationExpr.builder() .setStaticReferenceType( - types.get(ClassNames.getServiceStubSettingsClassName(service))) + typeStore.get(ClassNames.getServiceStubSettingsClassName(service))) .setMethodName("newBuilder") .setArguments(Arrays.asList(clientContextVarExpr)) .build()); @@ -504,7 +504,7 @@ private static List createNestedBuilderConstructorMethods( VariableExpr.withVariable( Variable.builder() .setName("settings") - .setType(types.get(ClassNames.getServiceSettingsClassName(service))) + .setType(typeStore.get(ClassNames.getServiceSettingsClassName(service))) .build()); MethodInvocationExpr settingsBuilderMethodExpr = MethodInvocationExpr.builder() @@ -528,14 +528,15 @@ private static List createNestedBuilderConstructorMethods( } private static MethodDefinition createNestedBuilderCreatorMethod( - Service service, Map types) { + Service service, TypeStore typeStore) { MethodInvocationExpr ctorArg = MethodInvocationExpr.builder() - .setStaticReferenceType(types.get(ClassNames.getServiceStubSettingsClassName(service))) + .setStaticReferenceType( + typeStore.get(ClassNames.getServiceStubSettingsClassName(service))) .setMethodName("newBuilder") .build(); - TypeNode builderType = types.get(BUILDER_CLASS_NAME); + TypeNode builderType = typeStore.get(BUILDER_CLASS_NAME); return MethodDefinition.builder() .setScope(ScopeNode.PRIVATE) .setIsStatic(true) @@ -546,7 +547,7 @@ private static MethodDefinition createNestedBuilderCreatorMethod( } private static MethodDefinition createNestedBuilderStubSettingsBuilderMethod( - Service service, Map types) { + Service service, TypeStore typeStore) { TypeNode retType = getStubSettingsBuilderType(service); return MethodDefinition.builder() .setScope(ScopeNode.PUBLIC) @@ -558,15 +559,15 @@ private static MethodDefinition createNestedBuilderStubSettingsBuilderMethod( .setExpr( MethodInvocationExpr.builder() .setMethodName("getStubSettings") - .setReturnType(staticTypes.get("StubSettings")) + .setReturnType(FIXED_TYPESTORE.get("StubSettings")) .build()) .build()) .build(); } private static MethodDefinition createNestedBuilderApplyToAllUnaryMethod( - Service service, Map types) { - TypeNode builderType = types.get(BUILDER_CLASS_NAME); + Service service, TypeStore typeStore) { + TypeNode builderType = typeStore.get(BUILDER_CLASS_NAME); String javaMethodName = "applyToAllUnaryMethods"; TypeNode unaryCallSettingsType = @@ -582,7 +583,7 @@ private static MethodDefinition createNestedBuilderApplyToAllUnaryMethod( .setName("settingsUpdater") .setType( TypeNode.withReference( - staticTypes + FIXED_TYPESTORE .get("ApiFunction") .reference() .copyAndSetGenerics( @@ -625,7 +626,7 @@ private static MethodDefinition createNestedBuilderApplyToAllUnaryMethod( } private static List createNestedBuilderSettingsGetterMethods( - Service service, Map types) { + Service service, TypeStore typeStore) { BiFunction methodMakerFn = (retType, methodName) -> MethodDefinition.builder() @@ -650,7 +651,7 @@ private static List createNestedBuilderSettingsGetterMethods( String javaStyleName = JavaStyle.toLowerCamelCase(protoMethod.name()); javaMethods.add( methodMakerFn.apply( - getCallSettingsBuilderType(protoMethod, types), + getCallSettingsBuilderType(protoMethod, typeStore), String.format("%sSettings", javaStyleName))); if (protoMethod.hasLro()) { javaMethods.add( @@ -663,15 +664,15 @@ private static List createNestedBuilderSettingsGetterMethods( } private static MethodDefinition createNestedBuilderClassBuildMethod( - Service service, Map types) { - TypeNode builderType = types.get(BUILDER_CLASS_NAME); - TypeNode returnType = types.get(ClassNames.getServiceSettingsClassName(service)); + Service service, TypeStore typeStore) { + TypeNode builderType = typeStore.get(BUILDER_CLASS_NAME); + TypeNode returnType = typeStore.get(ClassNames.getServiceSettingsClassName(service)); return MethodDefinition.builder() .setIsOverride(true) .setScope(ScopeNode.PUBLIC) .setReturnType(returnType) .setName("build") - .setThrowsExceptions(Arrays.asList(staticTypes.get("IOException"))) + .setThrowsExceptions(Arrays.asList(FIXED_TYPESTORE.get("IOException"))) .setReturnExpr( NewObjectExpr.builder() .setType(returnType) @@ -680,7 +681,7 @@ private static MethodDefinition createNestedBuilderClassBuildMethod( .build(); } - private static Map createStaticTypes() { + private static TypeStore createStaticTypes() { List concreteClazzes = Arrays.asList( ApiClientHeaderProvider.class, @@ -701,61 +702,37 @@ private static Map createStaticTypes() { StubSettings.class, TransportChannelProvider.class, UnaryCallSettings.class); - return concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); + return new TypeStore(concreteClazzes); } - private static Map createDynamicTypes(Service service) { - Map types = new HashMap<>(); + private static TypeStore createDynamicTypes(Service service) { + TypeStore typeStore = new TypeStore(); // ServiceStubSettings class. - String stubSettingsClassName = ClassNames.getServiceStubSettingsClassName(service); - types.put( - stubSettingsClassName, - TypeNode.withReference( - VaporReference.builder() - .setName(stubSettingsClassName) - .setPakkage(String.format("%s.stub", service.pakkage())) - .build())); + typeStore.put( + String.format("%s.stub", service.pakkage()), + ClassNames.getServiceStubSettingsClassName(service)); + // This class. - types.put( - ClassNames.getServiceSettingsClassName(service), - TypeNode.withReference( - VaporReference.builder() - .setName(ClassNames.getServiceSettingsClassName(service)) - .setPakkage(service.pakkage()) - .build())); + typeStore.put(service.pakkage(), ClassNames.getServiceSettingsClassName(service)); + // Nested Builder class. - types.put( + typeStore.put( + service.pakkage(), BUILDER_CLASS_NAME, - TypeNode.withReference( - VaporReference.builder() - .setName(BUILDER_CLASS_NAME) - .setEnclosingClassNames(ClassNames.getServiceSettingsClassName(service)) - .setPakkage(service.pakkage()) - .setIsStaticImport(true) - .build())); + true, + ClassNames.getServiceSettingsClassName(service)); // Pagination types. - types.putAll( + typeStore.putAll( + service.pakkage(), service.methods().stream() .filter(m -> m.isPaged()) - .collect( - Collectors.toMap( - m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name()), - m -> - TypeNode.withReference( - VaporReference.builder() - .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) - .setPakkage(service.pakkage()) - .setEnclosingClassNames( - ClassNames.getServiceClientClassName(service)) - .setIsStaticImport(true) - .build())))); - return types; + .map(m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) + .collect(Collectors.toList()), + true, + ClassNames.getServiceClientClassName(service)); + return typeStore; } private static TypeNode getOperationCallSettingsType(Method protoMethod) { @@ -784,17 +761,16 @@ private static TypeNode getOperationCallSettingsTypeHelper( .build()); } - private static TypeNode getCallSettingsType(Method protoMethod, Map types) { - return getCallSettingsTypeHelper(protoMethod, types, false); + private static TypeNode getCallSettingsType(Method protoMethod, TypeStore typeStore) { + return getCallSettingsTypeHelper(protoMethod, typeStore, false); } - private static TypeNode getCallSettingsBuilderType( - Method protoMethod, Map types) { - return getCallSettingsTypeHelper(protoMethod, types, true); + private static TypeNode getCallSettingsBuilderType(Method protoMethod, TypeStore typeStore) { + return getCallSettingsTypeHelper(protoMethod, typeStore, true); } private static TypeNode getCallSettingsTypeHelper( - Method protoMethod, Map types, boolean isBuilder) { + Method protoMethod, TypeStore typeStore, boolean isBuilder) { Class callSettingsClazz = isBuilder ? UnaryCallSettings.Builder.class : UnaryCallSettings.class; if (protoMethod.isPaged()) { callSettingsClazz = isBuilder ? PagedCallSettings.Builder.class : PagedCallSettings.class; @@ -827,7 +803,7 @@ private static TypeNode getCallSettingsTypeHelper( generics.add(protoMethod.outputType().reference()); if (protoMethod.isPaged()) { generics.add( - types + typeStore .get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, protoMethod.name())) .reference()); } diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java index 47a3c7a19e..9718f5a49e 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java @@ -22,7 +22,6 @@ import com.google.api.gax.rpc.UnaryCallable; import com.google.api.generator.engine.ast.AnnotationNode; import com.google.api.generator.engine.ast.ClassDefinition; -import com.google.api.generator.engine.ast.ConcreteReference; import com.google.api.generator.engine.ast.ExprStatement; import com.google.api.generator.engine.ast.MethodDefinition; import com.google.api.generator.engine.ast.Reference; @@ -30,7 +29,7 @@ import com.google.api.generator.engine.ast.Statement; import com.google.api.generator.engine.ast.ThrowExpr; import com.google.api.generator.engine.ast.TypeNode; -import com.google.api.generator.engine.ast.VaporReference; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; @@ -40,7 +39,6 @@ import com.google.longrunning.Operation; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -59,7 +57,7 @@ public static ServiceStubClassComposer instance() { @Override public GapicClass generate(Service service, Map messageTypes) { - Map types = createTypes(service, messageTypes); + TypeStore typeStore = createTypes(service, messageTypes); String className = ClassNames.getServiceStubClassName(service); GapicClass.Kind kind = Kind.STUB; String pakkage = String.format("%s.stub", service.pakkage()); @@ -69,88 +67,87 @@ public GapicClass generate(Service service, Map messageTypes) { .setPackageString(pakkage) .setHeaderCommentStatements( StubCommentComposer.createServiceStubClassHeaderComments(service.name())) - .setAnnotations(createClassAnnotations(types)) + .setAnnotations(createClassAnnotations(typeStore)) .setIsAbstract(true) - .setImplementsTypes(createClassImplements(types)) + .setImplementsTypes(createClassImplements(typeStore)) .setName(className) - .setMethods(createClassMethods(service, messageTypes, types)) + .setMethods(createClassMethods(service, messageTypes, typeStore)) .setScope(ScopeNode.PUBLIC) .build(); return GapicClass.create(kind, classDef); } - private static List createClassAnnotations(Map types) { + private static List createClassAnnotations(TypeStore typeStore) { return Arrays.asList( AnnotationNode.builder() - .setType(types.get("Generated")) + .setType(typeStore.get("Generated")) .setDescription("by gapic-generator") .build()); } - private static List createClassImplements(Map types) { - return Arrays.asList(types.get("BackgroundResource")); + private static List createClassImplements(TypeStore typeStore) { + return Arrays.asList(typeStore.get("BackgroundResource")); } private static List createClassMethods( - Service service, Map messageTypes, Map types) { + Service service, Map messageTypes, TypeStore typeStore) { boolean hasLroClient = hasLroMethods(service); List methods = new ArrayList<>(); if (hasLroClient) { - methods.add(createOperationsStubGetter(types)); + methods.add(createOperationsStubGetter(typeStore)); } - methods.addAll(createCallableGetters(service, messageTypes, types)); + methods.addAll(createCallableGetters(service, messageTypes, typeStore)); methods.addAll(createBackgroundResourceMethodOverrides()); return methods; } private static List createCallableGetters( - Service service, Map messageTypes, Map types) { + Service service, Map messageTypes, TypeStore typeStore) { // Use a traditional for-loop since the output cardinality is not necessarily 1:1 with that of // service.methods(). List javaMethods = new ArrayList<>(); for (Method method : service.methods()) { if (method.hasLro()) { - javaMethods.add(createOperationCallableGetter(method, types)); + javaMethods.add(createOperationCallableGetter(method, typeStore)); } if (method.isPaged()) { - javaMethods.add(createPagedCallableGetter(method, types)); + javaMethods.add(createPagedCallableGetter(method, typeStore)); } - javaMethods.add(createCallableGetter(method, types)); + javaMethods.add(createCallableGetter(method, typeStore)); } return javaMethods; } private static MethodDefinition createOperationCallableGetter( - Method method, Map types) { - return createCallableGetterHelper(method, types, true, false); + Method method, TypeStore typeStore) { + return createCallableGetterHelper(method, typeStore, true, false); } - private static MethodDefinition createPagedCallableGetter( - Method method, Map types) { - return createCallableGetterHelper(method, types, false, true); + private static MethodDefinition createPagedCallableGetter(Method method, TypeStore typeStore) { + return createCallableGetterHelper(method, typeStore, false, true); } - private static MethodDefinition createCallableGetter(Method method, Map types) { - return createCallableGetterHelper(method, types, false, false); + private static MethodDefinition createCallableGetter(Method method, TypeStore typeStore) { + return createCallableGetterHelper(method, typeStore, false, false); } private static MethodDefinition createCallableGetterHelper( - Method method, Map types, boolean isLroCallable, boolean isPaged) { + Method method, TypeStore typeStore, boolean isLroCallable, boolean isPaged) { TypeNode returnType; switch (method.stream()) { case CLIENT: - returnType = types.get("ClientStreamingCallable"); + returnType = typeStore.get("ClientStreamingCallable"); break; case SERVER: - returnType = types.get("ServerStreamingCallable"); + returnType = typeStore.get("ServerStreamingCallable"); break; case BIDI: - returnType = types.get("BidiStreamingCallable"); + returnType = typeStore.get("BidiStreamingCallable"); break; case NONE: // Fall through. default: - returnType = types.get(isLroCallable ? "OperationCallable" : "UnaryCallable"); + returnType = typeStore.get(isLroCallable ? "OperationCallable" : "UnaryCallable"); } String methodName = @@ -165,7 +162,9 @@ private static MethodDefinition createCallableGetterHelper( genericRefs.add(method.lro().metadataType().reference()); } else if (isPaged) { genericRefs.add( - types.get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())).reference()); + typeStore + .get(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) + .reference()); } else { genericRefs.add(method.outputType().reference()); } @@ -175,17 +174,17 @@ private static MethodDefinition createCallableGetterHelper( .setScope(ScopeNode.PUBLIC) .setReturnType(returnType) .setName(methodName) - .setBody(createThrowUOEBody(methodName, types)) + .setBody(createThrowUOEBody(methodName, typeStore)) .build(); } - private static MethodDefinition createOperationsStubGetter(Map types) { + private static MethodDefinition createOperationsStubGetter(TypeStore typeStore) { String methodName = "getOperationsStub"; return MethodDefinition.builder() .setScope(ScopeNode.PUBLIC) - .setReturnType(types.get("OperationsStub")) + .setReturnType(typeStore.get("OperationsStub")) .setName(methodName) - .setBody(createThrowUOEBody(methodName, types)) + .setBody(createThrowUOEBody(methodName, typeStore)) .build(); } @@ -210,8 +209,7 @@ private static boolean hasLroMethods(Service service) { return false; } - private static Map createTypes( - Service service, Map messageTypes) { + private static TypeStore createTypes(Service service, Map messageTypes) { List concreteClazzes = Arrays.asList( BackgroundResource.class, @@ -223,68 +221,30 @@ private static Map createTypes( ServerStreamingCallable.class, UnaryCallable.class, UnsupportedOperationException.class); - Map types = - concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); + TypeStore typeStore = new TypeStore(concreteClazzes); + typeStore.putMessageTypes(service.pakkage(), messageTypes); - // Vapor message types. - List msgs = new ArrayList(messageTypes.keySet()); - Collections.sort(msgs); - // Preconditions.checkState(false, "DEL: mesgs: " + msgs); - types.putAll( - messageTypes.entrySet().stream() - // Short-term hack for messages that have nested subtypes with colliding names. This - // should work as long as there isn't heavy usage of fully-qualified nested subtypes in - // general. A long-term fix would involve adding a custom type-store that handles - // fully-qualified types. - .filter(e -> e.getValue().outerNestedTypes().isEmpty()) - .collect( - Collectors.toMap( - e -> e.getValue().name(), - e -> - TypeNode.withReference( - VaporReference.builder() - .setName(e.getValue().name()) - .setPakkage(service.pakkage()) - .build())))); + // Vapor dependency typeStore. + typeStore.put("com.google.longrunning.stub", "OperationsStub"); - // Vapor dependency types. - types.put( - "OperationsStub", - TypeNode.withReference( - VaporReference.builder() - .setName("OperationsStub") - .setPakkage("com.google.longrunning.stub") - .build())); // Pagination types. - types.putAll( + typeStore.putAll( + service.pakkage(), service.methods().stream() .filter(m -> m.isPaged()) - .collect( - Collectors.toMap( - m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name()), - m -> - TypeNode.withReference( - VaporReference.builder() - .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) - .setPakkage(service.pakkage()) - .setEnclosingClassNames( - ClassNames.getServiceClientClassName(service)) - .setIsStaticImport(true) - .build())))); + .map(m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) + .collect(Collectors.toList()), + true, + ClassNames.getServiceClientClassName(service)); - return types; + return typeStore; } - private static List createThrowUOEBody( - String methodName, Map types) { + private static List createThrowUOEBody(String methodName, TypeStore typeStore) { return Arrays.asList( ExprStatement.withExpr( ThrowExpr.builder() - .setType(types.get("UnsupportedOperationException")) + .setType(typeStore.get("UnsupportedOperationException")) .setMessageExpr(String.format("Not implemented: %s()", methodName)) .build())); } diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java index 0cca729e39..870ef7bf5f 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java @@ -82,6 +82,7 @@ import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; import com.google.api.generator.gapic.composer.samplecode.SettingsSampleCodeComposer; +import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.Field; import com.google.api.generator.gapic.model.GapicBatchingSettings; import com.google.api.generator.gapic.model.GapicClass; @@ -101,7 +102,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -140,7 +140,7 @@ public class ServiceStubSettingsClassComposer { private static final ServiceStubSettingsClassComposer INSTANCE = new ServiceStubSettingsClassComposer(); - private static final Map STATIC_TYPES = createStaticTypes(); + private static final TypeStore FIXED_TYPESTORE = createStaticTypes(); private static final VariableExpr DEFAULT_SERVICE_SCOPES_VAR_EXPR = createDefaultServiceScopesVarExpr(); private static final VariableExpr NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR = @@ -162,35 +162,36 @@ public GapicClass generate( Map messageTypes) { // TODO(miraleung): Robustify this against a null serviceConfig. String pakkage = String.format("%s.stub", service.pakkage()); - Map types = createDynamicTypes(service, pakkage); + TypeStore typeStore = createDynamicTypes(service, pakkage); Map methodSettingsMemberVarExprs = createMethodSettingsClassMemberVarExprs( - service, serviceConfig, types, /* isNestedClass= */ false); + service, serviceConfig, typeStore, /* isNestedClass= */ false); String className = ClassNames.getServiceStubSettingsClassName(service); ClassDefinition classDef = ClassDefinition.builder() .setPackageString(pakkage) - .setHeaderCommentStatements(createClassHeaderComments(service, types.get(className))) + .setHeaderCommentStatements( + createClassHeaderComments(service, typeStore.get(className))) .setAnnotations(createClassAnnotations()) .setScope(ScopeNode.PUBLIC) .setName(className) - .setExtendsType(createExtendsType(service, types)) + .setExtendsType(createExtendsType(service, typeStore)) .setStatements( createClassStatements( - service, serviceConfig, methodSettingsMemberVarExprs, messageTypes, types)) - .setMethods(createClassMethods(service, methodSettingsMemberVarExprs, types)) + service, serviceConfig, methodSettingsMemberVarExprs, messageTypes, typeStore)) + .setMethods(createClassMethods(service, methodSettingsMemberVarExprs, typeStore)) .setNestedClasses( - Arrays.asList(createNestedBuilderClass(service, serviceConfig, types))) + Arrays.asList(createNestedBuilderClass(service, serviceConfig, typeStore))) .build(); return GapicClass.create(GapicClass.Kind.STUB, classDef); } private static List createClassAnnotations() { return Arrays.asList( - AnnotationNode.withType(STATIC_TYPES.get("BetaApi")), + AnnotationNode.withType(FIXED_TYPESTORE.get("BetaApi")), AnnotationNode.builder() - .setType(STATIC_TYPES.get("Generated")) + .setType(FIXED_TYPESTORE.get("Generated")) .setDescription("by gapic-generator-java") .build()); } @@ -220,10 +221,10 @@ private static List createClassHeaderComments( classType); } - private static TypeNode createExtendsType(Service service, Map types) { - TypeNode thisClassType = types.get(ClassNames.getServiceStubSettingsClassName(service)); + private static TypeNode createExtendsType(Service service, TypeStore typeStore) { + TypeNode thisClassType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service)); return TypeNode.withReference( - STATIC_TYPES + FIXED_TYPESTORE .get("StubSettings") .reference() .copyAndSetGenerics(Arrays.asList(thisClassType.reference()))); @@ -232,7 +233,7 @@ private static TypeNode createExtendsType(Service service, Map private static Map createMethodSettingsClassMemberVarExprs( Service service, GapicServiceConfig serviceConfig, - Map types, + TypeStore typeStore, boolean isNestedClass) { // Maintain insertion order. Map varExprs = new LinkedHashMap<>(); @@ -243,7 +244,7 @@ private static Map createMethodSettingsClassMemberVarExprs boolean hasBatchingSettings = !Objects.isNull(serviceConfig) && serviceConfig.hasBatchingSetting(service, method); TypeNode settingsType = - getCallSettingsType(method, types, hasBatchingSettings, isNestedClass); + getCallSettingsType(method, typeStore, hasBatchingSettings, isNestedClass); String varName = JavaStyle.toLowerCamelCase(String.format("%sSettings", method.name())); varExprs.put( varName, @@ -267,7 +268,7 @@ private static List createClassStatements( GapicServiceConfig serviceConfig, Map methodSettingsMemberVarExprs, Map messageTypes, - Map types) { + TypeStore typeStore) { Function exprToStatementFn = e -> ExprStatement.withExpr(e); List statements = new ArrayList<>(); @@ -283,7 +284,7 @@ private static List createClassStatements( .build(); MethodInvocationExpr listBuilderExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("ImmutableList")) + .setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableList")) .setGenerics(Arrays.asList(ConcreteReference.withClazz(String.class))) .setMethodName("builder") .build(); @@ -325,7 +326,7 @@ private static List createClassStatements( statements.add(EMPTY_LINE_STATEMENT); for (Expr pagingAssignExpr : - createPagingStaticAssignExprs(service, serviceConfig, messageTypes, types)) { + createPagingStaticAssignExprs(service, serviceConfig, messageTypes, typeStore)) { statements.add(exprToStatementFn.apply(pagingAssignExpr)); statements.add(EMPTY_LINE_STATEMENT); } @@ -351,7 +352,7 @@ private static List createPagingStaticAssignExprs( Service service, GapicServiceConfig serviceConfig, Map messageTypes, - Map types) { + TypeStore typeStore) { List descExprs = new ArrayList<>(); List factoryExprs = new ArrayList<>(); for (Method method : service.methods()) { @@ -407,10 +408,10 @@ private static List createPagingStaticAssignExprs( repeatedResponseType, repeatedFieldName, messageTypes, - types)); + typeStore)); factoryExprs.add( createPagedListResponseFactoryAssignExpr( - pagedListDescVarExpr, method, repeatedResponseType, types)); + pagedListDescVarExpr, method, repeatedResponseType, typeStore)); } descExprs.addAll(factoryExprs); @@ -423,7 +424,7 @@ private static Expr createPagedListDescriptorAssignExpr( TypeNode repeatedResponseType, String repeatedFieldName, Map messageTypes, - Map types) { + TypeStore typeStore) { MethodDefinition.Builder methodStarterBuilder = MethodDefinition.builder().setIsOverride(true).setScope(ScopeNode.PUBLIC); List anonClassMethods = new ArrayList<>(); @@ -600,12 +601,12 @@ private static Expr createPagedListResponseFactoryAssignExpr( VariableExpr pageStrDescVarExpr, Method method, TypeNode repeatedResponseType, - Map types) { + TypeStore typeStore) { Preconditions.checkState( method.isPaged(), String.format("Method %s is not paged", method.name())); // Create the PagedListResponseFactory. - TypeNode pagedResponseType = types.get(getPagedResponseTypeName(method.name())); + TypeNode pagedResponseType = typeStore.get(getPagedResponseTypeName(method.name())); TypeNode apiFutureType = TypeNode.withReference( ConcreteReference.builder() @@ -633,7 +634,7 @@ private static Expr createPagedListResponseFactoryAssignExpr( VariableExpr contextVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(STATIC_TYPES.get("ApiCallContext")) + .setType(FIXED_TYPESTORE.get("ApiCallContext")) .setName("context") .build()); VariableExpr futureResponseVarExpr = @@ -666,7 +667,7 @@ private static Expr createPagedListResponseFactoryAssignExpr( .setVariableExpr(pageContextVarExpr.toBuilder().setIsDecl(true).build()) .setValueExpr( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("PageContext")) + .setStaticReferenceType(FIXED_TYPESTORE.get("PageContext")) .setMethodName("create") .setArguments( callableVarExpr, pageStrDescVarExpr, requestVarExpr, contextVarExpr) @@ -676,7 +677,7 @@ private static Expr createPagedListResponseFactoryAssignExpr( Expr returnExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(types.get(getPagedResponseTypeName(method.name()))) + .setStaticReferenceType(typeStore.get(getPagedResponseTypeName(method.name()))) .setMethodName("createAsync") .setArguments(pageContextVarExpr, futureResponseVarExpr) .setReturnType(apiFutureType) @@ -707,7 +708,7 @@ private static Expr createPagedListResponseFactoryAssignExpr( Arrays.asList( method.inputType(), method.outputType(), - types.get(getPagedResponseTypeName(method.name()))) + typeStore.get(getPagedResponseTypeName(method.name()))) .stream() .map(t -> t.reference()) .collect(Collectors.toList())) @@ -739,13 +740,13 @@ private static Expr createPagedListResponseFactoryAssignExpr( private static List createClassMethods( Service service, Map methodSettingsMemberVarExprs, - Map types) { + TypeStore typeStore) { List javaMethods = new ArrayList<>(); javaMethods.addAll(createMethodSettingsGetterMethods(methodSettingsMemberVarExprs)); - javaMethods.add(createCreateStubMethod(service, types)); - javaMethods.addAll(createDefaultHelperAndGetterMethods(service, types)); - javaMethods.addAll(createBuilderHelperMethods(service, types)); - javaMethods.add(createClassConstructor(service, methodSettingsMemberVarExprs, types)); + javaMethods.add(createCreateStubMethod(service, typeStore)); + javaMethods.addAll(createDefaultHelperAndGetterMethods(service, typeStore)); + javaMethods.addAll(createBuilderHelperMethods(service, typeStore)); + javaMethods.add(createClassConstructor(service, methodSettingsMemberVarExprs, typeStore)); return javaMethods; } @@ -767,12 +768,11 @@ private static List createMethodSettingsGetterMethods( .collect(Collectors.toList()); } - private static MethodDefinition createCreateStubMethod( - Service service, Map types) { + private static MethodDefinition createCreateStubMethod(Service service, TypeStore typeStore) { // Set up the if-statement. Expr grpcTransportNameExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("GrpcTransportChannel")) + .setStaticReferenceType(FIXED_TYPESTORE.get("GrpcTransportChannel")) .setMethodName("getGrpcTransportName") .build(); @@ -794,12 +794,12 @@ private static MethodDefinition createCreateStubMethod( Expr createExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(types.get(ClassNames.getGrpcServiceStubClassName(service))) + .setStaticReferenceType(typeStore.get(ClassNames.getGrpcServiceStubClassName(service))) .setMethodName("create") .setArguments( ValueExpr.withValue( ThisObjectValue.withType( - types.get(ClassNames.getServiceStubSettingsClassName(service))))) + typeStore.get(ClassNames.getServiceStubSettingsClassName(service))))) .build(); IfStatement ifStatement = @@ -824,10 +824,10 @@ private static MethodDefinition createCreateStubMethod( ThrowExpr.builder().setType(exceptionType).setMessageExpr(errorMessageExpr).build()); // Put the method together. - TypeNode returnType = types.get(ClassNames.getServiceStubClassName(service)); + TypeNode returnType = typeStore.get(ClassNames.getServiceStubClassName(service)); AnnotationNode annotation = AnnotationNode.builder() - .setType(STATIC_TYPES.get("BetaApi")) + .setType(FIXED_TYPESTORE.get("BetaApi")) .setDescription( "A restructuring of stub classes is planned, so this may break in the future") .build(); @@ -843,7 +843,7 @@ private static MethodDefinition createCreateStubMethod( } private static List createDefaultHelperAndGetterMethods( - Service service, Map types) { + Service service, TypeStore typeStore) { List javaMethods = new ArrayList<>(); // Create the defaultExecutorProviderBuilder method. @@ -860,7 +860,7 @@ private static List createDefaultHelperAndGetterMethods( .setName("defaultExecutorProviderBuilder") .setReturnExpr( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("InstantiatingExecutorProvider")) + .setStaticReferenceType(FIXED_TYPESTORE.get("InstantiatingExecutorProvider")) .setMethodName("newBuilder") .setReturnType(returnType) .build()) @@ -903,7 +903,7 @@ private static List createDefaultHelperAndGetterMethods( ConcreteReference.withClazz(GoogleCredentialsProvider.Builder.class)); MethodInvocationExpr credsProviderBuilderExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("GoogleCredentialsProvider")) + .setStaticReferenceType(FIXED_TYPESTORE.get("GoogleCredentialsProvider")) .setMethodName("newBuilder") .build(); credsProviderBuilderExpr = @@ -930,7 +930,7 @@ private static List createDefaultHelperAndGetterMethods( ConcreteReference.withClazz(InstantiatingGrpcChannelProvider.Builder.class)); MethodInvocationExpr grpcChannelProviderBuilderExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("InstantiatingGrpcChannelProvider")) + .setStaticReferenceType(FIXED_TYPESTORE.get("InstantiatingGrpcChannelProvider")) .setMethodName("newBuilder") .build(); grpcChannelProviderBuilderExpr = @@ -957,7 +957,7 @@ private static List createDefaultHelperAndGetterMethods( .build()); // Create the defaultTransportChannelProvider method. - returnType = STATIC_TYPES.get("TransportChannelProvider"); + returnType = FIXED_TYPESTORE.get("TransportChannelProvider"); MethodInvocationExpr transportProviderBuilderExpr = MethodInvocationExpr.builder().setMethodName("defaultGrpcTransportProviderBuilder").build(); transportProviderBuilderExpr = @@ -980,13 +980,13 @@ private static List createDefaultHelperAndGetterMethods( TypeNode.withReference(ConcreteReference.withClazz(ApiClientHeaderProvider.Builder.class)); MethodInvocationExpr returnExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("ApiClientHeaderProvider")) + .setStaticReferenceType(FIXED_TYPESTORE.get("ApiClientHeaderProvider")) .setMethodName("newBuilder") .build(); MethodInvocationExpr versionArgExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("GaxProperties")) + .setStaticReferenceType(FIXED_TYPESTORE.get("GaxProperties")) .setMethodName("getLibraryVersion") .setArguments( VariableExpr.builder() @@ -997,7 +997,7 @@ private static List createDefaultHelperAndGetterMethods( .setName("class") .build()) .setStaticReferenceType( - types.get(ClassNames.getServiceStubSettingsClassName(service))) + typeStore.get(ClassNames.getServiceStubSettingsClassName(service))) .build()) .build(); @@ -1013,11 +1013,11 @@ private static List createDefaultHelperAndGetterMethods( .setMethodName("setTransportToken") .setArguments( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("GaxGrpcProperties")) + .setStaticReferenceType(FIXED_TYPESTORE.get("GaxGrpcProperties")) .setMethodName("getGrpcTokenName") .build(), MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("GaxGrpcProperties")) + .setStaticReferenceType(FIXED_TYPESTORE.get("GaxGrpcProperties")) .setMethodName("getGrpcVersion") .build()) .setReturnType(returnType) @@ -1025,7 +1025,7 @@ private static List createDefaultHelperAndGetterMethods( AnnotationNode annotation = AnnotationNode.builder() - .setType(STATIC_TYPES.get("BetaApi")) + .setType(FIXED_TYPESTORE.get("BetaApi")) .setDescription( "The surface for customizing headers is not stable yet and may change in the" + " future.") @@ -1044,10 +1044,10 @@ private static List createDefaultHelperAndGetterMethods( } private static List createBuilderHelperMethods( - Service service, Map types) { + Service service, TypeStore typeStore) { List javaMethods = new ArrayList<>(); // Create the newBuilder() method. - final TypeNode builderReturnType = types.get(NESTED_BUILDER_CLASS_NAME); + final TypeNode builderReturnType = typeStore.get(NESTED_BUILDER_CLASS_NAME); javaMethods.add( MethodDefinition.builder() .setHeaderCommentStatements(SettingsCommentComposer.NEW_BUILDER_METHOD_COMMENT) @@ -1069,7 +1069,7 @@ private static List createBuilderHelperMethods( VariableExpr clientContextVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(STATIC_TYPES.get("ClientContext")) + .setType(FIXED_TYPESTORE.get("ClientContext")) .setName("clientContext") .build()); javaMethods.add( @@ -1094,7 +1094,7 @@ private static List createBuilderHelperMethods( newBuilderFn.apply( ValueExpr.withValue( ThisObjectValue.withType( - types.get(ClassNames.getServiceStubClassName(service)))))) + typeStore.get(ClassNames.getServiceStubClassName(service)))))) .build()); return javaMethods; @@ -1103,18 +1103,18 @@ private static List createBuilderHelperMethods( private static MethodDefinition createClassConstructor( Service service, Map methodSettingsMemberVarExprs, - Map types) { - TypeNode thisType = types.get(ClassNames.getServiceStubSettingsClassName(service)); + TypeStore typeStore) { + TypeNode thisType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service)); final VariableExpr settingsBuilderVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(types.get(NESTED_BUILDER_CLASS_NAME)) + .setType(typeStore.get(NESTED_BUILDER_CLASS_NAME)) .setName("settingsBuilder") .build()); Expr superCtorExpr = ReferenceConstructorExpr.superBuilder() - .setType(STATIC_TYPES.get("StubSettings")) + .setType(FIXED_TYPESTORE.get("StubSettings")) .setArguments(settingsBuilderVarExpr) .build(); @@ -1152,10 +1152,10 @@ private static MethodDefinition createClassConstructor( } private static ClassDefinition createNestedBuilderClass( - Service service, @Nullable GapicServiceConfig serviceConfig, Map types) { + Service service, @Nullable GapicServiceConfig serviceConfig, TypeStore typeStore) { // TODO(miraleung): Robustify this against a null serviceConfig. String thisClassName = ClassNames.getServiceStubSettingsClassName(service); - TypeNode outerThisClassType = types.get(thisClassName); + TypeNode outerThisClassType = typeStore.get(thisClassName); String className = "Builder"; @@ -1164,14 +1164,14 @@ private static ClassDefinition createNestedBuilderClass( ConcreteReference.builder() .setClazz(StubSettings.Builder.class) .setGenerics( - Arrays.asList(types.get(thisClassName), types.get(className)).stream() + Arrays.asList(typeStore.get(thisClassName), typeStore.get(className)).stream() .map(t -> t.reference()) .collect(Collectors.toList())) .build()); Map nestedMethodSettingsMemberVarExprs = createMethodSettingsClassMemberVarExprs( - service, serviceConfig, types, /* isNestedClass= */ true); + service, serviceConfig, typeStore, /* isNestedClass= */ true); // TODO(miraleung): Fill this out. return ClassDefinition.builder() @@ -1187,7 +1187,7 @@ private static ClassDefinition createNestedBuilderClass( createNestedClassStatements(service, serviceConfig, nestedMethodSettingsMemberVarExprs)) .setMethods( createNestedClassMethods( - service, serviceConfig, extendsType, nestedMethodSettingsMemberVarExprs, types)) + service, serviceConfig, extendsType, nestedMethodSettingsMemberVarExprs, typeStore)) .build(); } @@ -1246,25 +1246,25 @@ private static List createNestedClassMethods( GapicServiceConfig serviceConfig, TypeNode superType, Map nestedMethodSettingsMemberVarExprs, - Map types) { + TypeStore typeStore) { List nestedClassMethods = new ArrayList<>(); nestedClassMethods.addAll( createNestedClassConstructorMethods( - service, serviceConfig, nestedMethodSettingsMemberVarExprs, types)); - nestedClassMethods.add(createNestedClassCreateDefaultMethod(types)); - nestedClassMethods.add(createNestedClassInitDefaultsMethod(service, serviceConfig, types)); - nestedClassMethods.add(createNestedClassApplyToAllUnaryMethodsMethod(superType, types)); + service, serviceConfig, nestedMethodSettingsMemberVarExprs, typeStore)); + nestedClassMethods.add(createNestedClassCreateDefaultMethod(typeStore)); + nestedClassMethods.add(createNestedClassInitDefaultsMethod(service, serviceConfig, typeStore)); + nestedClassMethods.add(createNestedClassApplyToAllUnaryMethodsMethod(superType, typeStore)); nestedClassMethods.add(createNestedClassUnaryMethodSettingsBuilderGetterMethod()); nestedClassMethods.addAll( createNestedClassSettingsBuilderGetterMethods(nestedMethodSettingsMemberVarExprs)); - nestedClassMethods.add(createNestedClassBuildMethod(service, types)); + nestedClassMethods.add(createNestedClassBuildMethod(service, typeStore)); return nestedClassMethods; } private static MethodDefinition createNestedClassInitDefaultsMethod( - Service service, @Nullable GapicServiceConfig serviceConfig, Map types) { + Service service, @Nullable GapicServiceConfig serviceConfig, TypeStore typeStore) { // TODO(miraleung): Robustify this against a null serviceConfig. - TypeNode builderType = types.get(NESTED_BUILDER_CLASS_NAME); + TypeNode builderType = typeStore.get(NESTED_BUILDER_CLASS_NAME); VariableExpr builderVarExpr = VariableExpr.withVariable( Variable.builder().setType(builderType).setName("builder").build()); @@ -1335,8 +1335,8 @@ private static List createNestedClassConstructorMethods( Service service, GapicServiceConfig serviceConfig, Map nestedMethodSettingsMemberVarExprs, - Map types) { - TypeNode builderType = types.get(NESTED_BUILDER_CLASS_NAME); + TypeStore typeStore) { + TypeNode builderType = typeStore.get(NESTED_BUILDER_CLASS_NAME); List ctorMethods = new ArrayList<>(); @@ -1352,7 +1352,7 @@ private static List createNestedClassConstructorMethods( .setType(builderType) .setArguments( CastExpr.builder() - .setType(STATIC_TYPES.get("ClientContext")) + .setType(FIXED_TYPESTORE.get("ClientContext")) .setExpr(ValueExpr.createNullExpr()) .build()) .build()))) @@ -1362,7 +1362,7 @@ private static List createNestedClassConstructorMethods( VariableExpr clientContextVarExpr = VariableExpr.withVariable( Variable.builder() - .setType(STATIC_TYPES.get("ClientContext")) + .setType(FIXED_TYPESTORE.get("ClientContext")) .setName("clientContext") .build()); Reference pagedSettingsBuilderRef = @@ -1431,7 +1431,7 @@ private static List createNestedClassConstructorMethods( } Expr newBatchingSettingsExpr = MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("BatchingSettings")) + .setStaticReferenceType(FIXED_TYPESTORE.get("BatchingSettings")) .setMethodName("newBuilder") .build(); newBatchingSettingsExpr = @@ -1450,7 +1450,7 @@ private static List createNestedClassConstructorMethods( .setArguments( VariableExpr.withVariable( Variable.builder() - .setType(STATIC_TYPES.get("BatchingDescriptor")) + .setType(FIXED_TYPESTORE.get("BatchingDescriptor")) .setName(batchingDescVarName) .build())) .build(); @@ -1475,7 +1475,7 @@ private static List createNestedClassConstructorMethods( VariableExpr argVar = VariableExpr.withVariable( Variable.builder() - .setType(STATIC_TYPES.get("PagedListResponseFactory")) + .setType(FIXED_TYPESTORE.get("PagedListResponseFactory")) .setName(memberVarName) .build()); Expr builderExpr = @@ -1499,7 +1499,7 @@ private static List createNestedClassConstructorMethods( .setVariableExpr(NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR) .setValueExpr( MethodInvocationExpr.builder() - .setStaticReferenceType(STATIC_TYPES.get("ImmutableList")) + .setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableList")) .setGenerics( NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR .type() @@ -1537,7 +1537,7 @@ private static List createNestedClassConstructorMethods( .build()); // Third constructor that takes a ServiceStubSettings. - TypeNode outerSettingsType = types.get(ClassNames.getServiceStubSettingsClassName(service)); + TypeNode outerSettingsType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service)); VariableExpr settingsVarExpr = VariableExpr.withVariable( Variable.builder().setType(outerSettingsType).setName("settings").build()); @@ -1586,12 +1586,11 @@ private static List createNestedClassConstructorMethods( return ctorMethods; } - private static MethodDefinition createNestedClassCreateDefaultMethod( - Map types) { + private static MethodDefinition createNestedClassCreateDefaultMethod(TypeStore typeStore) { List bodyStatements = new ArrayList<>(); // Initialize the builder: Builder builder = new Builder((ClientContext) null); - TypeNode builderType = types.get(NESTED_BUILDER_CLASS_NAME); + TypeNode builderType = typeStore.get(NESTED_BUILDER_CLASS_NAME); VariableExpr builderVarExpr = VariableExpr.withVariable( Variable.builder().setType(builderType).setName("builder").build()); @@ -1604,7 +1603,7 @@ private static MethodDefinition createNestedClassCreateDefaultMethod( .setType(builderType) .setArguments( CastExpr.builder() - .setType(STATIC_TYPES.get("ClientContext")) + .setType(FIXED_TYPESTORE.get("ClientContext")) .setExpr(ValueExpr.createNullExpr()) .build()) .build()) @@ -1679,7 +1678,7 @@ private static MethodDefinition createNestedClassCreateDefaultMethod( } private static MethodDefinition createNestedClassApplyToAllUnaryMethodsMethod( - TypeNode superType, Map types) { + TypeNode superType, TypeStore typeStore) { List apiFunctionTypeGenerics = new ArrayList<>(); apiFunctionTypeGenerics.addAll( NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR.type().reference().generics()); @@ -1703,7 +1702,7 @@ private static MethodDefinition createNestedClassApplyToAllUnaryMethodsMethod( .setArguments(NESTED_UNARY_METHOD_SETTINGS_BUILDERS_VAR_EXPR, settingsUpdaterVarExpr) .build(); - TypeNode returnType = types.get(NESTED_BUILDER_CLASS_NAME); + TypeNode returnType = typeStore.get(NESTED_BUILDER_CLASS_NAME); Expr returnExpr = ValueExpr.withValue(ThisObjectValue.withType(returnType)); return MethodDefinition.builder() @@ -1740,7 +1739,7 @@ private static List createNestedClassSettingsBuilderGetterMeth List lroBetaAnnotations = Arrays.asList( AnnotationNode.builder() - .setType(STATIC_TYPES.get("BetaApi")) + .setType(FIXED_TYPESTORE.get("BetaApi")) .setDescription( "The surface for use by generated code is not stable yet and may change in the" + " future.") @@ -1769,9 +1768,9 @@ private static List createNestedClassSettingsBuilderGetterMeth } private static MethodDefinition createNestedClassBuildMethod( - Service service, Map types) { - TypeNode outerClassType = types.get(ClassNames.getServiceStubSettingsClassName(service)); - TypeNode builderType = types.get(NESTED_BUILDER_CLASS_NAME); + Service service, TypeStore typeStore) { + TypeNode outerClassType = typeStore.get(ClassNames.getServiceStubSettingsClassName(service)); + TypeNode builderType = typeStore.get(NESTED_BUILDER_CLASS_NAME); return MethodDefinition.builder() .setIsOverride(true) @@ -1787,7 +1786,7 @@ private static MethodDefinition createNestedClassBuildMethod( .build(); } - private static Map createStaticTypes() { + private static TypeStore createStaticTypes() { List concreteClazzes = Arrays.asList( ApiCallContext.class, @@ -1837,66 +1836,36 @@ private static Map createStaticTypes() { TransportChannelProvider.class, UnaryCallSettings.class, UnaryCallable.class); - return concreteClazzes.stream() - .collect( - Collectors.toMap( - c -> c.getSimpleName(), - c -> TypeNode.withReference(ConcreteReference.withClazz(c)))); + return new TypeStore(concreteClazzes); } - private static Map createDynamicTypes(Service service, String pakkage) { - String thisClassName = ClassNames.getServiceStubSettingsClassName(service); - Map dynamicTypes = new HashMap<>(); + private static TypeStore createDynamicTypes(Service service, String pakkage) { + TypeStore typeStore = new TypeStore(); // This type. - dynamicTypes.put( - thisClassName, - TypeNode.withReference( - VaporReference.builder().setName(thisClassName).setPakkage(pakkage).build())); + String thisClassName = ClassNames.getServiceStubSettingsClassName(service); + typeStore.putAll( + pakkage, + Arrays.asList( + thisClassName, + ClassNames.getGrpcServiceStubClassName(service), + ClassNames.getServiceStubSettingsClassName(service), + ClassNames.getServiceStubClassName(service))); // Nested builder class. - dynamicTypes.put( - NESTED_BUILDER_CLASS_NAME, - TypeNode.withReference( - VaporReference.builder() - .setName(NESTED_BUILDER_CLASS_NAME) - .setPakkage(pakkage) - .setEnclosingClassNames(thisClassName) - .setIsStaticImport(true) - .build())); - - // Other generated stub classes. - dynamicTypes.putAll( - Arrays.asList( - ClassNames.getGrpcServiceStubClassName(service), - ClassNames.getServiceStubSettingsClassName(service), - ClassNames.getServiceStubClassName(service)) - .stream() - .collect( - Collectors.toMap( - n -> n, - n -> - TypeNode.withReference( - VaporReference.builder().setName(n).setPakkage(pakkage).build())))); + typeStore.put(pakkage, NESTED_BUILDER_CLASS_NAME, true, thisClassName); // Pagination types. - dynamicTypes.putAll( + typeStore.putAll( + service.pakkage(), service.methods().stream() .filter(m -> m.isPaged()) - .collect( - Collectors.toMap( - m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name()), - m -> - TypeNode.withReference( - VaporReference.builder() - .setName(getPagedResponseTypeName(m.name())) - .setPakkage(service.pakkage()) - .setEnclosingClassNames( - ClassNames.getServiceClientClassName(service)) - .setIsStaticImport(true) - .build())))); - - return dynamicTypes; + .map(m -> String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) + .collect(Collectors.toList()), + true, + ClassNames.getServiceClientClassName(service)); + + return typeStore; } private static VariableExpr createDefaultServiceScopesVarExpr() { @@ -1958,7 +1927,7 @@ private static VariableExpr createNestedRetryParamDefinitionsVarExpr() { ConcreteReference.builder() .setClazz(ImmutableMap.class) .setGenerics( - Arrays.asList(TypeNode.STRING, STATIC_TYPES.get("RetrySettings")).stream() + Arrays.asList(TypeNode.STRING, FIXED_TYPESTORE.get("RetrySettings")).stream() .map(t -> t.reference()) .collect(Collectors.toList())) .build()); @@ -1975,7 +1944,7 @@ private static String getPagedResponseTypeName(String methodName) { private static TypeNode getCallSettingsType( Method method, - Map types, + TypeStore typeStore, boolean isBatchingSettings, final boolean isSettingsBuilder) { Function typeMakerFn = @@ -2021,7 +1990,7 @@ private static TypeNode getCallSettingsType( generics.add(method.inputType().reference()); generics.add(method.outputType().reference()); if (method.isPaged()) { - generics.add(types.get(getPagedResponseTypeName(method.name())).reference()); + generics.add(typeStore.get(getPagedResponseTypeName(method.name())).reference()); } return TypeNode.withReference(callSettingsType.reference().copyAndSetGenerics(generics)); } diff --git a/src/main/java/com/google/api/generator/gapic/composer/samplecode/SampleCodeWriter.java b/src/main/java/com/google/api/generator/gapic/composer/samplecode/SampleCodeWriter.java index 1a6e4be89c..8f8f59d5e6 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/samplecode/SampleCodeWriter.java +++ b/src/main/java/com/google/api/generator/gapic/composer/samplecode/SampleCodeWriter.java @@ -21,7 +21,7 @@ public final class SampleCodeWriter { - public static String write(Statement ... statement) { + public static String write(Statement... statement) { return write(Arrays.asList(statement)); } diff --git a/src/main/java/com/google/api/generator/gapic/composer/store/BUILD.bazel b/src/main/java/com/google/api/generator/gapic/composer/store/BUILD.bazel new file mode 100644 index 0000000000..29cd8acc5f --- /dev/null +++ b/src/main/java/com/google/api/generator/gapic/composer/store/BUILD.bazel @@ -0,0 +1,38 @@ +load("@rules_java//java:defs.bzl", "java_library") + +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "store_files", + srcs = glob(["*.java"]), +) + +java_library( + name = "store", + srcs = [ + ":store_files", + ], + deps = [ + "//src/main/java/com/google/api/generator/engine/ast", + "//src/main/java/com/google/api/generator/gapic:status_java_proto", + "//src/main/java/com/google/api/generator/gapic/model", + "//src/main/java/com/google/api/generator/gapic/utils", + "@com_google_api_api_common//jar", + "@com_google_api_gax_java//gax", + "@com_google_api_gax_java//gax-grpc:gax_grpc", + "@com_google_code_findbugs_jsr305//jar", + "@com_google_googleapis//google/api:api_java_proto", + "@com_google_googleapis//google/longrunning:longrunning_java_proto", + "@com_google_googleapis//google/rpc:rpc_java_proto", + "@com_google_guava_guava//jar", + "@com_google_protobuf//:protobuf_java", + "@com_google_protobuf//:protobuf_java_util", + "@com_google_protobuf//java/core", + "@io_grpc_grpc_java//api", + "@io_grpc_grpc_java//protobuf", + "@io_grpc_grpc_java//stub", + "@javax_annotation_javax_annotation_api//jar", + "@junit_junit//jar", + "@org_threeten_threetenbp//jar", + ], +) diff --git a/src/main/java/com/google/api/generator/gapic/composer/store/TypeStore.java b/src/main/java/com/google/api/generator/gapic/composer/store/TypeStore.java new file mode 100644 index 0000000000..aa7ff06647 --- /dev/null +++ b/src/main/java/com/google/api/generator/gapic/composer/store/TypeStore.java @@ -0,0 +1,98 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.google.api.generator.gapic.composer.store; + +import com.google.api.generator.engine.ast.ConcreteReference; +import com.google.api.generator.engine.ast.TypeNode; +import com.google.api.generator.engine.ast.VaporReference; +import com.google.api.generator.gapic.model.Message; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class TypeStore { + private Map store = new HashMap<>(); + + public TypeStore() {} + + public TypeStore(List concreteClasses) { + store.putAll( + concreteClasses.stream() + .collect( + Collectors.toMap( + c -> c.getSimpleName(), + c -> TypeNode.withReference(ConcreteReference.withClazz(c))))); + } + + public TypeNode get(String typeName) { + return store.get(typeName); + } + + public void put(String pakkage, String typeName) { + store.put( + typeName, + TypeNode.withReference( + VaporReference.builder().setName(typeName).setPakkage(pakkage).build())); + } + + public void putAll(String pakkage, List typeNames) { + for (String typeName : typeNames) { + put(pakkage, typeName); + } + } + + public void put( + String pakkage, String typeName, boolean isStaticImport, String... enclosingClassNames) { + store.put( + typeName, + TypeNode.withReference( + VaporReference.builder() + .setName(typeName) + .setEnclosingClassNames(enclosingClassNames) + .setPakkage(pakkage) + .setIsStaticImport(isStaticImport) + .build())); + } + + public void putAll( + String pakkage, + List typeNames, + boolean isStaticImport, + String... enclosingClassNames) { + for (String typeName : typeNames) { + put(pakkage, typeName, isStaticImport, enclosingClassNames); + } + } + + public void putMessageTypes(String pakkage, Map messages) { + store.putAll( + messages.entrySet().stream() + // Short-term hack for messages that have nested subtypes with colliding names. This + // should work as long as there isn't heavy usage of fully-qualified nested subtypes in + // general. A long-term fix would involve adding a custom type-store that handles + // fully-qualified types. + .filter(e -> e.getValue().outerNestedTypes().isEmpty()) + .collect( + Collectors.toMap( + e -> e.getValue().name(), + e -> + TypeNode.withReference( + VaporReference.builder() + .setName(e.getValue().name()) + .setPakkage(pakkage) + .build())))); + } +} From 7a3f6c20ec82bf8d893a954c0df2ef4ba65e173f Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Mon, 21 Dec 2020 15:56:46 -0800 Subject: [PATCH 05/11] fix: remove superfluous varexpr helper in ServiceClientClassComposer --- .../gapic/composer/ServiceClientClassComposer.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java index 3436257a60..11b87f5325 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java @@ -801,9 +801,12 @@ private static List createBackgroundResourceMethods( List arguments = Arrays.asList( - VariableExpr.builder().setVariable(createVariable("duration", TypeNode.LONG)).build(), VariableExpr.builder() - .setVariable(createVariable("unit", typeStore.get("TimeUnit"))) + .setVariable(Variable.builder().setName("duration").setType(TypeNode.LONG).build()) + .build(), + VariableExpr.builder() + .setVariable( + Variable.builder().setName("unit").setType(typeStore.get("TimeUnit")).build()) .build()); MethodDefinition awaitTerminationMethod = @@ -1456,10 +1459,6 @@ private static void createVaporTypes(Service service, TypeStore typeStore) { ClassNames.getServiceClientClassName(service)); } - private static Variable createVariable(String name, TypeNode type) { - return Variable.builder().setName(name).setType(type).build(); - } - private static List getGenericsForCallable( CallableMethodKind kind, Method method, TypeStore typeStore) { if (kind.equals(CallableMethodKind.LRO)) { From 980e5bdcbf26292ff76b851258ee1f232d5422e7 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Mon, 21 Dec 2020 16:00:25 -0800 Subject: [PATCH 06/11] fix: move varexpr helper to local lambda for better locality --- .../ServiceClientSampleCodeComposer.java | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java index c4a2e5f4f8..14a2885d43 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java @@ -27,12 +27,17 @@ import com.google.api.generator.gapic.composer.samplecode.SampleCodeWriter; import com.google.api.generator.gapic.utils.JavaStyle; import java.util.Arrays; +import java.util.function.BiFunction; public class ServiceClientSampleCodeComposer { // TODO(summerji): Add unit tests for ServiceClientSampleCodeComposer. public static String composeClassHeaderCredentialsSampleCode( TypeNode clientType, TypeNode settingsType) { + // Funcdtion instead of a helper for better config / locality reference. + BiFunction createVarExprFn = + (s, t) -> VariableExpr.withVariable(Variable.builder().setName(s).setType(t).build()); + // Initialize clientSettings with builder() method. // e.g. EchoSettings echoSettings = // EchoSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create("myCredentials")).build(); @@ -44,7 +49,7 @@ public static String composeClassHeaderCredentialsSampleCode( .setName("myCredentials") .setPakkage(clientType.reference().pakkage()) .build()); - VariableExpr settingsVarExpr = createVariableExpr(settingsName, settingsType); + VariableExpr settingsVarExpr = createVarExprFn.apply(settingsName, settingsType); MethodInvocationExpr newBuilderMethodExpr = MethodInvocationExpr.builder() .setStaticReferenceType(settingsType) @@ -55,7 +60,7 @@ public static String composeClassHeaderCredentialsSampleCode( MethodInvocationExpr credentialArgExpr = MethodInvocationExpr.builder() .setStaticReferenceType(fixedCredentialProvideType) - .setArguments(createVariableExpr("myCredentials", myCredentialsType)) + .setArguments(createVarExprFn.apply("myCredentials", myCredentialsType)) .setMethodName("create") .build(); MethodInvocationExpr credentialsMethodExpr = @@ -78,7 +83,7 @@ public static String composeClassHeaderCredentialsSampleCode( // Initialized client with create() method. // e.g. EchoClient echoClient = EchoClient.create(echoSettings); - VariableExpr clientVarExpr = createVariableExpr(clientName, clientType); + VariableExpr clientVarExpr = createVarExprFn.apply(clientName, clientType); MethodInvocationExpr createMethodExpr = MethodInvocationExpr.builder() .setStaticReferenceType(clientType) @@ -99,6 +104,10 @@ public static String composeClassHeaderCredentialsSampleCode( public static String composeClassHeaderEndpointSampleCode( TypeNode clientType, TypeNode settingsType) { + // Funcdtion instead of a helper for better config / locality reference. + BiFunction createVarExprFn = + (s, t) -> VariableExpr.withVariable(Variable.builder().setName(s).setType(t).build()); + // Initialize client settings with builder() method. // e.g. EchoSettings echoSettings = EchoSettings.newBuilder().setEndpoint("myEndpoint").build(); String settingsName = JavaStyle.toLowerCamelCase(settingsType.reference().name()); @@ -109,7 +118,7 @@ public static String composeClassHeaderEndpointSampleCode( .setName("myEndpoint") .setPakkage(clientType.reference().pakkage()) .build()); - VariableExpr settingsVarExpr = createVariableExpr(settingsName, settingsType); + VariableExpr settingsVarExpr = createVarExprFn.apply(settingsName, settingsType); MethodInvocationExpr newBuilderMethodExpr = MethodInvocationExpr.builder() .setStaticReferenceType(settingsType) @@ -118,7 +127,7 @@ public static String composeClassHeaderEndpointSampleCode( MethodInvocationExpr credentialsMethodExpr = MethodInvocationExpr.builder() .setExprReferenceExpr(newBuilderMethodExpr) - .setArguments(createVariableExpr("myEndpoint", myEndpointType)) + .setArguments(createVarExprFn.apply("myEndpoint", myEndpointType)) .setMethodName("setEndpoint") .build(); MethodInvocationExpr buildMethodExpr = @@ -136,7 +145,7 @@ public static String composeClassHeaderEndpointSampleCode( // Initialize client with create() method. // e.g. EchoClient echoClient = EchoClient.create(echoSettings); - VariableExpr clientVarExpr = createVariableExpr(clientName, clientType); + VariableExpr clientVarExpr = createVarExprFn.apply(clientName, clientType); MethodInvocationExpr createMethodExpr = MethodInvocationExpr.builder() .setStaticReferenceType(clientType) @@ -155,11 +164,4 @@ public static String composeClassHeaderEndpointSampleCode( ExprStatement.withExpr(initSettingsVarExpr), ExprStatement.withExpr(initClientVarExpr))); } - - // ======================================== Helpers ==========================================// - - private static VariableExpr createVariableExpr(String variableName, TypeNode type) { - return VariableExpr.withVariable( - Variable.builder().setName(variableName).setType(type).build()); - } } From 18737e189f0967c5c391c42e2505f265257a91cf Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Mon, 21 Dec 2020 16:08:20 -0800 Subject: [PATCH 07/11] fix: move ServiceClientSampleCodeComposer to composer.samplecode --- .../generator/gapic/composer/ServiceClientCommentComposer.java | 1 + .../google/api/generator/gapic/composer/samplecode/BUILD.bazel | 1 + .../{ => samplecode}/ServiceClientSampleCodeComposer.java | 3 +-- 3 files changed, 3 insertions(+), 2 deletions(-) rename src/main/java/com/google/api/generator/gapic/composer/{ => samplecode}/ServiceClientSampleCodeComposer.java (98%) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java index 6ed371a489..c8ba481a9a 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java @@ -17,6 +17,7 @@ import com.google.api.generator.engine.ast.CommentStatement; import com.google.api.generator.engine.ast.JavaDocComment; import com.google.api.generator.engine.ast.TypeNode; +import com.google.api.generator.gapic.composer.samplecode.ServiceClientSampleCodeComposer; import com.google.api.generator.gapic.model.Method; import com.google.api.generator.gapic.model.MethodArgument; import com.google.api.generator.gapic.model.Service; diff --git a/src/main/java/com/google/api/generator/gapic/composer/samplecode/BUILD.bazel b/src/main/java/com/google/api/generator/gapic/composer/samplecode/BUILD.bazel index 54f203fff4..822cf0b169 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/samplecode/BUILD.bazel +++ b/src/main/java/com/google/api/generator/gapic/composer/samplecode/BUILD.bazel @@ -17,6 +17,7 @@ java_library( "//src/main/java/com/google/api/generator/engine/writer", "//src/main/java/com/google/api/generator/gapic/model", "//src/main/java/com/google/api/generator/gapic/utils", + "@com_google_api_gax_java//gax", "@google_java_format_all_deps//jar", ], ) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java b/src/main/java/com/google/api/generator/gapic/composer/samplecode/ServiceClientSampleCodeComposer.java similarity index 98% rename from src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java rename to src/main/java/com/google/api/generator/gapic/composer/samplecode/ServiceClientSampleCodeComposer.java index 14a2885d43..892e4bb44d 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/samplecode/ServiceClientSampleCodeComposer.java @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package com.google.api.generator.gapic.composer; +package com.google.api.generator.gapic.composer.samplecode; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.api.generator.engine.ast.AssignmentExpr; @@ -24,7 +24,6 @@ import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; -import com.google.api.generator.gapic.composer.samplecode.SampleCodeWriter; import com.google.api.generator.gapic.utils.JavaStyle; import java.util.Arrays; import java.util.function.BiFunction; From f94bca8f68a5f61eeb598d78ac97950b32930049 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Mon, 21 Dec 2020 16:31:20 -0800 Subject: [PATCH 08/11] refactor: pull sample code creation out of ServiceClientCommentComposer --- .../composer/ServiceClientClassComposer.java | 22 ++++++++++++++----- .../ServiceClientCommentComposer.java | 11 +++------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java index 11b87f5325..042da51ac5 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java @@ -34,6 +34,7 @@ import com.google.api.generator.engine.ast.AssignmentExpr; import com.google.api.generator.engine.ast.CastExpr; import com.google.api.generator.engine.ast.ClassDefinition; +import com.google.api.generator.engine.ast.CommentStatement; import com.google.api.generator.engine.ast.ConcreteReference; import com.google.api.generator.engine.ast.Expr; import com.google.api.generator.engine.ast.ExprStatement; @@ -53,6 +54,7 @@ import com.google.api.generator.engine.ast.ValueExpr; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.samplecode.ServiceClientSampleCodeComposer; import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.Field; import com.google.api.generator.gapic.model.GapicClass; @@ -118,11 +120,7 @@ public GapicClass generate(Service service, Map messageTypes) { ClassDefinition classDef = ClassDefinition.builder() - .setHeaderCommentStatements( - ServiceClientCommentComposer.createClassHeaderComments( - service, - typeStore.get(ClassNames.getServiceClientClassName(service)), - typeStore.get(ClassNames.getServiceSettingsClassName(service)))) + .setHeaderCommentStatements(createClassHeaderComments(service, typeStore)) .setPackageString(pakkage) .setAnnotations(createClassAnnotations(typeStore)) .setScope(ScopeNode.PUBLIC) @@ -148,6 +146,20 @@ private static List createClassImplements(TypeStore typeStore) { return Arrays.asList(typeStore.get("BackgroundResource")); } + private static List createClassHeaderComments( + Service service, TypeStore typeStore) { + TypeNode clientType = typeStore.get(ClassNames.getServiceClientClassName(service)); + TypeNode settingsType = typeStore.get(ClassNames.getServiceSettingsClassName(service)); + String credentialsSampleCode = + ServiceClientSampleCodeComposer.composeClassHeaderCredentialsSampleCode( + clientType, settingsType); + String endpointSampleCode = + ServiceClientSampleCodeComposer.composeClassHeaderEndpointSampleCode( + clientType, settingsType); + return ServiceClientCommentComposer.createClassHeaderComments( + service, credentialsSampleCode, endpointSampleCode); + } + private static List createClassMethods( Service service, Map messageTypes, diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java index c8ba481a9a..9f3cc83062 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java @@ -17,7 +17,6 @@ import com.google.api.generator.engine.ast.CommentStatement; import com.google.api.generator.engine.ast.JavaDocComment; import com.google.api.generator.engine.ast.TypeNode; -import com.google.api.generator.gapic.composer.samplecode.ServiceClientSampleCodeComposer; import com.google.api.generator.gapic.model.Method; import com.google.api.generator.gapic.model.MethodArgument; import com.google.api.generator.gapic.model.Service; @@ -109,7 +108,7 @@ class ServiceClientCommentComposer { + " operation returned by another API method call."); static List createClassHeaderComments( - Service service, TypeNode clientType, TypeNode settingsType) { + Service service, String credentialsSampleCode, String endpointSampleCode) { JavaDocComment.Builder classHeaderJavadocBuilder = JavaDocComment.builder(); if (service.hasDescription()) { classHeaderJavadocBuilder = @@ -140,13 +139,9 @@ static List createClassHeaderComments( SERVICE_DESCRIPTION_CUSTOMIZE_SUMMARY_PATTERN, ClassNames.getServiceSettingsClassName(service))); classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_CREDENTIALS_SUMMARY_STRING); - classHeaderJavadocBuilder.addSampleCode( - ServiceClientSampleCodeComposer.composeClassHeaderCredentialsSampleCode( - clientType, settingsType)); + classHeaderJavadocBuilder.addSampleCode(credentialsSampleCode); classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_ENDPOINT_SUMMARY_STRING); - classHeaderJavadocBuilder.addSampleCode( - ServiceClientSampleCodeComposer.composeClassHeaderEndpointSampleCode( - clientType, settingsType)); + classHeaderJavadocBuilder.addSampleCode(endpointSampleCode); classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_SAMPLE_REFERENCE_STRING); From 7c58e0b1679452d48018d02e129051e5b7c4ef23 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Mon, 21 Dec 2020 17:36:36 -0800 Subject: [PATCH 09/11] refactor: move comment composers into dedicated package --- .../google/api/generator/gapic/BUILD.bazel | 1 + .../api/generator/gapic/composer/BUILD.bazel | 2 ++ .../ClientLibraryPackageInfoComposer.java | 1 + .../generator/gapic/composer/Composer.java | 1 + ...pcServiceCallableFactoryClassComposer.java | 2 ++ .../GrpcServiceStubClassComposer.java | 2 ++ .../composer/MockServiceClassComposer.java | 1 + .../MockServiceImplClassComposer.java | 1 + .../ResourceNameHelperClassComposer.java | 1 + .../composer/ServiceClientClassComposer.java | 2 ++ .../ServiceClientTestClassComposer.java | 1 + .../ServiceSettingsClassComposer.java | 2 ++ .../composer/ServiceStubClassComposer.java | 2 ++ .../ServiceStubSettingsClassComposer.java | 2 ++ .../gapic/composer/comment/BUILD.bazel | 22 ++++++++++++++ .../{ => comment}/CommentComposer.java | 2 +- .../ServiceClientCommentComposer.java | 23 +++++++------- .../SettingsCommentComposer.java | 30 +++++++++---------- .../{ => comment}/StubCommentComposer.java | 11 +++---- .../gapic/composer/utils/BUILD.bazel | 18 +++++++++++ .../composer/{ => utils}/ClassNames.java | 20 ++++++------- 21 files changed, 105 insertions(+), 42 deletions(-) create mode 100644 src/main/java/com/google/api/generator/gapic/composer/comment/BUILD.bazel rename src/main/java/com/google/api/generator/gapic/composer/{ => comment}/CommentComposer.java (97%) rename src/main/java/com/google/api/generator/gapic/composer/{ => comment}/ServiceClientCommentComposer.java (93%) rename src/main/java/com/google/api/generator/gapic/composer/{ => comment}/SettingsCommentComposer.java (84%) rename src/main/java/com/google/api/generator/gapic/composer/{ => comment}/StubCommentComposer.java (86%) create mode 100644 src/main/java/com/google/api/generator/gapic/composer/utils/BUILD.bazel rename src/main/java/com/google/api/generator/gapic/composer/{ => utils}/ClassNames.java (79%) diff --git a/src/main/java/com/google/api/generator/gapic/BUILD.bazel b/src/main/java/com/google/api/generator/gapic/BUILD.bazel index 93e9d3077a..37a314ed0b 100644 --- a/src/main/java/com/google/api/generator/gapic/BUILD.bazel +++ b/src/main/java/com/google/api/generator/gapic/BUILD.bazel @@ -6,6 +6,7 @@ filegroup( name = "gapic_files", srcs = glob(["*.java"]) + [ "//src/main/java/com/google/api/generator/gapic/composer:composer_files", + "//src/main/java/com/google/api/generator/gapic/composer/comment:comment_files", "//src/main/java/com/google/api/generator/gapic/composer/samplecode:samplecode_files", "//src/main/java/com/google/api/generator/gapic/composer/store:store_files", "//src/main/java/com/google/api/generator/gapic/model:model_files", diff --git a/src/main/java/com/google/api/generator/gapic/composer/BUILD.bazel b/src/main/java/com/google/api/generator/gapic/composer/BUILD.bazel index 4e5946c30f..4555aed048 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/BUILD.bazel +++ b/src/main/java/com/google/api/generator/gapic/composer/BUILD.bazel @@ -17,8 +17,10 @@ java_library( "//src/main/java/com/google/api/generator/engine/ast", "//src/main/java/com/google/api/generator/engine/writer", "//src/main/java/com/google/api/generator/gapic:status_java_proto", + "//src/main/java/com/google/api/generator/gapic/composer/comment", "//src/main/java/com/google/api/generator/gapic/composer/samplecode", "//src/main/java/com/google/api/generator/gapic/composer/store", + "//src/main/java/com/google/api/generator/gapic/composer/utils", "//src/main/java/com/google/api/generator/gapic/model", "//src/main/java/com/google/api/generator/gapic/utils", "@com_google_api_api_common//jar", diff --git a/src/main/java/com/google/api/generator/gapic/composer/ClientLibraryPackageInfoComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ClientLibraryPackageInfoComposer.java index 4cf054f178..fa6de000a1 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ClientLibraryPackageInfoComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ClientLibraryPackageInfoComposer.java @@ -20,6 +20,7 @@ import com.google.api.generator.engine.ast.JavaDocComment; import com.google.api.generator.engine.ast.PackageInfoDefinition; import com.google.api.generator.engine.ast.TypeNode; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.GapicContext; import com.google.api.generator.gapic.model.GapicPackageInfo; import com.google.api.generator.gapic.model.Service; diff --git a/src/main/java/com/google/api/generator/gapic/composer/Composer.java b/src/main/java/com/google/api/generator/gapic/composer/Composer.java index 02e1dc9bcc..58f57b93e9 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/Composer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/Composer.java @@ -16,6 +16,7 @@ import com.google.api.generator.engine.ast.ClassDefinition; import com.google.api.generator.engine.ast.ScopeNode; +import com.google.api.generator.gapic.composer.comment.CommentComposer; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.GapicContext; diff --git a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposer.java index da761c834c..672a35804f 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposer.java @@ -37,7 +37,9 @@ import com.google.api.generator.engine.ast.TypeNode; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.comment.StubCommentComposer; import com.google.api.generator.gapic.composer.store.TypeStore; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; diff --git a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java index 3f22fc65b0..a43f27b91a 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java @@ -48,7 +48,9 @@ import com.google.api.generator.engine.ast.ValueExpr; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.comment.StubCommentComposer; import com.google.api.generator.gapic.composer.store.TypeStore; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; diff --git a/src/main/java/com/google/api/generator/gapic/composer/MockServiceClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/MockServiceClassComposer.java index c9af986535..a029a25d39 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/MockServiceClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/MockServiceClassComposer.java @@ -30,6 +30,7 @@ import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; import com.google.api.generator.gapic.composer.store.TypeStore; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; diff --git a/src/main/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposer.java index ab7e03a52a..efdff56e6a 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposer.java @@ -38,6 +38,7 @@ import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; import com.google.api.generator.gapic.composer.store.TypeStore; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; diff --git a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java index 2270c2b3be..3c6e87d191 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java @@ -46,6 +46,7 @@ import com.google.api.generator.engine.ast.ValueExpr; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.comment.CommentComposer; import com.google.api.generator.gapic.composer.store.TypeStore; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.ResourceName; diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java index 042da51ac5..b18d9eb123 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java @@ -54,8 +54,10 @@ import com.google.api.generator.engine.ast.ValueExpr; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.comment.ServiceClientCommentComposer; import com.google.api.generator.gapic.composer.samplecode.ServiceClientSampleCodeComposer; import com.google.api.generator.gapic.composer.store.TypeStore; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.Field; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java index a1d6fa7912..7f5ae520f2 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java @@ -58,6 +58,7 @@ import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; import com.google.api.generator.gapic.composer.store.TypeStore; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.Field; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java index 861a1a2f73..8af3e88e38 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java @@ -50,8 +50,10 @@ import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.comment.SettingsCommentComposer; import com.google.api.generator.gapic.composer.samplecode.SettingsSampleCodeComposer; import com.google.api.generator.gapic.composer.store.TypeStore; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java index 9718f5a49e..17190aa4d6 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java @@ -29,7 +29,9 @@ import com.google.api.generator.engine.ast.Statement; import com.google.api.generator.engine.ast.ThrowExpr; import com.google.api.generator.engine.ast.TypeNode; +import com.google.api.generator.gapic.composer.comment.StubCommentComposer; import com.google.api.generator.gapic.composer.store.TypeStore; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.gapic.model.Message; diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java index 870ef7bf5f..e0352303d7 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java @@ -81,8 +81,10 @@ import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.engine.ast.Variable; import com.google.api.generator.engine.ast.VariableExpr; +import com.google.api.generator.gapic.composer.comment.SettingsCommentComposer; import com.google.api.generator.gapic.composer.samplecode.SettingsSampleCodeComposer; import com.google.api.generator.gapic.composer.store.TypeStore; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.Field; import com.google.api.generator.gapic.model.GapicBatchingSettings; import com.google.api.generator.gapic.model.GapicClass; diff --git a/src/main/java/com/google/api/generator/gapic/composer/comment/BUILD.bazel b/src/main/java/com/google/api/generator/gapic/composer/comment/BUILD.bazel new file mode 100644 index 0000000000..d7c61158f5 --- /dev/null +++ b/src/main/java/com/google/api/generator/gapic/composer/comment/BUILD.bazel @@ -0,0 +1,22 @@ +load("@rules_java//java:defs.bzl", "java_library") + +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "comment_files", + srcs = glob(["*.java"]), +) + +java_library( + name = "comment", + srcs = [ + ":comment_files", + ], + deps = [ + "//src/main/java/com/google/api/generator/engine/ast", + "//src/main/java/com/google/api/generator/gapic/composer/utils", + "//src/main/java/com/google/api/generator/gapic/model", + "//src/main/java/com/google/api/generator/gapic/utils", + "@com_google_guava_guava//jar", + ], +) diff --git a/src/main/java/com/google/api/generator/gapic/composer/CommentComposer.java b/src/main/java/com/google/api/generator/gapic/composer/comment/CommentComposer.java similarity index 97% rename from src/main/java/com/google/api/generator/gapic/composer/CommentComposer.java rename to src/main/java/com/google/api/generator/gapic/composer/comment/CommentComposer.java index 8457288b82..f779bae88e 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/CommentComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/comment/CommentComposer.java @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package com.google.api.generator.gapic.composer; +package com.google.api.generator.gapic.composer.comment; import com.google.api.generator.engine.ast.BlockComment; import com.google.api.generator.engine.ast.CommentStatement; diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java b/src/main/java/com/google/api/generator/gapic/composer/comment/ServiceClientCommentComposer.java similarity index 93% rename from src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java rename to src/main/java/com/google/api/generator/gapic/composer/comment/ServiceClientCommentComposer.java index 9f3cc83062..eb2d91f7d7 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/comment/ServiceClientCommentComposer.java @@ -12,11 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -package com.google.api.generator.gapic.composer; +package com.google.api.generator.gapic.composer.comment; import com.google.api.generator.engine.ast.CommentStatement; import com.google.api.generator.engine.ast.JavaDocComment; import com.google.api.generator.engine.ast.TypeNode; +import com.google.api.generator.gapic.composer.utils.ClassNames; import com.google.api.generator.gapic.model.Method; import com.google.api.generator.gapic.model.MethodArgument; import com.google.api.generator.gapic.model.Service; @@ -29,7 +30,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -class ServiceClientCommentComposer { +public class ServiceClientCommentComposer { // Tokens. private static final String COLON = ":"; private static final String EMPTY_STRING = ""; @@ -102,12 +103,12 @@ class ServiceClientCommentComposer { + " should be preferred."; // Comments. - static final CommentStatement GET_OPERATIONS_CLIENT_METHOD_COMMENT = + public static final CommentStatement GET_OPERATIONS_CLIENT_METHOD_COMMENT = toSimpleComment( "Returns the OperationsClient that can be used to query the status of a long-running" + " operation returned by another API method call."); - static List createClassHeaderComments( + public static List createClassHeaderComments( Service service, String credentialsSampleCode, String endpointSampleCode) { JavaDocComment.Builder classHeaderJavadocBuilder = JavaDocComment.builder(); if (service.hasDescription()) { @@ -150,14 +151,14 @@ static List createClassHeaderComments( CommentStatement.withComment(classHeaderJavadocBuilder.build())); } - static CommentStatement createCreateMethodStubArgComment( + public static CommentStatement createCreateMethodStubArgComment( String serviceName, TypeNode settingsType) { return toSimpleComment( String.format( CREATE_METHOD_STUB_ARG_PATTERN, serviceName, settingsType.reference().name())); } - static List createRpcMethodHeaderComment( + public static List createRpcMethodHeaderComment( Method method, List methodArguments) { JavaDocComment.Builder methodJavadocBuilder = JavaDocComment.builder(); @@ -191,23 +192,23 @@ static List createRpcMethodHeaderComment( return comments; } - static List createRpcMethodHeaderComment(Method method) { + public static List createRpcMethodHeaderComment(Method method) { return createRpcMethodHeaderComment(method, Collections.emptyList()); } - static CommentStatement createMethodNoArgComment(String serviceName) { + public static CommentStatement createMethodNoArgComment(String serviceName) { return toSimpleComment(String.format(CREATE_METHOD_NO_ARG_PATTERN, serviceName)); } - static CommentStatement createProtectedCtorSettingsArgComment(String serviceName) { + public static CommentStatement createProtectedCtorSettingsArgComment(String serviceName) { return toSimpleComment(String.format(PROTECTED_CONSTRUCTOR_SETTINGS_ARG_PATTERN, serviceName)); } - static CommentStatement createMethodSettingsArgComment(String serviceName) { + public static CommentStatement createMethodSettingsArgComment(String serviceName) { return toSimpleComment(String.format(CREATE_METHOD_SETTINGS_ARG_PATTERN, serviceName)); } - static List createRpcCallableMethodHeaderComment(Method method) { + public static List createRpcCallableMethodHeaderComment(Method method) { JavaDocComment.Builder methodJavadocBuilder = JavaDocComment.builder(); if (method.hasDescription()) { diff --git a/src/main/java/com/google/api/generator/gapic/composer/SettingsCommentComposer.java b/src/main/java/com/google/api/generator/gapic/composer/comment/SettingsCommentComposer.java similarity index 84% rename from src/main/java/com/google/api/generator/gapic/composer/SettingsCommentComposer.java rename to src/main/java/com/google/api/generator/gapic/composer/comment/SettingsCommentComposer.java index 6ded91f6fe..3c98fa0b79 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/SettingsCommentComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/comment/SettingsCommentComposer.java @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package com.google.api.generator.gapic.composer; +package com.google.api.generator.gapic.composer.comment; import com.google.api.generator.engine.ast.CommentStatement; import com.google.api.generator.engine.ast.JavaDocComment; @@ -25,7 +25,7 @@ import java.util.Optional; import java.util.stream.Collectors; -class SettingsCommentComposer { +public class SettingsCommentComposer { private static final String COLON = ":"; private static final String STUB_PATTERN = "%sStub"; @@ -54,29 +54,29 @@ class SettingsCommentComposer { private static final String CLASS_HEADER_DEFAULTS_RETRIES_DESCRIPTION = "Retries are configured for idempotent methods but not for non-idempotent methods."; - static final CommentStatement DEFAULT_SCOPES_COMMENT = + public static final CommentStatement DEFAULT_SCOPES_COMMENT = toSimpleComment("The default scopes of the service."); - static final CommentStatement DEFAULT_EXECUTOR_PROVIDER_BUILDER_METHOD_COMMENT = + public static final CommentStatement DEFAULT_EXECUTOR_PROVIDER_BUILDER_METHOD_COMMENT = toSimpleComment("Returns a builder for the default ExecutorProvider for this service."); - static final CommentStatement DEFAULT_SERVICE_ENDPOINT_METHOD_COMMENT = + public static final CommentStatement DEFAULT_SERVICE_ENDPOINT_METHOD_COMMENT = toSimpleComment("Returns the default service endpoint."); - static final CommentStatement DEFAULT_SERVICE_SCOPES_METHOD_COMMENT = + public static final CommentStatement DEFAULT_SERVICE_SCOPES_METHOD_COMMENT = toSimpleComment("Returns the default service scopes."); - static final CommentStatement DEFAULT_CREDENTIALS_PROVIDER_BUILDER_METHOD_COMMENT = + public static final CommentStatement DEFAULT_CREDENTIALS_PROVIDER_BUILDER_METHOD_COMMENT = toSimpleComment("Returns a builder for the default credentials for this service."); - static final CommentStatement DEFAULT_GRPC_TRANSPORT_PROVIDER_BUILDER_METHOD_COMMENT = + public static final CommentStatement DEFAULT_GRPC_TRANSPORT_PROVIDER_BUILDER_METHOD_COMMENT = toSimpleComment("Returns a builder for the default ChannelProvider for this service."); - static final CommentStatement NEW_BUILDER_METHOD_COMMENT = + public static final CommentStatement NEW_BUILDER_METHOD_COMMENT = toSimpleComment("Returns a new builder for this class."); - static final CommentStatement TO_BUILDER_METHOD_COMMENT = + public static final CommentStatement TO_BUILDER_METHOD_COMMENT = toSimpleComment("Returns a builder containing all the values of this settings class."); - static final List APPLY_TO_ALL_UNARY_METHODS_METHOD_COMMENTS = + public static final List APPLY_TO_ALL_UNARY_METHODS_METHOD_COMMENTS = Arrays.asList( LineComment.withComment("NEXT_MAJOR_VER: remove 'throws Exception'."), JavaDocComment.builder() @@ -90,19 +90,19 @@ class SettingsCommentComposer { .map(c -> CommentStatement.withComment(c)) .collect(Collectors.toList()); - static CommentStatement createCallSettingsGetterComment(String javaMethodName) { + public static CommentStatement createCallSettingsGetterComment(String javaMethodName) { return toSimpleComment(String.format(CALL_SETTINGS_METHOD_DOC_PATTERN, javaMethodName)); } - static CommentStatement createBuilderClassComment(String outerClassName) { + public static CommentStatement createBuilderClassComment(String outerClassName) { return toSimpleComment(String.format(BUILDER_CLASS_DOC_PATTERN, outerClassName)); } - static CommentStatement createCallSettingsBuilderGetterComment(String javaMethodName) { + public static CommentStatement createCallSettingsBuilderGetterComment(String javaMethodName) { return toSimpleComment(String.format(CALL_SETTINGS_BUILDER_METHOD_DOC_PATTERN, javaMethodName)); } - static List createClassHeaderComments( + public static List createClassHeaderComments( String configuredClassName, String defaultHost, Optional methodNameOpt, diff --git a/src/main/java/com/google/api/generator/gapic/composer/StubCommentComposer.java b/src/main/java/com/google/api/generator/gapic/composer/comment/StubCommentComposer.java similarity index 86% rename from src/main/java/com/google/api/generator/gapic/composer/StubCommentComposer.java rename to src/main/java/com/google/api/generator/gapic/composer/comment/StubCommentComposer.java index fb7731496d..2fb1a5c2a0 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/StubCommentComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/comment/StubCommentComposer.java @@ -12,14 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -package com.google.api.generator.gapic.composer; +package com.google.api.generator.gapic.composer.comment; import com.google.api.generator.engine.ast.CommentStatement; import com.google.api.generator.engine.ast.JavaDocComment; import java.util.Arrays; import java.util.List; -class StubCommentComposer { +public class StubCommentComposer { private static final String STUB_CLASS_HEADER_SUMMARY_PATTERN = "Base stub class for the %s service API."; private static final String GRPC_CALLABLE_FACTORY_CLASS_HEADER_SUMMARY_PATTERN = @@ -31,7 +31,8 @@ class StubCommentComposer { private static final String ADVANCED_USAGE_API_REFLECTION_DESCRIPTION = "This class is for advanced usage and reflects the underlying API directly."; - static List createGrpcServiceStubClassHeaderComments(String serviceName) { + public static List createGrpcServiceStubClassHeaderComments( + String serviceName) { return Arrays.asList( CommentComposer.AUTO_GENERATED_CLASS_COMMENT, CommentStatement.withComment( @@ -41,7 +42,7 @@ static List createGrpcServiceStubClassHeaderComments(String se .build())); } - static List createGrpcServiceCallableFactoryClassHeaderComments( + public static List createGrpcServiceCallableFactoryClassHeaderComments( String serviceName) { return Arrays.asList( CommentComposer.AUTO_GENERATED_CLASS_COMMENT, @@ -53,7 +54,7 @@ static List createGrpcServiceCallableFactoryClassHeaderComment .build())); } - static List createServiceStubClassHeaderComments(String serviceName) { + public static List createServiceStubClassHeaderComments(String serviceName) { return Arrays.asList( CommentComposer.AUTO_GENERATED_CLASS_COMMENT, CommentStatement.withComment( diff --git a/src/main/java/com/google/api/generator/gapic/composer/utils/BUILD.bazel b/src/main/java/com/google/api/generator/gapic/composer/utils/BUILD.bazel new file mode 100644 index 0000000000..dbcf57db8a --- /dev/null +++ b/src/main/java/com/google/api/generator/gapic/composer/utils/BUILD.bazel @@ -0,0 +1,18 @@ +load("@rules_java//java:defs.bzl", "java_library") + +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "utils_files", + srcs = glob(["*.java"]), +) + +java_library( + name = "utils", + srcs = [ + ":utils_files", + ], + deps = [ + "//src/main/java/com/google/api/generator/gapic/model", + ], +) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ClassNames.java b/src/main/java/com/google/api/generator/gapic/composer/utils/ClassNames.java similarity index 79% rename from src/main/java/com/google/api/generator/gapic/composer/ClassNames.java rename to src/main/java/com/google/api/generator/gapic/composer/utils/ClassNames.java index 9135d88b5b..fb54e3f4d4 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ClassNames.java +++ b/src/main/java/com/google/api/generator/gapic/composer/utils/ClassNames.java @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package com.google.api.generator.gapic.composer; +package com.google.api.generator.gapic.composer.utils; import com.google.api.generator.gapic.model.Service; @@ -30,48 +30,48 @@ public class ClassNames { private static final String GRPC_SERVICE_CALLABLE_FACTORY_CLASS_NAME_PATTERN = "Grpc%sCallableFactory"; - protected static String getServiceClientClassName(Service service) { + public static String getServiceClientClassName(Service service) { return String.format( SERVICE_CLIENT_CLASS_NAME_PATTERN, monolithBackwardsCompatibleName(service.overriddenName())); } - protected static String getServiceSettingsClassName(Service service) { + public static String getServiceSettingsClassName(Service service) { return String.format( SERVICE_SETTINGS_CLASS_NAME_PATTERN, monolithBackwardsCompatibleName(service.overriddenName())); } - protected static String getServiceStubSettingsClassName(Service service) { + public static String getServiceStubSettingsClassName(Service service) { return String.format( SERVICE_STUB_SETTINGS_CLASS_NAME_PATTERN, monolithBackwardsCompatibleName(service.name())); } - protected static String getServiceStubClassName(Service service) { + public static String getServiceStubClassName(Service service) { return String.format( SERVICE_STUB_CLASS_NAME_PATTERN, monolithBackwardsCompatibleName(service.name())); } - protected static String getGrpcServiceCallableFactoryClassName(Service service) { + public static String getGrpcServiceCallableFactoryClassName(Service service) { return String.format( GRPC_SERVICE_CALLABLE_FACTORY_CLASS_NAME_PATTERN, monolithBackwardsCompatibleName(service.name())); } - protected static String getGrpcServiceStubClassName(Service service) { + public static String getGrpcServiceStubClassName(Service service) { return String.format( GRPC_SERVICE_STUB_CLASS_NAME_PATTERN, monolithBackwardsCompatibleName(service.name())); } - protected static String getServiceClientTestClassName(Service service) { + public static String getServiceClientTestClassName(Service service) { return String.format(SERVICE_CLIENT_TEST_CLASS_NAME_PATTERN, service.overriddenName()); } - protected static String getMockServiceClassName(Service service) { + public static String getMockServiceClassName(Service service) { return String.format(MOCK_SERVICE_CLASS_NAME_PATTERN, service.name()); } - protected static String getMockServiceImplClassName(Service service) { + public static String getMockServiceImplClassName(Service service) { return String.format(MOCK_SERVICE_IMPL_CLASS_NAME_PATTERN, service.name()); } From 5e8a564eff8ec7b25ffcb9c5119b692a9ce0edb5 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Tue, 22 Dec 2020 11:38:39 -0800 Subject: [PATCH 10/11] fix: remove BiFunction --- .../ServiceClientSampleCodeComposer.java | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java index 14a2885d43..cfdfd913c1 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientSampleCodeComposer.java @@ -27,17 +27,12 @@ import com.google.api.generator.gapic.composer.samplecode.SampleCodeWriter; import com.google.api.generator.gapic.utils.JavaStyle; import java.util.Arrays; -import java.util.function.BiFunction; public class ServiceClientSampleCodeComposer { // TODO(summerji): Add unit tests for ServiceClientSampleCodeComposer. public static String composeClassHeaderCredentialsSampleCode( TypeNode clientType, TypeNode settingsType) { - // Funcdtion instead of a helper for better config / locality reference. - BiFunction createVarExprFn = - (s, t) -> VariableExpr.withVariable(Variable.builder().setName(s).setType(t).build()); - // Initialize clientSettings with builder() method. // e.g. EchoSettings echoSettings = // EchoSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create("myCredentials")).build(); @@ -49,7 +44,9 @@ public static String composeClassHeaderCredentialsSampleCode( .setName("myCredentials") .setPakkage(clientType.reference().pakkage()) .build()); - VariableExpr settingsVarExpr = createVarExprFn.apply(settingsName, settingsType); + VariableExpr settingsVarExpr = + VariableExpr.withVariable( + Variable.builder().setName(settingsName).setType(settingsType).build()); MethodInvocationExpr newBuilderMethodExpr = MethodInvocationExpr.builder() .setStaticReferenceType(settingsType) @@ -60,7 +57,9 @@ public static String composeClassHeaderCredentialsSampleCode( MethodInvocationExpr credentialArgExpr = MethodInvocationExpr.builder() .setStaticReferenceType(fixedCredentialProvideType) - .setArguments(createVarExprFn.apply("myCredentials", myCredentialsType)) + .setArguments( + VariableExpr.withVariable( + Variable.builder().setName("myCredentials").setType(myCredentialsType).build())) .setMethodName("create") .build(); MethodInvocationExpr credentialsMethodExpr = @@ -83,7 +82,9 @@ public static String composeClassHeaderCredentialsSampleCode( // Initialized client with create() method. // e.g. EchoClient echoClient = EchoClient.create(echoSettings); - VariableExpr clientVarExpr = createVarExprFn.apply(clientName, clientType); + VariableExpr clientVarExpr = + VariableExpr.withVariable( + Variable.builder().setName(clientName).setType(clientType).build()); MethodInvocationExpr createMethodExpr = MethodInvocationExpr.builder() .setStaticReferenceType(clientType) @@ -104,10 +105,6 @@ public static String composeClassHeaderCredentialsSampleCode( public static String composeClassHeaderEndpointSampleCode( TypeNode clientType, TypeNode settingsType) { - // Funcdtion instead of a helper for better config / locality reference. - BiFunction createVarExprFn = - (s, t) -> VariableExpr.withVariable(Variable.builder().setName(s).setType(t).build()); - // Initialize client settings with builder() method. // e.g. EchoSettings echoSettings = EchoSettings.newBuilder().setEndpoint("myEndpoint").build(); String settingsName = JavaStyle.toLowerCamelCase(settingsType.reference().name()); @@ -118,7 +115,9 @@ public static String composeClassHeaderEndpointSampleCode( .setName("myEndpoint") .setPakkage(clientType.reference().pakkage()) .build()); - VariableExpr settingsVarExpr = createVarExprFn.apply(settingsName, settingsType); + VariableExpr settingsVarExpr = + VariableExpr.withVariable( + Variable.builder().setName(settingsName).setType(settingsType).build()); MethodInvocationExpr newBuilderMethodExpr = MethodInvocationExpr.builder() .setStaticReferenceType(settingsType) @@ -127,7 +126,9 @@ public static String composeClassHeaderEndpointSampleCode( MethodInvocationExpr credentialsMethodExpr = MethodInvocationExpr.builder() .setExprReferenceExpr(newBuilderMethodExpr) - .setArguments(createVarExprFn.apply("myEndpoint", myEndpointType)) + .setArguments( + VariableExpr.withVariable( + Variable.builder().setName("myEndpoint").setType(myEndpointType).build())) .setMethodName("setEndpoint") .build(); MethodInvocationExpr buildMethodExpr = @@ -145,7 +146,9 @@ public static String composeClassHeaderEndpointSampleCode( // Initialize client with create() method. // e.g. EchoClient echoClient = EchoClient.create(echoSettings); - VariableExpr clientVarExpr = createVarExprFn.apply(clientName, clientType); + VariableExpr clientVarExpr = + VariableExpr.withVariable( + Variable.builder().setName(clientName).setType(clientType).build()); MethodInvocationExpr createMethodExpr = MethodInvocationExpr.builder() .setStaticReferenceType(clientType) From aa245c880bc6735fd2c08f94e01418fb56a4f14d Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Tue, 22 Dec 2020 13:51:39 -0800 Subject: [PATCH 11/11] fix: merge master --- .../generator/gapic/composer/ServiceClientCommentComposer.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java index db62d4b4e5..9f3cc83062 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java @@ -17,7 +17,6 @@ import com.google.api.generator.engine.ast.CommentStatement; import com.google.api.generator.engine.ast.JavaDocComment; import com.google.api.generator.engine.ast.TypeNode; -import com.google.api.generator.gapic.composer.samplecode.ServiceClientSampleCodeComposer; import com.google.api.generator.gapic.model.Method; import com.google.api.generator.gapic.model.MethodArgument; import com.google.api.generator.gapic.model.Service;