From 18495c73ca83fcc8c29ebac1aaf637c4131e1196 Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Tue, 8 Sep 2020 11:26:46 -0700 Subject: [PATCH 01/16] add golden folder --- .../api/generator/engine/goldens/BUILD.bazel | 6 + .../goldens/JavaCodeGeneratorTest.golden | 149 ++++++++++++++++++ .../gapic/composer/goldens/BUILD.bazel | 6 + 3 files changed, 161 insertions(+) create mode 100644 src/test/java/com/google/api/generator/engine/goldens/BUILD.bazel create mode 100644 src/test/java/com/google/api/generator/engine/goldens/JavaCodeGeneratorTest.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/BUILD.bazel diff --git a/src/test/java/com/google/api/generator/engine/goldens/BUILD.bazel b/src/test/java/com/google/api/generator/engine/goldens/BUILD.bazel new file mode 100644 index 0000000000..cf5efe56d1 --- /dev/null +++ b/src/test/java/com/google/api/generator/engine/goldens/BUILD.bazel @@ -0,0 +1,6 @@ +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "goldens_files", + srcs = glob(["*.golden"]), +) \ No newline at end of file diff --git a/src/test/java/com/google/api/generator/engine/goldens/JavaCodeGeneratorTest.golden b/src/test/java/com/google/api/generator/engine/goldens/JavaCodeGeneratorTest.golden new file mode 100644 index 0000000000..c6fb279b8f --- /dev/null +++ b/src/test/java/com/google/api/generator/engine/goldens/JavaCodeGeneratorTest.golden @@ -0,0 +1,149 @@ +/* + * Copyright 2020 Gagpic-generator-java + * + * Licensed description and license version 2.0 (the "License"); + * + * https://www.foo.bar/licenses/LICENSE-2.0 + * + * Software distributed under the License is distributed on an "AS IS" BASIS. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.example.library.core; + +import com.google.exmaple.library.LibraryService; +import com.google.exmaple.library.core.LibraryServiceStub; +import com.google.exmaple.library.v1.BookKind; +import com.google.gax.grpc.Stub; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Stack; + +/** + * Service Description: This is a test comment. + * + *

+ * LibraryServiceStub libServiceStub = new LibraryServiceStub()
+ * 
+ * + *
    + *
  1. A "flattened" method. + *
  2. A "request object" method. + *
  3. A "callable" method. + *
+ * + * @deprecated This is a deprecated message. + */ +@SuppressWarnings("all") +@Deprecated +@Override +public class LibraryServiceStub extends Stub implements LibraryService { + private static final String serviceName = "LibraryServiceStub"; + protected List shelfList; + public static HashMap shelfMap; + + public LibraryServiceStub() { + super(); + this.shelfList = new ArrayList<>(); + shelfMap = new HashMap<>(); + } + + @Override + public String addShelf(String name, double seriesDoubleNum) { + int seriesNum = ((int) seriesDoubleNum); + if (condition) { + return "Series number equals to max int value."; + } + shelfList.add(new Shelf(name, seriesNum)); + if (shelfMap.containsKey(name)) { + return "Shelf is already existing in the map."; + } + shelfMap.put(name, new Shelf(name, seriesNum)); + return "Shelf added."; + } + + public void updateShelfMap(Shelf newShelf) throws Exception { + if (shelfMap.containsKey(newShelf.shelfName)) { + shelfMap.put(newShelf.shelfName, newShelf); + } else { + throw new Exception("Updating shelf is not existing in the map"); + } + } + + public void printShelfListToFile(String fileName) { + StringBuilder sb = new StringBuilder(); + try { + FileWriter fileWriter = new FileWriter(fileName); + for (Shelf s : shelfList) { + sb.append(s.shelfName).append(s.seriesNum); + } + fileName.write(sb.toString()); + fileName.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Add books to Shelf and check if there is a novel, return string message as whether novel books + * are added to the shelf. + * + * @param shelf The Shelf object to which books will put. + * @param stack The Stack of the BookKinds. + */ + public String addBooksContainsNovel(Shelf shelf, Stack stack) { + boolean containsNovel = false; + while (stack.isEmpty()) { + Book addedBook = addBookToShelf(stack.pop(), shelf); + if (addedBook instanceof Novel) { + containsNovel = true; + } + } + return containsNovel ? "Added novels" : "No novels added"; + } + + // Private helper. + private Book addBookToShelf(BookKind bookKind, Shelf shelf) { + Book book = + new Book() { + @Override + public void createBook(int seriesNum, BookKind bookKind) { + this.seriesNum = seriesNum; + this.bookKind = bookKind; + } + }; + return book; + } + + public class Shelf { + public String shelfName; + public int seriesNum; + public String shelfServiceName = serviceName; + + public Shelf(String shelfName, int seriesNum) { + this.shelfName = shelfName; + this.seriesNum = seriesNum; + } + } + + // Test nested abstract class and abstract method. + public abstract class Book { + public BookKind bookKind; + public int seriesNum; + + public abstract void createBook(int seriesNum, BookKind bookKind); + } + + public class Novel extends Book { + + @Override + public void createBook(int seriesNum, BookKind bookKind) { + this.seriesNum = seriesNum; + this.bookKind = BookKind.NOVEL; + } + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/goldens/BUILD.bazel new file mode 100644 index 0000000000..cf5efe56d1 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/BUILD.bazel @@ -0,0 +1,6 @@ +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "goldens_files", + srcs = glob(["*.golden"]), +) \ No newline at end of file From e1360b54cd7ca5d613250b970d8e2a52d8657f2c Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Tue, 8 Sep 2020 11:29:44 -0700 Subject: [PATCH 02/16] format --- .../java/com/google/api/generator/engine/goldens/BUILD.bazel | 2 +- .../com/google/api/generator/gapic/composer/goldens/BUILD.bazel | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/google/api/generator/engine/goldens/BUILD.bazel b/src/test/java/com/google/api/generator/engine/goldens/BUILD.bazel index cf5efe56d1..85ac1a519e 100644 --- a/src/test/java/com/google/api/generator/engine/goldens/BUILD.bazel +++ b/src/test/java/com/google/api/generator/engine/goldens/BUILD.bazel @@ -3,4 +3,4 @@ package(default_visibility = ["//visibility:public"]) filegroup( name = "goldens_files", srcs = glob(["*.golden"]), -) \ No newline at end of file +) diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/goldens/BUILD.bazel index cf5efe56d1..85ac1a519e 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/BUILD.bazel @@ -3,4 +3,4 @@ package(default_visibility = ["//visibility:public"]) filegroup( name = "goldens_files", srcs = glob(["*.golden"]), -) \ No newline at end of file +) From 810e536a6782ff1f3dfe3b5a6d9a658824bfa1f3 Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Tue, 8 Sep 2020 14:07:06 -0700 Subject: [PATCH 03/16] move all expected strings to golden files --- .../google/api/generator/engine/BUILD.bazel | 1 + .../engine/JavaCodeGeneratorTest.java | 163 +- .../api/generator/gapic/composer/BUILD.bazel | 1 + .../gapic/composer/ComposerTest.java | 32 +- ...rviceCallableFactoryClassComposerTest.java | 117 +- .../GrpcServiceStubClassComposerTest.java | 333 +-- .../MockServiceClassComposerTest.java | 58 +- .../MockServiceImplClassComposerTest.java | 244 +- .../ResourceNameHelperClassComposerTest.java | 486 +--- .../ServiceClientClassComposerTest.java | 216 +- .../ServiceClientTestClassComposerTest.java | 69 +- .../ServiceSettingsClassComposerTest.java | 279 +-- .../ServiceStubClassComposerTest.java | 95 +- .../ServiceStubSettingsClassComposerTest.java | 2179 +---------------- .../composer/goldens/ComposerTest.golden | 19 + ...iceCallableFactoryClassComposerTest.golden | 97 + .../GrpcServiceStubClassComposerTest.golden | 278 +++ .../MockServiceClassComposerTest.golden | 43 + .../MockServiceImplClassComposerTest.golden | 212 ++ ...HelperClassComposerTestMultiPattern.golden | 314 +++ ...meHelperClassComposerTestOnePattern.golden | 127 + .../ServiceClientClassComposerTest.golden | 191 ++ .../ServiceClientTestClassComposerTest.golden | 53 + .../ServiceSettingsClassComposerTest.golden | 242 ++ .../ServiceStubClassComposerTest.golden | 73 + ...ceStubSettingsClassComposerTestEcho.golden | 486 ++++ ...tubSettingsClassComposerTestLogging.golden | 649 +++++ ...bSettingsClassComposerTestPublisher.golden | 758 ++++++ 28 files changed, 3686 insertions(+), 4129 deletions(-) create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ComposerTest.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceCallableFactoryClassComposerTest.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceStubClassComposerTest.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceClassComposerTest.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceImplClassComposerTest.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestMultiPattern.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestOnePattern.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceSettingsClassComposerTest.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubClassComposerTest.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestEcho.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestLogging.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestPublisher.golden diff --git a/src/test/java/com/google/api/generator/engine/BUILD.bazel b/src/test/java/com/google/api/generator/engine/BUILD.bazel index e4cead379e..76d309f069 100644 --- a/src/test/java/com/google/api/generator/engine/BUILD.bazel +++ b/src/test/java/com/google/api/generator/engine/BUILD.bazel @@ -16,6 +16,7 @@ TESTS = [ [java_test( name = test_name, srcs = ["{0}.java".format(test_name)], + data = ["//src/test/java/com/google/api/generator/engine/goldens:goldens_files"], test_class = "com.google.api.generator.engine.{0}".format(test_name), deps = [ "//src/main/java/com/google/api/generator/engine/ast", diff --git a/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java b/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java index d9aa8fb0f2..4887d677c6 100644 --- a/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java +++ b/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java @@ -53,6 +53,9 @@ import com.google.api.generator.engine.writer.JavaWriterVisitor; import java.io.FileWriter; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -61,6 +64,8 @@ import org.junit.Test; public class JavaCodeGeneratorTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/engine/goldens/"; // Create shared VaporReferences. private static final VaporReference stubRef = createVaporReference("com.google.gax.grpc", "Stub"); private static final VaporReference bookKindRef = @@ -96,7 +101,7 @@ public class JavaCodeGeneratorTest { private static final Variable bookKindVar = createVarFromVaporRef(bookKindRef, "bookKind"); @Test - public void validJavaClass() { + public void validJavaClass() throws IOException { // Create outer class variableDecls. // [code] private static final String serviceName = "LibraryServiceStub"; VariableExpr serviceName = createServiceNameVarExpr(); @@ -169,7 +174,9 @@ public void validJavaClass() { .build(); JavaWriterVisitor javaWriterVisitor = new JavaWriterVisitor(); libraryServiceStubClass.accept(javaWriterVisitor); - assertEquals(javaWriterVisitor.write(), EXPECTED_CLASS_STRING); + Path goldeFilePath = Paths.get(GOLDENFILES_DIRECTORY, "JavaCodeGeneratorTest.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(javaWriterVisitor.write(), expectedClassString); } // Private helpers. @@ -744,156 +751,4 @@ private ClassDefinition createNestedClassNovel() { Arrays.asList(createOverrideCreateBookMethod(novelClassRef, bookKindNovelEnumExpr))) .build(); } - - private static final String EXPECTED_CLASS_STRING = - "/*\n" - + " * Copyright 2020 Gagpic-generator-java\n" - + " *\n" - + " * Licensed description and license version 2.0 (the \"License\");\n" - + " *\n" - + " * https://www.foo.bar/licenses/LICENSE-2.0\n" - + " *\n" - + " * Software distributed under the License is distributed on an \"AS IS\" BASIS.\n" - + " * See the License for the specific language governing permissions and\n" - + " * limitations under the License.\n" - + " */\n" - + "\n" - + "package com.google.example.library.core;\n" - + "\n" - + "import com.google.exmaple.library.LibraryService;\n" - + "import com.google.exmaple.library.core.LibraryServiceStub;\n" - + "import com.google.exmaple.library.v1.BookKind;\n" - + "import com.google.gax.grpc.Stub;\n" - + "import java.io.FileWriter;\n" - + "import java.io.IOException;\n" - + "import java.util.ArrayList;\n" - + "import java.util.HashMap;\n" - + "import java.util.List;\n" - + "import java.util.Stack;\n" - + "\n" - + "/**\n" - + " * Service Description: This is a test comment.\n" - + " *\n" - + " *
\n"
-          + " * LibraryServiceStub libServiceStub = new LibraryServiceStub()\n"
-          + " * 
\n" - + " *\n" - + " *
    \n" - + " *
  1. A \"flattened\" method.\n" - + " *
  2. A \"request object\" method.\n" - + " *
  3. A \"callable\" method.\n" - + " *
\n" - + " *\n" - + " * @deprecated This is a deprecated message.\n" - + " */\n" - + "@SuppressWarnings(\"all\")\n" - + "@Deprecated\n" - + "@Override\n" - + "public class LibraryServiceStub extends Stub implements LibraryService {\n" - + " private static final String serviceName = \"LibraryServiceStub\";\n" - + " protected List shelfList;\n" - + " public static HashMap shelfMap;\n" - + "\n" - + " public LibraryServiceStub() {\n" - + " super();\n" - + " this.shelfList = new ArrayList<>();\n" - + " shelfMap = new HashMap<>();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String addShelf(String name, double seriesDoubleNum) {\n" - + " int seriesNum = ((int) seriesDoubleNum);\n" - + " if (condition) {\n" - + " return \"Series number equals to max int value.\";\n" - + " }\n" - + " shelfList.add(new Shelf(name, seriesNum));\n" - + " if (shelfMap.containsKey(name)) {\n" - + " return \"Shelf is already existing in the map.\";\n" - + " }\n" - + " shelfMap.put(name, new Shelf(name, seriesNum));\n" - + " return \"Shelf added.\";\n" - + " }\n" - + "\n" - + " public void updateShelfMap(Shelf newShelf) throws Exception {\n" - + " if (shelfMap.containsKey(newShelf.shelfName)) {\n" - + " shelfMap.put(newShelf.shelfName, newShelf);\n" - + " } else {\n" - + " throw new Exception(\"Updating shelf is not existing in the map\");\n" - + " }\n" - + " }\n" - + "\n" - + " public void printShelfListToFile(String fileName) {\n" - + " StringBuilder sb = new StringBuilder();\n" - + " try {\n" - + " FileWriter fileWriter = new FileWriter(fileName);\n" - + " for (Shelf s : shelfList) {\n" - + " sb.append(s.shelfName).append(s.seriesNum);\n" - + " }\n" - + " fileName.write(sb.toString());\n" - + " fileName.close();\n" - + " } catch (IOException e) {\n" - + " e.printStackTrace();\n" - + " }\n" - + " }\n" - + "\n" - + " /**\n" - + " * Add books to Shelf and check if there is a novel, return string message as" - + " whether novel books\n" - + " * are added to the shelf.\n" - + " *\n" - + " * @param shelf The Shelf object to which books will put.\n" - + " * @param stack The Stack of the BookKinds.\n" - + " */\n" - + " public String addBooksContainsNovel(Shelf shelf, Stack stack) {\n" - + " boolean containsNovel = false;\n" - + " while (stack.isEmpty()) {\n" - + " Book addedBook = addBookToShelf(stack.pop(), shelf);\n" - + " if (addedBook instanceof Novel) {\n" - + " containsNovel = true;\n" - + " }\n" - + " }\n" - + " return containsNovel ? \"Added novels\" : \"No novels added\";\n" - + " }\n" - + "\n" - + " // Private helper.\n" - + " private Book addBookToShelf(BookKind bookKind, Shelf shelf) {\n" - + " Book book =\n" - + " new Book() {\n" - + " @Override\n" - + " public void createBook(int seriesNum, BookKind bookKind) {\n" - + " this.seriesNum = seriesNum;\n" - + " this.bookKind = bookKind;\n" - + " }\n" - + " };\n" - + " return book;\n" - + " }\n" - + "\n" - + " public class Shelf {\n" - + " public String shelfName;\n" - + " public int seriesNum;\n" - + " public String shelfServiceName = serviceName;\n" - + "\n" - + " public Shelf(String shelfName, int seriesNum) {\n" - + " this.shelfName = shelfName;\n" - + " this.seriesNum = seriesNum;\n" - + " }\n" - + " }\n" - + "\n" - + " // Test nested abstract class and abstract method.\n" - + " public abstract class Book {\n" - + " public BookKind bookKind;\n" - + " public int seriesNum;\n" - + "\n" - + " public abstract void createBook(int seriesNum, BookKind bookKind);\n" - + " }\n" - + "\n" - + " public class Novel extends Book {\n" - + "\n" - + " @Override\n" - + " public void createBook(int seriesNum, BookKind bookKind) {\n" - + " this.seriesNum = seriesNum;\n" - + " this.bookKind = BookKind.NOVEL;\n" - + " }\n" - + " }\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel index 740ba1b5f2..943026628e 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel @@ -48,6 +48,7 @@ java_proto_library( data = [ "//src/test/java/com/google/api/generator/gapic/testdata:gapic_config_files", "//src/test/java/com/google/api/generator/gapic/testdata:service_config_files", + "//src/test/java/com/google/api/generator/gapic/composer/goldens:goldens_files", ], test_class = "com.google.api.generator.gapic.composer.{0}".format(test_name), deps = [ diff --git a/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java index e5102b3211..59f46da982 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java @@ -21,13 +21,20 @@ import com.google.api.generator.engine.writer.JavaWriterVisitor; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import org.junit.Test; public class ComposerTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + @Test - public void gapicClass_addApacheLicense() { + public void gapicClass_addApacheLicense() throws IOException { ClassDefinition classDef = ClassDefinition.builder() .setPackageString("com.google.showcase.v1beta1.stub") @@ -38,25 +45,8 @@ public void gapicClass_addApacheLicense() { Composer.addApacheLicense(Arrays.asList(GapicClass.create(Kind.TEST, classDef))); JavaWriterVisitor visitor = new JavaWriterVisitor(); gapicClassWithHeaderList.get(0).classDefinition().accept(visitor); - assertEquals(visitor.write(), EXPECTED_CLASS_STRING); + Path goldeFilePath = Paths.get(GOLDENFILES_DIRECTORY, "ComposerTest.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(visitor.write(), expectedClassString); } - - private static final String EXPECTED_CLASS_STRING = - "/*\n" - + " * Copyright 2020 Google LLC\n" - + " *\n" - + " * Licensed under the Apache License, Version 2.0 (the \"License\");\n" - + " * you may not use this file except in compliance with the License.\n" - + " * You may obtain a copy of the License at\n" - + " *\n" - + " * https://www.apache.org/licenses/LICENSE-2.0\n" - + " *\n" - + " * Unless required by applicable law or agreed to in writing, software\n" - + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" - + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" - + " * See the License for the specific language governing permissions and\n" - + " * limitations under the License.\n" - + " */\n\n" - + "package com.google.showcase.v1beta1.stub;\n\n" - + "public class EchoStubSettings {}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java index 33bb12caad..fd6ee29780 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java @@ -25,6 +25,10 @@ import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -35,6 +39,8 @@ public class GrpcServiceCallableFactoryClassComposerTest { private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; @Before public void setUp() { @@ -44,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() { + public void generateServiceClasses() throws IOException { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -57,110 +63,9 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_CLASS_STRING, visitor.write()); + Path goldeFilePath = + Paths.get(GOLDENFILES_DIRECTORY, "GrpcServiceCallableFactoryClassComposerTest.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } - - // TODO(miraleung): Update this when a file-diffing test mechanism is in place. - private static final String EXPECTED_CLASS_STRING = - "package com.google.showcase.v1beta1.stub;\n" - + "\n" - + "import com.google.api.gax.grpc.GrpcCallSettings;\n" - + "import com.google.api.gax.grpc.GrpcCallableFactory;\n" - + "import com.google.api.gax.grpc.GrpcStubCallableFactory;\n" - + "import com.google.api.gax.rpc.BatchingCallSettings;\n" - + "import com.google.api.gax.rpc.BidiStreamingCallable;\n" - + "import com.google.api.gax.rpc.ClientContext;\n" - + "import com.google.api.gax.rpc.ClientStreamingCallable;\n" - + "import com.google.api.gax.rpc.OperationCallSettings;\n" - + "import com.google.api.gax.rpc.OperationCallable;\n" - + "import com.google.api.gax.rpc.PagedCallSettings;\n" - + "import com.google.api.gax.rpc.ServerStreamingCallSettings;\n" - + "import com.google.api.gax.rpc.ServerStreamingCallable;\n" - + "import com.google.api.gax.rpc.StreamingCallSettings;\n" - + "import com.google.api.gax.rpc.UnaryCallSettings;\n" - + "import com.google.api.gax.rpc.UnaryCallable;\n" - + "import com.google.longrunning.Operation;\n" - + "import com.google.longrunning.stub.OperationsStub;\n" - + "import javax.annotation.Generated;\n" - + "\n" - + "// AUTO-GENERATED DOCUMENTATION AND CLASS.\n" - + "/**\n" - + " * gRPC callable factory implementation for the Echo service API.\n" - + " *\n" - + " *

This class is for advanced usage.\n" - + " */\n" - + "@Generated(\"by gapic-generator\")\n" - + "public class GrpcEchoCallableFactory implements GrpcStubCallableFactory {\n" - + "\n" - + " @Override\n" - + " public UnaryCallable" - + " createUnaryCallable(\n" - + " GrpcCallSettings grpcCallSettings,\n" - + " UnaryCallSettings callSettings,\n" - + " ClientContext clientContext) {\n" - + " return GrpcCallableFactory.createUnaryCallable(grpcCallSettings, callSettings," - + " clientContext);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public \n" - + " UnaryCallable createPagedCallable(\n" - + " GrpcCallSettings grpcCallSettings,\n" - + " PagedCallSettings callSettings,\n" - + " ClientContext clientContext) {\n" - + " return GrpcCallableFactory.createPagedCallable(grpcCallSettings, callSettings," - + " clientContext);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public UnaryCallable" - + " createBatchingCallable(\n" - + " GrpcCallSettings grpcCallSettings,\n" - + " BatchingCallSettings callSettings,\n" - + " ClientContext clientContext) {\n" - + " return GrpcCallableFactory.createBatchingCallable(\n" - + " grpcCallSettings, callSettings, clientContext);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public \n" - + " OperationCallable createOperationCallable(\n" - + " GrpcCallSettings grpcCallSettings,\n" - + " OperationCallSettings callSettings,\n" - + " ClientContext clientContext,\n" - + " OperationsStub operationsStub) {\n" - + " return GrpcCallableFactory.createOperationCallable(\n" - + " grpcCallSettings, callSettings, clientContext, operationsStub);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public \n" - + " BidiStreamingCallable createBidiStreamingCallable(\n" - + " GrpcCallSettings grpcCallSettings,\n" - + " StreamingCallSettings callSettings,\n" - + " ClientContext clientContext) {\n" - + " return GrpcCallableFactory.createBidiStreamingCallable(\n" - + " grpcCallSettings, callSettings, clientContext);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public \n" - + " ServerStreamingCallable createServerStreamingCallable(\n" - + " GrpcCallSettings grpcCallSettings,\n" - + " ServerStreamingCallSettings callSettings,\n" - + " ClientContext clientContext) {\n" - + " return GrpcCallableFactory.createServerStreamingCallable(\n" - + " grpcCallSettings, callSettings, clientContext);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public \n" - + " ClientStreamingCallable createClientStreamingCallable(\n" - + " GrpcCallSettings grpcCallSettings,\n" - + " StreamingCallSettings callSettings,\n" - + " ClientContext clientContext) {\n" - + " return GrpcCallableFactory.createClientStreamingCallable(\n" - + " grpcCallSettings, callSettings, clientContext);\n" - + " }\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java index 9bd357bc15..26e5515864 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java @@ -25,6 +25,10 @@ import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -33,6 +37,8 @@ import org.junit.Test; public class GrpcServiceStubClassComposerTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -44,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() { + public void generateServiceClasses() throws IOException { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -56,326 +62,9 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_CLASS_STRING, visitor.write()); + Path goldeFilePath = + Paths.get(GOLDENFILES_DIRECTORY, "GrpcServiceStubClassComposerTest.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } - - // TODO(miraleung): Update this when a file-diffing test mechanism is in place. - private static final String EXPECTED_CLASS_STRING = - "package com.google.showcase.v1beta1.stub;\n" - + "\n" - + "import static com.google.showcase.v1beta1.EchoClient.PagedExpandPagedResponse;\n" - + "\n" - + "import com.google.api.gax.core.BackgroundResource;\n" - + "import com.google.api.gax.core.BackgroundResourceAggregation;\n" - + "import com.google.api.gax.grpc.GrpcCallSettings;\n" - + "import com.google.api.gax.grpc.GrpcStubCallableFactory;\n" - + "import com.google.api.gax.rpc.BidiStreamingCallable;\n" - + "import com.google.api.gax.rpc.ClientContext;\n" - + "import com.google.api.gax.rpc.ClientStreamingCallable;\n" - + "import com.google.api.gax.rpc.OperationCallable;\n" - + "import com.google.api.gax.rpc.ServerStreamingCallable;\n" - + "import com.google.api.gax.rpc.UnaryCallable;\n" - + "import com.google.longrunning.Operation;\n" - + "import com.google.longrunning.stub.GrpcOperationsStub;\n" - + "import com.google.showcase.v1beta1.BlockRequest;\n" - + "import com.google.showcase.v1beta1.BlockResponse;\n" - + "import com.google.showcase.v1beta1.EchoRequest;\n" - + "import com.google.showcase.v1beta1.EchoResponse;\n" - + "import com.google.showcase.v1beta1.ExpandRequest;\n" - + "import com.google.showcase.v1beta1.PagedExpandRequest;\n" - + "import com.google.showcase.v1beta1.PagedExpandResponse;\n" - + "import com.google.showcase.v1beta1.WaitMetadata;\n" - + "import com.google.showcase.v1beta1.WaitRequest;\n" - + "import com.google.showcase.v1beta1.WaitResponse;\n" - + "import io.grpc.MethodDescriptor;\n" - + "import io.grpc.protobuf.ProtoUtils;\n" - + "import java.io.IOException;\n" - + "import java.util.concurrent.TimeUnit;\n" - + "import javax.annotation.Generated;\n" - + "\n" - + "// AUTO-GENERATED DOCUMENTATION AND CLASS.\n" - + "/**\n" - + " * gRPC stub implementation for the Echo service API.\n" - + " *\n" - + " *

This class is for advanced usage and reflects the underlying API directly.\n" - + " */\n" - + "@Generated(\"by gapic-generator-java\")\n" - + "public class GrpcEchoStub extends EchoStub {\n" - + " private static final MethodDescriptor" - + " echoMethodDescriptor =\n" - + " MethodDescriptor.newBuilder()\n" - + " .setType(MethodDescriptor.MethodType.UNARY)\n" - + " .setFullMethodName(\"google.showcase.v1beta1.Echo/Echo\")\n" - + " " - + " .setRequestMarshaller(ProtoUtils.marshaller(EchoRequest.getDefaultInstance()))\n" - + " " - + " .setResponseMarshaller(ProtoUtils.marshaller(EchoResponse.getDefaultInstance()))\n" - + " .build();\n" - + " private static final MethodDescriptor" - + " expandMethodDescriptor =\n" - + " MethodDescriptor.newBuilder()\n" - + " .setType(MethodDescriptor.MethodType.SERVER_STREAMING)\n" - + " .setFullMethodName(\"google.showcase.v1beta1.Echo/Expand\")\n" - + " " - + " .setRequestMarshaller(ProtoUtils.marshaller(ExpandRequest.getDefaultInstance()))\n" - + " " - + " .setResponseMarshaller(ProtoUtils.marshaller(EchoResponse.getDefaultInstance()))\n" - + " .build();\n" - + " private static final MethodDescriptor" - + " collectMethodDescriptor =\n" - + " MethodDescriptor.newBuilder()\n" - + " .setType(MethodDescriptor.MethodType.CLIENT_STREAMING)\n" - + " .setFullMethodName(\"google.showcase.v1beta1.Echo/Collect\")\n" - + " " - + " .setRequestMarshaller(ProtoUtils.marshaller(EchoRequest.getDefaultInstance()))\n" - + " " - + " .setResponseMarshaller(ProtoUtils.marshaller(EchoResponse.getDefaultInstance()))\n" - + " .build();\n" - + " private static final MethodDescriptor" - + " chatMethodDescriptor =\n" - + " MethodDescriptor.newBuilder()\n" - + " .setType(MethodDescriptor.MethodType.BIDI_STREAMING)\n" - + " .setFullMethodName(\"google.showcase.v1beta1.Echo/Chat\")\n" - + " " - + " .setRequestMarshaller(ProtoUtils.marshaller(EchoRequest.getDefaultInstance()))\n" - + " " - + " .setResponseMarshaller(ProtoUtils.marshaller(EchoResponse.getDefaultInstance()))\n" - + " .build();\n" - + " private static final MethodDescriptor" - + " chatAgainMethodDescriptor =\n" - + " MethodDescriptor.newBuilder()\n" - + " .setType(MethodDescriptor.MethodType.BIDI_STREAMING)\n" - + " .setFullMethodName(\"google.showcase.v1beta1.Echo/ChatAgain\")\n" - + " " - + " .setRequestMarshaller(ProtoUtils.marshaller(EchoRequest.getDefaultInstance()))\n" - + " " - + " .setResponseMarshaller(ProtoUtils.marshaller(EchoResponse.getDefaultInstance()))\n" - + " .build();\n" - + " private static final MethodDescriptor\n" - + " pagedExpandMethodDescriptor =\n" - + " MethodDescriptor.newBuilder()\n" - + " .setType(MethodDescriptor.MethodType.UNARY)\n" - + " .setFullMethodName(\"google.showcase.v1beta1.Echo/PagedExpand\")\n" - + " " - + " .setRequestMarshaller(ProtoUtils.marshaller(PagedExpandRequest.getDefaultInstance()))\n" - + " .setResponseMarshaller(\n" - + " ProtoUtils.marshaller(PagedExpandResponse.getDefaultInstance()))\n" - + " .build();\n" - + " private static final MethodDescriptor waitMethodDescriptor" - + " =\n" - + " MethodDescriptor.newBuilder()\n" - + " .setType(MethodDescriptor.MethodType.UNARY)\n" - + " .setFullMethodName(\"google.showcase.v1beta1.Echo/Wait\")\n" - + " " - + " .setRequestMarshaller(ProtoUtils.marshaller(WaitRequest.getDefaultInstance()))\n" - + " " - + " .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))\n" - + " .build();\n" - + " private static final MethodDescriptor" - + " blockMethodDescriptor =\n" - + " MethodDescriptor.newBuilder()\n" - + " .setType(MethodDescriptor.MethodType.UNARY)\n" - + " .setFullMethodName(\"google.showcase.v1beta1.Echo/Block\")\n" - + " " - + " .setRequestMarshaller(ProtoUtils.marshaller(BlockRequest.getDefaultInstance()))\n" - + " " - + " .setResponseMarshaller(ProtoUtils.marshaller(BlockResponse.getDefaultInstance()))\n" - + " .build();\n" - + " private final UnaryCallable echoCallable;\n" - + " private final ServerStreamingCallable" - + " expandCallable;\n" - + " private final ClientStreamingCallable collectCallable;\n" - + " private final BidiStreamingCallable chatCallable;\n" - + " private final BidiStreamingCallable chatAgainCallable;\n" - + " private final UnaryCallable" - + " pagedExpandCallable;\n" - + " private final UnaryCallable\n" - + " pagedExpandPagedCallable;\n" - + " private final UnaryCallable waitCallable;\n" - + " private final OperationCallable" - + " waitOperationCallable;\n" - + " private final UnaryCallable blockCallable;\n" - + " private final BackgroundResource backgroundResources;\n" - + " private final GrpcOperationsStub operationsStub;\n" - + " private final GrpcStubCallableFactory callableFactory;\n" - + "\n" - + " public static final GrpcEchoStub create(EchoStubSettings settings) throws" - + " IOException {\n" - + " return new GrpcEchoStub(settings, ClientContext.create(settings));\n" - + " }\n" - + "\n" - + " public static final GrpcEchoStub create(ClientContext clientContext) throws" - + " IOException {\n" - + " return new GrpcEchoStub(EchoStubSettings.newBuilder().build(), clientContext);\n" - + " }\n" - + "\n" - + " public static final GrpcEchoStub create(\n" - + " ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws" - + " IOException {\n" - + " return new GrpcEchoStub(EchoStubSettings.newBuilder().build(), clientContext," - + " callableFactory);\n" - + " }\n" - + "\n" - + " protected GrpcEchoStub(EchoStubSettings settings, ClientContext clientContext)\n" - + " throws IOException {\n" - + " this(settings, clientContext, new GrpcEchoCallableFactory());\n" - + " }\n" - + "\n" - + " protected GrpcEchoStub(\n" - + " EchoStubSettings settings,\n" - + " ClientContext clientContext,\n" - + " GrpcStubCallableFactory callableFactory)\n" - + " throws IOException {\n" - + " this.callableFactory = callableFactory;\n" - + " this.operationsStub = GrpcOperationsStub.create(clientContext," - + " callableFactory);\n" - + " GrpcCallSettings echoTransportSettings =\n" - + " GrpcCallSettings.newBuilder()\n" - + " .setMethodDescriptor(echoMethodDescriptor)\n" - + " .build();\n" - + " GrpcCallSettings expandTransportSettings =\n" - + " GrpcCallSettings.newBuilder()\n" - + " .setMethodDescriptor(expandMethodDescriptor)\n" - + " .build();\n" - + " GrpcCallSettings collectTransportSettings =\n" - + " GrpcCallSettings.newBuilder()\n" - + " .setMethodDescriptor(collectMethodDescriptor)\n" - + " .build();\n" - + " GrpcCallSettings chatTransportSettings =\n" - + " GrpcCallSettings.newBuilder()\n" - + " .setMethodDescriptor(chatMethodDescriptor)\n" - + " .build();\n" - + " GrpcCallSettings chatAgainTransportSettings =\n" - + " GrpcCallSettings.newBuilder()\n" - + " .setMethodDescriptor(chatAgainMethodDescriptor)\n" - + " .build();\n" - + " GrpcCallSettings" - + " pagedExpandTransportSettings =\n" - + " GrpcCallSettings.newBuilder()\n" - + " .setMethodDescriptor(pagedExpandMethodDescriptor)\n" - + " .build();\n" - + " GrpcCallSettings waitTransportSettings =\n" - + " GrpcCallSettings.newBuilder()\n" - + " .setMethodDescriptor(waitMethodDescriptor)\n" - + " .build();\n" - + " GrpcCallSettings blockTransportSettings =\n" - + " GrpcCallSettings.newBuilder()\n" - + " .setMethodDescriptor(blockMethodDescriptor)\n" - + " .build();\n" - + " this.echoCallable =\n" - + " callableFactory.createUnaryCallable(\n" - + " echoTransportSettings, settings.echoSettings(), clientContext);\n" - + " this.expandCallable =\n" - + " callableFactory.createServerStreamingCallable(\n" - + " expandTransportSettings, settings.expandSettings(), clientContext);\n" - + " this.collectCallable =\n" - + " callableFactory.createClientStreamingCallable(\n" - + " collectTransportSettings, settings.collectSettings(), clientContext);\n" - + " this.chatCallable =\n" - + " callableFactory.createBidiStreamingCallable(\n" - + " chatTransportSettings, settings.chatSettings(), clientContext);\n" - + " this.chatAgainCallable =\n" - + " callableFactory.createBidiStreamingCallable(\n" - + " chatAgainTransportSettings, settings.chatAgainSettings()," - + " clientContext);\n" - + " this.pagedExpandCallable =\n" - + " callableFactory.createUnaryCallable(\n" - + " pagedExpandTransportSettings, settings.pagedExpandSettings()," - + " clientContext);\n" - + " this.pagedExpandPagedCallable =\n" - + " callableFactory.createUnaryCallable(\n" - + " pagedExpandTransportSettings, settings.pagedExpandSettings()," - + " clientContext);\n" - + " this.waitCallable =\n" - + " callableFactory.createUnaryCallable(\n" - + " waitTransportSettings, settings.waitSettings(), clientContext);\n" - + " this.waitOperationCallable =\n" - + " callableFactory.createOperationCallable(\n" - + " waitTransportSettings, settings.waitOperationSettings(), clientContext," - + " operationsStub);\n" - + " this.blockCallable =\n" - + " callableFactory.createUnaryCallable(\n" - + " blockTransportSettings, settings.blockSettings(), clientContext);\n" - + " this.backgroundResources =\n" - + " new BackgroundResourceAggregation(clientContext.getBackgroundResources());\n" - + " }\n" - + "\n" - + " public GrpcOperationsStub getOperationsStub() {\n" - + " return operationsStub;\n" - + " }\n" - + "\n" - + " public UnaryCallable echoCallable() {\n" - + " return echoCallable;\n" - + " }\n" - + "\n" - + " public ServerStreamingCallable expandCallable() {\n" - + " return expandCallable;\n" - + " }\n" - + "\n" - + " public ClientStreamingCallable collectCallable() {\n" - + " return collectCallable;\n" - + " }\n" - + "\n" - + " public BidiStreamingCallable chatCallable() {\n" - + " return chatCallable;\n" - + " }\n" - + "\n" - + " public BidiStreamingCallable chatAgainCallable() {\n" - + " return chatAgainCallable;\n" - + " }\n" - + "\n" - + " public UnaryCallable pagedExpandCallable()" - + " {\n" - + " return pagedExpandCallable;\n" - + " }\n" - + "\n" - + " public UnaryCallable" - + " pagedExpandPagedCallable() {\n" - + " return pagedExpandPagedCallable;\n" - + " }\n" - + "\n" - + " public UnaryCallable waitCallable() {\n" - + " return waitCallable;\n" - + " }\n" - + "\n" - + " public OperationCallable" - + " waitOperationCallable() {\n" - + " return waitOperationCallable;\n" - + " }\n" - + "\n" - + " public UnaryCallable blockCallable() {\n" - + " return blockCallable;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public final void close() {\n" - + " shutdown();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void shutdown() {\n" - + " backgroundResources.shutdown();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public boolean isShutdown() {\n" - + " return backgroundResources.isShutdown();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public boolean isTerminated() {\n" - + " return backgroundResources.isTerminated();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void shutdownNow() {\n" - + " backgroundResources.shutdownNow();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public boolean awaitTermination(long duration, TimeUnit unit) throws" - + " InterruptedException {\n" - + " return backgroundResources.awaitTermination(duration, unit);\n" - + " }\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java index 7bcb5e48dd..21921ce5a1 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java @@ -25,6 +25,10 @@ import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -33,6 +37,8 @@ import org.junit.Test; public class MockServiceClassComposerTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -44,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() { + public void generateServiceClasses() throws IOException { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -56,52 +62,8 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_CLASS_STRING, visitor.write()); + Path goldeFilePath = Paths.get(GOLDENFILES_DIRECTORY, "MockServiceClassComposerTest.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } - - // TODO(miraleung): Update this when a file-diffing test mechanism is in place. - private static final String EXPECTED_CLASS_STRING = - "package com.google.showcase.v1beta1;\n" - + "\n" - + "import com.google.api.core.BetaApi;\n" - + "import com.google.api.gax.grpc.testing.MockGrpcService;\n" - + "import com.google.protobuf.AbstractMessage;\n" - + "import io.grpc.ServerServiceDefinition;\n" - + "import java.util.List;\n" - + "import javax.annotation.Generated;\n" - + "\n" - + "@BetaApi\n" - + "@Generated(\"by gapic-generator-java\")\n" - + "public class MockEcho implements MockGrpcService {\n" - + " private final MockEchoImpl serviceImpl;\n" - + "\n" - + " public MockEcho() {\n" - + " serviceImpl = new MockEchoImpl();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public List getRequests() {\n" - + " return serviceImpl.getRequests();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void addResponse(AbstractMessage response) {\n" - + " serviceImpl.addResponse(response);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void addException(Exception exception) {\n" - + " serviceImpl.addException(exception);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ServerServiceDefinition getServiceDefinition() {\n" - + " return serviceImpl.bindService();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void reset() {\n" - + " serviceImpl.reset();\n" - + " }\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java index 8fe7478590..827436b3c2 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java @@ -25,6 +25,10 @@ import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -33,6 +37,8 @@ import org.junit.Test; public class MockServiceImplClassComposerTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -44,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() { + public void generateServiceClasses() throws IOException { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -57,236 +63,10 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_CLASS_STRING, visitor.write()); + Path goldeFilePath = + Paths.get(GOLDENFILES_DIRECTORY, "MockServiceImplClassComposerTest.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + System.out.println(visitor.write()); + assertEquals(expectedClassString, visitor.write()); } - - // TODO(miraleung): Update this when a file-diffing test mechanism is in place. - private static final String EXPECTED_CLASS_STRING = - "package com.google.showcase.v1beta1;\n" - + "\n" - + "import com.google.api.core.BetaApi;\n" - + "import com.google.longrunning.Operation;\n" - + "import com.google.protobuf.AbstractMessage;\n" - + "import com.google.showcase.v1beta1.EchoGrpc.EchoImplBase;\n" - + "import io.grpc.stub.StreamObserver;\n" - + "import java.util.ArrayList;\n" - + "import java.util.LinkedList;\n" - + "import java.util.List;\n" - + "import java.util.Queue;\n" - + "import javax.annotation.Generated;\n" - + "\n" - + "@BetaApi\n" - + "@Generated(\"by gapic-generator-java\")\n" - + "public class MockEchoImpl extends EchoImplBase {\n" - + " private List requests;\n" - + " private Queue responses;\n" - + "\n" - + " public MockEchoImpl() {\n" - + " requests = new ArrayList<>();\n" - + " responses = new LinkedList<>();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public List getRequests() {\n" - + " return requests;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void addResponse(AbstractMessage response) {\n" - + " responses.add(response);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void setResponses(List responses) {\n" - + " this.responses = new LinkedList(responses);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void addException(Exception exception) {\n" - + " responses.add(exception);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void reset() {\n" - + " requests = new ArrayList<>();\n" - + " responses = new LinkedList<>();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void echo(EchoRequest request, StreamObserver" - + " responseObserver) {\n" - + " Object response = responses.remove();\n" - + " if (response instanceof EchoResponse) {\n" - + " requests.add(request);\n" - + " responseObserver.onNext(((EchoResponse) response));\n" - + " responseObserver.onCompleted();\n" - + " } else if (response instanceof Exception) {\n" - + " responseObserver.onError(((Exception) response));\n" - + " } else {\n" - + " responseObserver.onError(new " - + "IllegalArgumentException(\"Unrecognized response type\"));\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void expand(ExpandRequest request, StreamObserver" - + " responseObserver) {\n" - + " Object response = responses.remove();\n" - + " if (response instanceof EchoResponse) {\n" - + " requests.add(request);\n" - + " responseObserver.onNext(((EchoResponse) response));\n" - + " responseObserver.onCompleted();\n" - + " } else if (response instanceof Exception) {\n" - + " responseObserver.onError(((Exception) response));\n" - + " } else {\n" - + " responseObserver.onError(new " - + "IllegalArgumentException(\"Unrecognized response type\"));\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public StreamObserver collect(final StreamObserver" - + " responseObserver) {\n" - + " StreamObserver requestObserver =\n" - + " new StreamObserver() {\n" - + " @Override\n" - + " public void onNext(EchoRequest value) {\n" - + " requests.add(value);\n" - + " final Object response = responses.remove();\n" - + " if (response instanceof EchoResponse) {\n" - + " responseObserver.onNext(((EchoResponse) response));\n" - + " } else if (response instanceof Exception) {\n" - + " responseObserver.onError(((Exception) response));\n" - + " } else {\n" - + " responseObserver.onError(new " - + "IllegalArgumentException(\"Unrecognized response type\"));\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void onError(Throwable t) {\n" - + " responseObserver.onError(t);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void onCompleted() {\n" - + " responseObserver.onCompleted();\n" - + " }\n" - + " };\n" - + " return requestObserver;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public StreamObserver chat(final StreamObserver" - + " responseObserver) {\n" - + " StreamObserver requestObserver =\n" - + " new StreamObserver() {\n" - + " @Override\n" - + " public void onNext(EchoRequest value) {\n" - + " requests.add(value);\n" - + " final Object response = responses.remove();\n" - + " if (response instanceof EchoResponse) {\n" - + " responseObserver.onNext(((EchoResponse) response));\n" - + " } else if (response instanceof Exception) {\n" - + " responseObserver.onError(((Exception) response));\n" - + " } else {\n" - + " responseObserver.onError(new " - + "IllegalArgumentException(\"Unrecognized response type\"));\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void onError(Throwable t) {\n" - + " responseObserver.onError(t);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void onCompleted() {\n" - + " responseObserver.onCompleted();\n" - + " }\n" - + " };\n" - + " return requestObserver;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public StreamObserver chatAgain(\n" - + " final StreamObserver responseObserver) {\n" - + " StreamObserver requestObserver =\n" - + " new StreamObserver() {\n" - + " @Override\n" - + " public void onNext(EchoRequest value) {\n" - + " requests.add(value);\n" - + " final Object response = responses.remove();\n" - + " if (response instanceof EchoResponse) {\n" - + " responseObserver.onNext(((EchoResponse) response));\n" - + " } else if (response instanceof Exception) {\n" - + " responseObserver.onError(((Exception) response));\n" - + " } else {\n" - + " responseObserver.onError(new " - + "IllegalArgumentException(\"Unrecognized response type\"));\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void onError(Throwable t) {\n" - + " responseObserver.onError(t);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void onCompleted() {\n" - + " responseObserver.onCompleted();\n" - + " }\n" - + " };\n" - + " return requestObserver;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void pagedExpand(\n" - + " PagedExpandRequest request, StreamObserver" - + " responseObserver) {\n" - + " Object response = responses.remove();\n" - + " if (response instanceof PagedExpandResponse) {\n" - + " requests.add(request);\n" - + " responseObserver.onNext(((PagedExpandResponse) response));\n" - + " responseObserver.onCompleted();\n" - + " } else if (response instanceof Exception) {\n" - + " responseObserver.onError(((Exception) response));\n" - + " } else {\n" - + " responseObserver.onError(new " - + "IllegalArgumentException(\"Unrecognized response type\"));\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void wait(WaitRequest request, StreamObserver responseObserver)" - + " {\n" - + " Object response = responses.remove();\n" - + " if (response instanceof Operation) {\n" - + " requests.add(request);\n" - + " responseObserver.onNext(((Operation) response));\n" - + " responseObserver.onCompleted();\n" - + " } else if (response instanceof Exception) {\n" - + " responseObserver.onError(((Exception) response));\n" - + " } else {\n" - + " responseObserver.onError(new " - + "IllegalArgumentException(\"Unrecognized response type\"));\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void block(BlockRequest request, StreamObserver" - + " responseObserver) {\n" - + " Object response = responses.remove();\n" - + " if (response instanceof BlockResponse) {\n" - + " requests.add(request);\n" - + " responseObserver.onNext(((BlockResponse) response));\n" - + " responseObserver.onCompleted();\n" - + " } else if (response instanceof Exception) {\n" - + " responseObserver.onError(((Exception) response));\n" - + " } else {\n" - + " responseObserver.onError(new " - + "IllegalArgumentException(\"Unrecognized response type\"));\n" - + " }\n" - + " }\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java index 836c2cbcf8..d9c6fbc0e5 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java @@ -27,6 +27,10 @@ import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; import com.google.showcase.v1beta1.TestingOuterClass; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.List; @@ -38,6 +42,8 @@ import org.junit.Test; public class ResourceNameHelperClassComposerTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -161,7 +167,7 @@ public void concatToUpperCamelCaseName_basic() { } @Test - public void generateResourceNameClass_echoFoobarMultiplePatterns() { + public void generateResourceNameClass_echoFoobarMultiplePatterns() throws IOException { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -176,11 +182,14 @@ public void generateResourceNameClass_echoFoobarMultiplePatterns() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_FOOBAR_NAME_CLASS_STRING, visitor.write()); + Path goldeFilePath = + Paths.get(GOLDENFILES_DIRECTORY, "ResourceNameHelperClassComposerTestMultiPattern.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } @Test - public void generateResourceNameClass_testingSessionOnePattern() { + public void generateResourceNameClass_testingSessionOnePattern() throws IOException { FileDescriptor testingFileDescriptor = TestingOuterClass.getDescriptor(); ServiceDescriptor testingService = testingFileDescriptor.getServices().get(0); assertEquals(testingService.getName(), "Testing"); @@ -200,473 +209,10 @@ public void generateResourceNameClass_testingSessionOnePattern() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_SESSION_NAME_CLASS_STRING, visitor.write()); + Path goldeFilePath = + Paths.get(GOLDENFILES_DIRECTORY, "ResourceNameHelperClassComposerTestOnePattern.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } - // TODO(miraleung): Add more tests for a single pattern. - // TODO(miraleung): Update this when a file-diffing test mechanism is in place. - private static final String EXPECTED_FOOBAR_NAME_CLASS_STRING = - "package com.google.showcase.v1beta1;\n" - + "\n" - + "import com.google.api.core.BetaApi;\n" - + "import com.google.api.pathtemplate.PathTemplate;\n" - + "import com.google.api.pathtemplate.ValidationException;\n" - + "import com.google.api.resourcenames.ResourceName;\n" - + "import com.google.common.base.Preconditions;\n" - + "import com.google.common.collect.ImmutableMap;\n" - + "import java.util.ArrayList;\n" - + "import java.util.List;\n" - + "import java.util.Map;\n" - + "import java.util.Objects;\n" - + "import javax.annotation.Generated;\n" - + "\n" - + "// AUTO-GENERATED DOCUMENTATION AND CLASS.\n" - + "@Generated(\"by gapic-generator-java\")\n" - + "public class FoobarName implements ResourceName {\n" - + " private static final PathTemplate PROJECT_FOOBAR =\n" - + " " - + " PathTemplate.createWithoutUrlEncoding(\"projects/{project}/foobars/{foobar}\");\n" - + " private static final PathTemplate PROJECT_VARIANT_FOOBAR =\n" - + " PathTemplate.createWithoutUrlEncoding(\n" - + " \"projects/{project}/chocolate/variants/{variant}/foobars/{foobar}\");\n" - + " private static final PathTemplate FOOBAR =\n" - + " PathTemplate.createWithoutUrlEncoding(\"foobars/{foobar}\");\n" - + " private volatile Map fieldValuesMap;\n" - + " private PathTemplate pathTemplate;\n" - + " private String fixedValue;\n" - + " private final String project;\n" - + " private final String foobar;\n" - + " private final String variant;\n" - + "\n" - + " @Deprecated\n" - + " protected FoobarName() {}\n" - + "\n" - + " private FoobarName(Builder builder) {\n" - + " project = Preconditions.checkNotNull(builder.getProject());\n" - + " foobar = Preconditions.checkNotNull(builder.getFoobar());\n" - + " pathTemplate = PROJECT_FOOBAR;\n" - + " }\n" - + "\n" - + " private FoobarName(ProjectVariantFoobarBuilder builder) {\n" - + " project = Preconditions.checkNotNull(builder.getProject());\n" - + " variant = Preconditions.checkNotNull(builder.getVariant());\n" - + " foobar = Preconditions.checkNotNull(builder.getFoobar());\n" - + " pathTemplate = PROJECT_VARIANT_FOOBAR;\n" - + " }\n" - + "\n" - + " private FoobarName(FoobarBuilder builder) {\n" - + " foobar = Preconditions.checkNotNull(builder.getFoobar());\n" - + " pathTemplate = FOOBAR;\n" - + " }\n" - + "\n" - + " public String getProject() {\n" - + " return project;\n" - + " }\n" - + "\n" - + " public String getFoobar() {\n" - + " return foobar;\n" - + " }\n" - + "\n" - + " public String getVariant() {\n" - + " return variant;\n" - + " }\n" - + "\n" - + " public static Builder newBuilder() {\n" - + " return new Builder();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The per-pattern Builders are not stable yet and may be changed in the" - + " future.\")\n" - + " public static Builder newProjectFoobarBuilder() {\n" - + " return new Builder();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The per-pattern Builders are not stable yet and may be changed in the" - + " future.\")\n" - + " public static ProjectVariantFoobarBuilder newProjectVariantFoobarBuilder() {\n" - + " return new ProjectVariantFoobarBuilder();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The per-pattern Builders are not stable yet and may be changed in the" - + " future.\")\n" - + " public static FoobarBuilder newFoobarBuilder() {\n" - + " return new FoobarBuilder();\n" - + " }\n" - + "\n" - + " public Builder toBuilder() {\n" - + " return new Builder(this);\n" - + " }\n" - + "\n" - + " public static FoobarName of(String project, String foobar) {\n" - + " return newBuilder().setProject(project).setFoobar(foobar).build();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The static create methods are not stable yet and may be changed in the" - + " future.\")\n" - + " public static FoobarName ofProjectFoobarBuilder(String project, String foobar) {\n" - + " return newBuilder().setProject(project).setFoobar(foobar).build();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The static create methods are not stable yet and may be changed in the" - + " future.\")\n" - + " public static FoobarName ofProjectVariantFoobarBuilder(\n" - + " String project, String variant, String foobar) {\n" - + " return newProjectVariantFoobarBuilder()\n" - + " .setProject(project)\n" - + " .setVariant(variant)\n" - + " .setFoobar(foobar)\n" - + " .build();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The static create methods are not stable yet and may be changed in the" - + " future.\")\n" - + " public static FoobarName ofFoobarBuilder(String foobar) {\n" - + " return newFoobarBuilder().setFoobar(foobar).build();\n" - + " }\n" - + "\n" - + " public static String format(String project, String foobar) {\n" - + " return newBuilder().setProject(project).setFoobar(foobar).build().toString();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The static format methods are not stable yet and may be changed in the" - + " future.\")\n" - + " public static String formatProjectFoobarBuilder(String project, String foobar) {\n" - + " return newBuilder().setProject(project).setFoobar(foobar).build().toString();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The static format methods are not stable yet and may be changed in the" - + " future.\")\n" - + " public static String formatProjectVariantFoobarBuilder(\n" - + " String project, String variant, String foobar) {\n" - + " return newProjectVariantFoobarBuilder()\n" - + " .setProject(project)\n" - + " .setVariant(variant)\n" - + " .setFoobar(foobar)\n" - + " .build()\n" - + " .toString();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The static format methods are not stable yet and may be changed in the" - + " future.\")\n" - + " public static String formatFoobarBuilder(String foobar) {\n" - + " return newFoobarBuilder().setFoobar(foobar).build().toString();\n" - + " }\n" - + "\n" - + " public static FoobarName parse(String formattedString) {\n" - + " if (formattedString.isEmpty()) {\n" - + " return null;\n" - + " }\n" - + " if (PROJECT_FOOBAR.matches(formattedString)) {\n" - + " Map matchMap = PROJECT_FOOBAR.match(formattedString);\n" - + " return ofProjectFoobarBuilder(matchMap.get(\"project\")," - + " matchMap.get(\"foobar\"));\n" - + " } else if (PROJECT_VARIANT_FOOBAR.matches(formattedString)) {\n" - + " Map matchMap = PROJECT_VARIANT_FOOBAR.match(formattedString);\n" - + " return ofProjectVariantFoobarBuilder(\n" - + " matchMap.get(\"project\"), matchMap.get(\"variant\")," - + " matchMap.get(\"foobar\"));\n" - + " } else if (FOOBAR.matches(formattedString)) {\n" - + " Map matchMap = FOOBAR.match(formattedString);\n" - + " return ofFoobarBuilder(matchMap.get(\"foobar\"));\n" - + " }\n" - + " throw new ValidationException(\"FoobarName.parse: formattedString not in valid" - + " format\");\n" - + " }\n" - + "\n" - + " public static List parseList(List formattedStrings) {\n" - + " List list = new ArrayList<>(formattedStrings.size());\n" - + " for (String formattedString : formattedStrings) {\n" - + " list.add(parse(formattedString));\n" - + " }\n" - + " return list;\n" - + " }\n" - + "\n" - + " public static List toStringList(List values) {\n" - + " List list = new ArrayList<>(values.size());\n" - + " for (FoobarName value : values) {\n" - + " if (Objects.equals(value, null)) {\n" - + " list.add(\"\");\n" - + " } else {\n" - + " list.add(value.toString());\n" - + " }\n" - + " }\n" - + " return list;\n" - + " }\n" - + "\n" - + " public static boolean isParsableFrom(String formattedString) {\n" - + " return PROJECT_FOOBAR\n" - + " .matches(formattedString)\n" - + " .todoOr(PROJECT_VARIANT_FOOBAR.matches(formattedString))\n" - + " .todoOr(FOOBAR.matches(formattedString));\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Map getFieldValuesMap() {\n" - + " if (Objects.equals(fieldValuesMap, null)) {\n" - + " synchronized (this) {\n" - + " if (Objects.equals(fieldValuesMap, null)) {\n" - + " ImmutableMap.Builder fieldMapBuilder =" - + " ImmutableMap.builder();\n" - + " if (Objects.notTodoEquals(project, null)) {\n" - + " fieldMapBuilder.put(\"project\", project);\n" - + " }\n" - + " if (Objects.notTodoEquals(foobar, null)) {\n" - + " fieldMapBuilder.put(\"foobar\", foobar);\n" - + " }\n" - + " if (Objects.notTodoEquals(variant, null)) {\n" - + " fieldMapBuilder.put(\"variant\", variant);\n" - + " }\n" - + " fieldValuesMap = fieldMapBuilder.build();\n" - + " }\n" - + " }\n" - + " }\n" - + " return fieldValuesMap;\n" - + " }\n" - + "\n" - + " public String getFieldValue(String fieldName) {\n" - + " return getFieldValuesMap().get(fieldName);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String toString() {\n" - + " return Objects.equals(fixedValue, null)\n" - + " ? pathTemplate.instantiate(getFieldValuesMap())\n" - + " : fixedValue;\n" - + " }\n" - + "\n" - + " /** Builder for projects/{project}/foobars/{foobar}. */\n" - + " public static class Builder {\n" - + " private String project;\n" - + " private String foobar;\n" - + "\n" - + " private Builder() {}\n" - + "\n" - + " public String getProject() {\n" - + " return project;\n" - + " }\n" - + "\n" - + " public String getFoobar() {\n" - + " return foobar;\n" - + " }\n" - + "\n" - + " public Builder setProject(String project) {\n" - + " this.project = project;\n" - + " return this;\n" - + " }\n" - + "\n" - + " public Builder setFoobar(String foobar) {\n" - + " this.foobar = foobar;\n" - + " return this;\n" - + " }\n" - + "\n" - + " private Builder(FoobarName foobarName) {\n" - + " Preconditions.checkArgument(\n" - + " Objects.equals(foobarName.pathTemplate, PROJECT_FOOBAR),\n" - + " \"toBuilder is only supported when FoobarName has the pattern of" - + " projects/{project}/foobars/{foobar}\");\n" - + " project = foobarName.project;\n" - + " foobar = foobarName.foobar;\n" - + " }\n" - + "\n" - + " public FoobarName build() {\n" - + " return new FoobarName(this);\n" - + " }\n" - + " }\n" - + "\n" - + " /** Builder for projects/{project}/chocolate/variants/{variant}/foobars/{foobar}." - + " */\n" - + " @BetaApi(\"The per-pattern Builders are not stable yet and may be changed in the" - + " future.\")\n" - + " public static class ProjectVariantFoobarBuilder {\n" - + " private String project;\n" - + " private String variant;\n" - + " private String foobar;\n" - + "\n" - + " private ProjectVariantFoobarBuilder() {}\n" - + "\n" - + " public String getProject() {\n" - + " return project;\n" - + " }\n" - + "\n" - + " public String getVariant() {\n" - + " return variant;\n" - + " }\n" - + "\n" - + " public String getFoobar() {\n" - + " return foobar;\n" - + " }\n" - + "\n" - + " public ProjectVariantFoobarBuilder setProject(String project) {\n" - + " this.project = project;\n" - + " return this;\n" - + " }\n" - + "\n" - + " public ProjectVariantFoobarBuilder setVariant(String variant) {\n" - + " this.variant = variant;\n" - + " return this;\n" - + " }\n" - + "\n" - + " public ProjectVariantFoobarBuilder setFoobar(String foobar) {\n" - + " this.foobar = foobar;\n" - + " return this;\n" - + " }\n" - + "\n" - + " public FoobarName build() {\n" - + " return new FoobarName(this);\n" - + " }\n" - + " }\n" - + "\n" - + " /** Builder for foobars/{foobar}. */\n" - + " @BetaApi(\"The per-pattern Builders are not stable yet and may be changed in the" - + " future.\")\n" - + " public static class FoobarBuilder {\n" - + " private String foobar;\n" - + "\n" - + " private FoobarBuilder() {}\n" - + "\n" - + " public String getFoobar() {\n" - + " return foobar;\n" - + " }\n" - + "\n" - + " public FoobarBuilder setFoobar(String foobar) {\n" - + " this.foobar = foobar;\n" - + " return this;\n" - + " }\n" - + "\n" - + " public FoobarName build() {\n" - + " return new FoobarName(this);\n" - + " }\n" - + " }\n" - + "}\n"; - - private static final String EXPECTED_SESSION_NAME_CLASS_STRING = - "package com.google.showcase.v1beta1;\n" - + "\n" - + "import com.google.api.pathtemplate.PathTemplate;\n" - + "import com.google.api.resourcenames.ResourceName;\n" - + "import com.google.common.base.Preconditions;\n" - + "import com.google.common.collect.ImmutableMap;\n" - + "import java.util.ArrayList;\n" - + "import java.util.List;\n" - + "import java.util.Map;\n" - + "import java.util.Objects;\n" - + "import javax.annotation.Generated;\n" - + "\n" - + "// AUTO-GENERATED DOCUMENTATION AND CLASS.\n" - + "@Generated(\"by gapic-generator-java\")\n" - + "public class SessionName implements ResourceName {\n" - + " private static final PathTemplate SESSION =\n" - + " PathTemplate.createWithoutUrlEncoding(\"sessions/{session}\");\n" - + " private volatile Map fieldValuesMap;\n" - + " private final String session;\n" - + "\n" - + " private SessionName(Builder builder) {\n" - + " session = Preconditions.checkNotNull(builder.getSession());\n" - + " }\n" - + "\n" - + " public String getSession() {\n" - + " return session;\n" - + " }\n" - + "\n" - + " public static Builder newBuilder() {\n" - + " return new Builder();\n" - + " }\n" - + "\n" - + " public Builder toBuilder() {\n" - + " return new Builder(this);\n" - + " }\n" - + "\n" - + " public static SessionName of(String session) {\n" - + " return newBuilder().setSession(session).build();\n" - + " }\n" - + "\n" - + " public static String format(String session) {\n" - + " return newBuilder().setSession(session).build().toString();\n" - + " }\n" - + "\n" - + " public static SessionName parse(String formattedString) {\n" - + " if (formattedString.isEmpty()) {\n" - + " return null;\n" - + " }\n" - + " Map matchMap =\n" - + " SESSION.validatedMatch(\n" - + " formattedString, \"SessionName.parse:" - + " formattedString not in valid format\");\n" - + " return of(matchMap.get(\"session\"));\n" - + " }\n" - + "\n" - + " public static List parseList(List formattedStrings) {\n" - + " List list = new ArrayList<>(formattedStrings.size());\n" - + " for (String formattedString : formattedStrings) {\n" - + " list.add(parse(formattedString));\n" - + " }\n" - + " return list;\n" - + " }\n" - + "\n" - + " public static List toStringList(List values) {\n" - + " List list = new ArrayList<>(values.size());\n" - + " for (SessionName value : values) {\n" - + " if (Objects.equals(value, null)) {\n" - + " list.add(\"\");\n" - + " } else {\n" - + " list.add(value.toString());\n" - + " }\n" - + " }\n" - + " return list;\n" - + " }\n" - + "\n" - + " public static boolean isParsableFrom(String formattedString) {\n" - + " return SESSION.matches(formattedString);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Map getFieldValuesMap() {\n" - + " if (Objects.equals(fieldValuesMap, null)) {\n" - + " synchronized (this) {\n" - + " if (Objects.equals(fieldValuesMap, null)) {\n" - + " ImmutableMap.Builder fieldMapBuilder =" - + " ImmutableMap.builder();\n" - + " if (Objects.notTodoEquals(session, null)) {\n" - + " fieldMapBuilder.put(\"session\", session);\n" - + " }\n" - + " fieldValuesMap = fieldMapBuilder.build();\n" - + " }\n" - + " }\n" - + " }\n" - + " return fieldValuesMap;\n" - + " }\n" - + "\n" - + " public String getFieldValue(String fieldName) {\n" - + " return getFieldValuesMap().get(fieldName);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String toString() {\n" - + " return SESSION.instantiate(\"session\", session);\n" - + " }\n" - + "\n" - + " /** Builder for sessions/{session}. */\n" - + " public static class Builder {\n" - + " private String session;\n" - + "\n" - + " private Builder() {}\n" - + "\n" - + " public String getSession() {\n" - + " return session;\n" - + " }\n" - + "\n" - + " public Builder setSession(String session) {\n" - + " this.session = session;\n" - + " return this;\n" - + " }\n" - + "\n" - + " private Builder(SessionName sessionName) {\n" - + " session = sessionName.session;\n" - + " }\n" - + "\n" - + " public SessionName build() {\n" - + " return new SessionName(this);\n" - + " }\n" - + " }\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java index c5df016a51..498d6d0db3 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java @@ -25,6 +25,10 @@ import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -33,6 +37,8 @@ import org.junit.Test; public class ServiceClientClassComposerTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -44,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() { + public void generateServiceClasses() throws IOException { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -57,210 +63,8 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_CLASS_STRING, visitor.write()); + Path goldeFilePath = Paths.get(GOLDENFILES_DIRECTORY, "ServiceClientClassComposerTest.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } - - // TODO(miraleung): Update this when a file-diffing test mechanism is in place. - private static final String EXPECTED_CLASS_STRING = - "package com.google.showcase.v1beta1;\n" - + "\n" - + "import com.google.api.core.BetaApi;\n" - + "import com.google.api.gax.core.BackgroundResource;\n" - + "import com.google.api.gax.longrunning.OperationFuture;\n" - + "import com.google.api.gax.rpc.BidiStreamingCallable;\n" - + "import com.google.api.gax.rpc.ClientStreamingCallable;\n" - + "import com.google.api.gax.rpc.OperationCallable;\n" - + "import com.google.api.gax.rpc.ServerStreamingCallable;\n" - + "import com.google.api.gax.rpc.UnaryCallable;\n" - + "import com.google.api.resourcenames.ResourceName;\n" - + "import com.google.common.base.Strings;\n" - + "import com.google.longrunning.Operation;\n" - + "import com.google.longrunning.OperationsClient;\n" - + "import com.google.rpc.Status;\n" - + "import com.google.showcase.v1beta1.stub.EchoStub;\n" - + "import com.google.showcase.v1beta1.stub.EchoStubSettings;\n" - + "import java.io.IOException;\n" - + "import java.util.concurrent.TimeUnit;\n" - + "import javax.annotation.Generated;\n" - + "\n" - + "@BetaApi\n" - + "@Generated(\"by gapic-generator\")\n" - + "public class EchoClient implements BackgroundResource {\n" - + " private final EchoSettings settings;\n" - + " private final EchoStub stub;\n" - + " private final OperationsClient operationsClient;\n" - + "\n" - + " public static final EchoClient create() throws IOException {\n" - + " return create(EchoSettings.newBuilder().build());\n" - + " }\n" - + "\n" - + " public static final EchoClient create(EchoSettings settings) throws IOException {\n" - + " return new EchoClient(settings);\n" - + " }\n" - + "\n" - + " @BetaApi(\"A restructuring of stub classes is planned, so this may break in the" - + " future\")\n" - + " public static final EchoClient create(EchoStub stub) {\n" - + " return new EchoClient(stub);\n" - + " }\n" - + "\n" - + " protected EchoClient(EchoSettings settings) throws IOException {\n" - + " this.settings = settings;\n" - + " this.stub = ((EchoStubSettings) settings.getStubSettings()).createStub();\n" - + " this.operationsClient = OperationsClient.create(this.stub.getOperationsStub());\n" - + " }\n" - + "\n" - + " @BetaApi(\"A restructuring of stub classes is planned, so this may break in the" - + " future\")\n" - + " protected EchoClient(EchoStub stub) {\n" - + " this.settings = null;\n" - + " this.stub = stub;\n" - + " this.operationsClient = OperationsClient.create(this.stub.getOperationsStub());\n" - + " }\n" - + "\n" - + " public final EchoSettings getSettings() {\n" - + " return settings;\n" - + " }\n" - + "\n" - + " @BetaApi(\"A restructuring of stub classes is planned, so this may break in the" - + " future\")\n" - + " public EchoStub getStub() {\n" - + " return stub;\n" - + " }\n" - + "\n" - + " public final OperationsClient getOperationsClient() {\n" - + " return operationsClient;\n" - + " }\n" - + "\n" - + " public final EchoResponse echo(String content) {\n" - + " EchoRequest request = EchoRequest.newBuilder().setContent(content).build();\n" - + " return echo(request);\n" - + " }\n" - + "\n" - + " public final EchoResponse echo(Status error) {\n" - + " EchoRequest request = EchoRequest.newBuilder().setError(error).build();\n" - + " return echo(request);\n" - + " }\n" - + "\n" - + " public final EchoResponse echo(String content, Severity severity) {\n" - + " EchoRequest request =\n" - + " EchoRequest.newBuilder().setContent(content).setSeverity(severity).build();\n" - + " return echo(request);\n" - + " }\n" - + "\n" - + " public final EchoResponse echo(String name) {\n" - + " EchoRequest request = EchoRequest.newBuilder().setName(name).build();\n" - + " return echo(request);\n" - + " }\n" - + "\n" - + " public final EchoResponse echo(FoobarName name) {\n" - + " EchoRequest request =\n" - + " EchoRequest.newBuilder()\n" - + " .setName(Strings.isNullOrEmpty(name) ? null : name.toString())\n" - + " .build();\n" - + " return echo(request);\n" - + " }\n" - + "\n" - + " public final EchoResponse echo(String parent) {\n" - + " EchoRequest request = EchoRequest.newBuilder().setParent(parent).build();\n" - + " return echo(request);\n" - + " }\n" - + "\n" - + " public final EchoResponse echo(ResourceName parent) {\n" - + " EchoRequest request =\n" - + " EchoRequest.newBuilder()\n" - + " .setParent(Strings.isNullOrEmpty(parent) ? null : parent.toString())\n" - + " .build();\n" - + " return echo(request);\n" - + " }\n" - + "\n" - + " public final EchoResponse echo(EchoRequest request) {\n" - + " return echoCallable().call(request);\n" - + " }\n" - + "\n" - + " public final UnaryCallable echoCallable() {\n" - + " return stub.echoCallable();\n" - + " }\n" - + "\n" - + " public final ServerStreamingCallable expandCallable()" - + " {\n" - + " return stub.expandCallable();\n" - + " }\n" - + "\n" - + " public final ClientStreamingCallable collectCallable()" - + " {\n" - + " return stub.collectCallable();\n" - + " }\n" - + "\n" - + " public final BidiStreamingCallable chatCallable() {\n" - + " return stub.chatCallable();\n" - + " }\n" - + "\n" - + " public final BidiStreamingCallable chatAgainCallable()" - + " {\n" - + " return stub.chatAgainCallable();\n" - + " }\n" - + "\n" - + " public final PagedExpandResponse pagedExpand(PagedExpandRequest request) {\n" - + " return pagedExpandCallable().call(request);\n" - + " }\n" - + "\n" - + " public final UnaryCallable" - + " pagedExpandCallable() {\n" - + " return stub.pagedExpandCallable();\n" - + " }\n" - + "\n" - + " public final OperationFuture waitAsync(WaitRequest" - + " request) {\n" - + " return waitOperationCallable().futureCall(request);\n" - + " }\n" - + "\n" - + " public final OperationCallable" - + " waitOperationCallabke() {\n" - + " return stub.waitOperationCallabke();\n" - + " }\n" - + "\n" - + " public final UnaryCallable waitCallable() {\n" - + " return stub.waitCallable();\n" - + " }\n" - + "\n" - + " public final BlockResponse block(BlockRequest request) {\n" - + " return blockCallable().call(request);\n" - + " }\n" - + "\n" - + " public final UnaryCallable blockCallable() {\n" - + " return stub.blockCallable();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public final void close() {\n" - + " stub.close();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void shutdown() {\n" - + " stub.shutdown();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public boolean isShutdown() {\n" - + " return stub.isShutdown();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public boolean isTerminated() {\n" - + " return stub.isTerminated();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void shutdownNow() {\n" - + " stub.shutdownNow();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public boolean awaitTermination(long duration, TimeUnit unit) throws" - + " InterruptedException {\n" - + " return stub.awaitTermination(duration, unit);\n" - + " }\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java index 090428c836..1b48c9246f 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java @@ -25,6 +25,10 @@ import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -33,6 +37,8 @@ import org.junit.Test; public class ServiceClientTestClassComposerTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -44,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() { + public void generateServiceClasses() throws IOException { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -57,62 +63,9 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_CLASS_STRING, visitor.write()); + Path goldeFilePath = + Paths.get(GOLDENFILES_DIRECTORY, "ServiceClientTestClassComposerTest.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } - - // TODO(miraleung): Update this when a file-diffing test mechanism is in place. - private static final String EXPECTED_CLASS_STRING = - "package com.google.showcase.v1beta1;\n" - + "\n" - + "import com.google.api.gax.core.NoCredentialsProvider;\n" - + "import com.google.api.gax.grpc.testing.LocalChannelProvider;\n" - + "import com.google.api.gax.grpc.testing.MockGrpcService;\n" - + "import com.google.api.gax.grpc.testing.MockServiceHelper;\n" - + "import java.io.IOException;\n" - + "import java.util.Arrays;\n" - + "import java.util.UUID;\n" - + "import javax.annotation.Generated;\n" - + "import org.junit.After;\n" - + "import org.junit.AfterClass;\n" - + "import org.junit.Before;\n" - + "import org.junit.BeforeClass;\n" - + "\n" - + "@Generated(\"by gapic-generator-java\")\n" - + "public class EchoClientTest {\n" - + " public static MockServiceHelper mockServiceHelper;\n" - + " public static MockEcho mockEcho;\n" - + " public EchoClient client;\n" - + " public LocalChannelProvider channelProvider;\n" - + "\n" - + " @BeforeClass\n" - + " public static void startStaticServer() {\n" - + " mockEcho = new MockEcho();\n" - + " mockServiceHelper =\n" - + " new MockServiceHelper(\n" - + " UUID.randomUUID().toString(), Arrays.asList(mockEcho));\n" - + " mockServiceHelper.start();\n" - + " }\n" - + "\n" - + " @AfterClass\n" - + " public static void stopServer() {\n" - + " mockServiceHelper.stop();\n" - + " }\n" - + "\n" - + " @Before\n" - + " public void setUp() throws IOException {\n" - + " mockServiceHelper.reset();\n" - + " channelProvider = mockServiceHelper.createChannelProvider();\n" - + " settings =\n" - + " EchoSettings.newBuilder()\n" - + " .setTransportChannelProvider(channelProvider)\n" - + " .setCredentialsProvider(NoCredentialsProvider.create())\n" - + " .build();\n" - + " client = EchoClient.create(settings);\n" - + " }\n" - + "\n" - + " @After\n" - + " public static void tearDown() throws Exception {\n" - + " client.close();\n" - + " }\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java index 110d54f7d5..7d19d5d7ff 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java @@ -25,6 +25,10 @@ import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -33,6 +37,8 @@ import org.junit.Test; public class ServiceSettingsClassComposerTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -44,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() { + public void generateServiceClasses() throws IOException { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -57,272 +63,9 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_CLASS_STRING, visitor.write()); + Path goldeFilePath = + Paths.get(GOLDENFILES_DIRECTORY, "ServiceSettingsClassComposerTest.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } - - // TODO(miraleung): Update this when a file-diffing test mechanism is in place. - private static final String EXPECTED_CLASS_STRING = - "package com.google.showcase.v1beta1;\n" - + "\n" - + "import static com.google.showcase.v1beta1.EchoClient.PagedExpandPagedResponse;\n" - + "\n" - + "import com.google.api.core.ApiFunction;\n" - + "import com.google.api.core.BetaApi;\n" - + "import com.google.api.gax.core.GoogleCredentialsProvider;\n" - + "import com.google.api.gax.core.InstantiatingExecutorProvider;\n" - + "import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;\n" - + "import com.google.api.gax.rpc.ApiClientHeaderProvider;\n" - + "import com.google.api.gax.rpc.ClientContext;\n" - + "import com.google.api.gax.rpc.ClientSettings;\n" - + "import com.google.api.gax.rpc.OperationCallSettings;\n" - + "import com.google.api.gax.rpc.PagedCallSettings;\n" - + "import com.google.api.gax.rpc.ServerStreamingCallSettings;\n" - + "import com.google.api.gax.rpc.StreamingCallSettings;\n" - + "import com.google.api.gax.rpc.StubSettings;\n" - + "import com.google.api.gax.rpc.TransportChannelProvider;\n" - + "import com.google.api.gax.rpc.UnaryCallSettings;\n" - + "import com.google.longrunning.Operation;\n" - + "import com.google.showcase.v1beta1.stub.EchoStubSettings;\n" - + "import java.io.IOException;\n" - + "import java.util.List;\n" - + "import javax.annotation.Generated;\n" - + "\n" - + "// AUTO-GENERATED DOCUMENTATION AND CLASS.\n" - + "/**\n" - + " * Settings class to configure an instance of {@link EchoClient}.\n" - + " *\n" - + " *

The default instance has everything set to sensible defaults:\n" - + " *\n" - + " *

    \n" - + " *
  • The default service address (localhost) and default port (7469) are used.\n" - + " *
  • Credentials are acquired automatically through Application Default" - + " Credentials.\n" - + " *
  • Retries are configured for idempotent methods but not for non-idempotent" - + " methods.\n" - + " *
\n" - + " *\n" - + " *

The builder of this class is recursive, so contained classes are themselves" - + " builders. When\n" - + " * build() is called, the tree of builders is called to create the complete settings" - + " object.\n" - + " *\n" - + " *

For example, to set the total timeout of echo to 30 seconds:\n" - + " */\n" - + "@Generated(\"by gapic-generator-java\")\n" - + "public class EchoSettings extends ClientSettings {\n" - + "\n" - + " /** Returns the object with the settings used for calls to echo. */\n" - + " public UnaryCallSettings echoSettings() {\n" - + " return ((EchoStubSettings) getStubSettings()).echoSettings();\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to expand. */\n" - + " public ServerStreamingCallSettings expandSettings()" - + " {\n" - + " return ((EchoStubSettings) getStubSettings()).expandSettings();\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to collect. */\n" - + " public StreamingCallSettings collectSettings() {\n" - + " return ((EchoStubSettings) getStubSettings()).collectSettings();\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to chat. */\n" - + " public StreamingCallSettings chatSettings() {\n" - + " return ((EchoStubSettings) getStubSettings()).chatSettings();\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to chatAgain. */\n" - + " public StreamingCallSettings chatAgainSettings() {\n" - + " return ((EchoStubSettings) getStubSettings()).chatAgainSettings();\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to pagedExpand. */\n" - + " public PagedCallSettings\n" - + " pagedExpandSettings() {\n" - + " return ((EchoStubSettings) getStubSettings()).pagedExpandSettings();\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to wait. */\n" - + " public UnaryCallSettings waitSettings() {\n" - + " return ((EchoStubSettings) getStubSettings()).waitSettings();\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to wait. */\n" - + " public OperationCallSettings" - + " waitOperationSettings() {\n" - + " return ((EchoStubSettings) getStubSettings()).waitOperationSettings();\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to block. */\n" - + " public UnaryCallSettings blockSettings() {\n" - + " return ((EchoStubSettings) getStubSettings()).blockSettings();\n" - + " }\n" - + "\n" - + " public static final EchoSettings create(EchoStubSettings stub) throws IOException" - + " {\n" - + " return new EchoStubSettings.Builder(stub.toBuilder()).build();\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default ExecutorProvider for this service. */\n" - + " public static InstantiatingExecutorProvider.Builder" - + " defaultExecutorProviderBuilder() {\n" - + " return EchoStubSettings.defaultExecutorProviderBuilder();\n" - + " }\n" - + "\n" - + " /** Returns the default service endpoint. */\n" - + " public static String getDefaultEndpoint() {\n" - + " return EchoStubSettings.getDefaultEndpoint();\n" - + " }\n" - + "\n" - + " /** Returns the default service scopes. */\n" - + " public static List getDefaultServiceScopes() {\n" - + " return EchoStubSettings.getDefaultServiceScopes();\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default credentials for this service. */\n" - + " public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder()" - + " {\n" - + " return EchoStubSettings.defaultCredentialsProviderBuilder();\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default ChannelProvider for this service. */\n" - + " public static InstantiatingGrpcChannelProvider.Builder" - + " defaultGrpcTransportProviderBuilder() {\n" - + " return EchoStubSettings.defaultGrpcTransportProviderBuilder();\n" - + " }\n" - + "\n" - + " public static TransportChannelProvider defaultTransportChannelProvider() {\n" - + " return EchoStubSettings.defaultTransportChannelProvider();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The surface for customizing headers is not stable yet and may change in" - + " the future.\")\n" - + " public static ApiClientHeaderProvider.Builder" - + " defaultApiClientHeaderProviderBuilder() {\n" - + " return EchoStubSettings.defaultApiClientHeaderProviderBuilder();\n" - + " }\n" - + "\n" - + " /** Returns a new builder for this class. */\n" - + " public static Builder newBuilder() {\n" - + " return Builder.createDefault();\n" - + " }\n" - + "\n" - + " /** Returns a new builder for this class. */\n" - + " public static Builder newBuilder(ClientContext clientContext) {\n" - + " return new Builder(clientContext);\n" - + " }\n" - + "\n" - + " /** Returns a builder containing all the values of this settings class. */\n" - + " public Builder toBuilder() {\n" - + " return new Builder(this);\n" - + " }\n" - + "\n" - + " protected EchoSettings(Builder settingsBuilder) throws IOException {\n" - + " super(settingsBuilder);\n" - + " }\n" - + "\n" - + " /** Builder for EchoSettings. */\n" - + " public static class Builder extends ClientSettings.Builder" - + " {\n" - + "\n" - + " protected Builder() throws IOException {\n" - + " this(((ClientContext) null));\n" - + " }\n" - + "\n" - + " protected Builder(ClientContext clientContext) {\n" - + " super(EchoStubSettings.newBuilder(clientContext));\n" - + " }\n" - + "\n" - + " protected Builder(EchoSettings settings) {\n" - + " super(settings.getStubSettings().toBuilder());\n" - + " }\n" - + "\n" - + " protected Builder(EchoStubSettings.Builder stubSettings) {\n" - + " super(stubSettings);\n" - + " }\n" - + "\n" - + " private static Builder createDefault() {\n" - + " return new Builder(EchoStubSettings.newBuilder());\n" - + " }\n" - + "\n" - + " public EchoStubSettings.Builder getStubSettingsBuilder() {\n" - + " return ((EchoStubSettings.Builder) getStubSettings());\n" - + " }\n" - + "\n" - + " // NEXT_MAJOR_VER: remove 'throws Exception'.\n" - + " /**\n" - + " * Applies the given settings updater function to all of the unary API methods in" - + " this service.\n" - + " *\n" - + " *

Note: This method does not support applying settings to streaming" - + " methods.\n" - + " */\n" - + " public Builder applyToAllUnaryMethods(\n" - + " ApiFunction, Void> settingsUpdater) throws" - + " Exception {\n" - + " super.applyToAllUnaryMethods(\n" - + " getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater);\n" - + " return this;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to echo. */\n" - + " public UnaryCallSettings.Builder echoSettings() {\n" - + " return getStubSettingsBuilder().echoSettings();\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to expand. */\n" - + " public ServerStreamingCallSettings.Builder" - + " expandSettings() {\n" - + " return getStubSettingsBuilder().expandSettings();\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to collect. */\n" - + " public StreamingCallSettings.Builder collectSettings()" - + " {\n" - + " return getStubSettingsBuilder().collectSettings();\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to chat. */\n" - + " public StreamingCallSettings.Builder chatSettings()" - + " {\n" - + " return getStubSettingsBuilder().chatSettings();\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to chatAgain. */\n" - + " public StreamingCallSettings.Builder" - + " chatAgainSettings() {\n" - + " return getStubSettingsBuilder().chatAgainSettings();\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to pagedExpand. */\n" - + " public PagedCallSettings.Builder<\n" - + " PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse>\n" - + " pagedExpandSettings() {\n" - + " return getStubSettingsBuilder().pagedExpandSettings();\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to wait. */\n" - + " public UnaryCallSettings.Builder waitSettings() {\n" - + " return getStubSettingsBuilder().waitSettings();\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to wait. */\n" - + " public OperationCallSettings.Builder\n" - + " waitOperationSettings() {\n" - + " return getStubSettingsBuilder().waitOperationSettings();\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to block. */\n" - + " public UnaryCallSettings.Builder blockSettings() {\n" - + " return getStubSettingsBuilder().blockSettings();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public EchoSettings build() throws IOException {\n" - + " return new EchoSettings(this);\n" - + " }\n" - + " }\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java index 8ce0fac92c..b9672c43c5 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java @@ -25,6 +25,10 @@ import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -33,6 +37,8 @@ import org.junit.Test; public class ServiceStubClassComposerTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -44,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() { + public void generateServiceClasses() throws IOException { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -56,89 +62,8 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_CLASS_STRING, visitor.write()); + Path goldeFilePath = Paths.get(GOLDENFILES_DIRECTORY, "ServiceStubClassComposerTest.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } - - // TODO(miraleung): Update this when a file-diffing test mechanism is in place. - private static final String EXPECTED_CLASS_STRING = - "package com.google.showcase.v1beta1.stub;\n" - + "\n" - + "import com.google.api.gax.core.BackgroundResource;\n" - + "import com.google.api.gax.rpc.BidiStreamingCallable;\n" - + "import com.google.api.gax.rpc.ClientStreamingCallable;\n" - + "import com.google.api.gax.rpc.OperationCallable;\n" - + "import com.google.api.gax.rpc.ServerStreamingCallable;\n" - + "import com.google.api.gax.rpc.UnaryCallable;\n" - + "import com.google.longrunning.stub.OperationsStub;\n" - + "import com.google.showcase.v1beta1.BlockRequest;\n" - + "import com.google.showcase.v1beta1.BlockResponse;\n" - + "import com.google.showcase.v1beta1.EchoRequest;\n" - + "import com.google.showcase.v1beta1.EchoResponse;\n" - + "import com.google.showcase.v1beta1.ExpandRequest;\n" - + "import com.google.showcase.v1beta1.PagedExpandRequest;\n" - + "import com.google.showcase.v1beta1.PagedExpandResponse;\n" - + "import com.google.showcase.v1beta1.WaitMetadata;\n" - + "import com.google.showcase.v1beta1.WaitRequest;\n" - + "import com.google.showcase.v1beta1.WaitResponse;\n" - + "import javax.annotation.Generated;\n" - + "\n" - + "// AUTO-GENERATED DOCUMENTATION AND CLASS.\n" - + "/**\n" - + " * Base stub class for the Echo service API.\n" - + " *\n" - + " *

This class is for advanced usage and reflects the underlying API directly.\n" - + " */\n" - + "@Generated(\"by gapic-generator\")\n" - + "public abstract class EchoStub implements BackgroundResource {\n" - + "\n" - + " public OperationsStub getOperationsStub() {\n" - + " throw new UnsupportedOperationException(\"Not implemented:" - + " getOperationsStub()\");\n" - + " }\n" - + "\n" - + " public UnaryCallable echoCallable() {\n" - + " throw new UnsupportedOperationException(\"Not implemented: echoCallable()\");\n" - + " }\n" - + "\n" - + " public ServerStreamingCallable expandCallable() {\n" - + " throw new UnsupportedOperationException(\"Not implemented: expandCallable()\");\n" - + " }\n" - + "\n" - + " public ClientStreamingCallable collectCallable() {\n" - + " throw new UnsupportedOperationException(\"Not implemented:" - + " collectCallable()\");\n" - + " }\n" - + "\n" - + " public BidiStreamingCallable chatCallable() {\n" - + " throw new UnsupportedOperationException(\"Not implemented: chatCallable()\");\n" - + " }\n" - + "\n" - + " public BidiStreamingCallable chatAgainCallable() {\n" - + " throw new UnsupportedOperationException(\"Not implemented:" - + " chatAgainCallable()\");\n" - + " }\n" - + "\n" - + " public UnaryCallable pagedExpandCallable()" - + " {\n" - + " throw new UnsupportedOperationException(\"Not implemented:" - + " pagedExpandCallable()\");\n" - + " }\n" - + "\n" - + " public OperationCallable" - + " waitOperationCallable() {\n" - + " throw new UnsupportedOperationException(\"Not implemented:" - + " waitOperationCallable()\");\n" - + " }\n" - + "\n" - + " public UnaryCallable waitCallable() {\n" - + " throw new UnsupportedOperationException(\"Not implemented: waitCallable()\");\n" - + " }\n" - + "\n" - + " public UnaryCallable blockCallable() {\n" - + " throw new UnsupportedOperationException(\"Not implemented: blockCallable()\");\n" - + " }\n" - + "\n" - + " @Override\n" - + " public abstract void close();\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java index 2003af7eb2..3995cde711 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java @@ -36,6 +36,8 @@ import com.google.pubsub.v1.PubsubProto; import com.google.showcase.v1beta1.EchoOuterClass; import google.cloud.CommonResources; +import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; @@ -48,11 +50,13 @@ import org.junit.Test; public class ServiceStubSettingsClassComposerTest { + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; private static final String TESTFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/testdata/"; @Test - public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() { + public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() throws IOException { FileDescriptor serviceFileDescriptor = LoggingProto.getDescriptor(); ServiceDescriptor serviceDescriptor = serviceFileDescriptor.getServices().get(0); assertEquals(serviceDescriptor.getName(), "LoggingServiceV2"); @@ -93,11 +97,15 @@ public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_LOGGING_STUB_SETTINGS_STRING, visitor.write()); + Path goldeFilePath = + Paths.get(GOLDENFILES_DIRECTORY, "ServiceStubSettingsClassComposerTestLogging.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } @Test - public void generateServiceStubSettingsClasses_batchingWithNonemptyResponses() { + public void generateServiceStubSettingsClasses_batchingWithNonemptyResponses() + throws IOException { FileDescriptor serviceFileDescriptor = PubsubProto.getDescriptor(); FileDescriptor commonResourcesFileDescriptor = CommonResources.getDescriptor(); ServiceDescriptor serviceDescriptor = serviceFileDescriptor.getServices().get(0); @@ -132,11 +140,14 @@ public void generateServiceStubSettingsClasses_batchingWithNonemptyResponses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_PUBLISHER_STUB_SETTINGS_STRING, visitor.write()); + Path goldeFilePath = + Paths.get(GOLDENFILES_DIRECTORY, "ServiceStubSettingsClassComposerTestPublisher.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } @Test - public void generateServiceStubSettingsClasses_basic() { + public void generateServiceStubSettingsClasses_basic() throws IOException { FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor(); ServiceDescriptor echoServiceDescriptor = echoFileDescriptor.getServices().get(0); assertEquals(echoServiceDescriptor.getName(), "Echo"); @@ -160,7 +171,10 @@ public void generateServiceStubSettingsClasses_basic() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - assertEquals(EXPECTED_ECHO_STUB_SETTINGS_STRING, visitor.write()); + Path goldeFilePath = + Paths.get(GOLDENFILES_DIRECTORY, "ServiceStubSettingsClassComposerTestEcho.golden"); + String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); + assertEquals(expectedClassString, visitor.write()); } private static List parseServices( @@ -172,2157 +186,4 @@ private static List parseServices( return Parser.parseService( protoFileDescriptor, messageTypes, resourceNames, outputResourceNames); } - - // TODO(miraleung): Update this when a file-diffing test mechanism is in place. - private static final String EXPECTED_ECHO_STUB_SETTINGS_STRING = - "package com.google.showcase.v1beta1.stub;\n" - + "\n" - + "import static com.google.showcase.v1beta1.EchoClient.PagedExpandPagedResponse;\n" - + "\n" - + "import com.google.api.core.ApiFunction;\n" - + "import com.google.api.core.ApiFuture;\n" - + "import com.google.api.core.BetaApi;\n" - + "import com.google.api.gax.core.GaxProperties;\n" - + "import com.google.api.gax.core.GoogleCredentialsProvider;\n" - + "import com.google.api.gax.core.InstantiatingExecutorProvider;\n" - + "import com.google.api.gax.grpc.GaxGrpcProperties;\n" - + "import com.google.api.gax.grpc.GrpcTransportChannel;\n" - + "import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;\n" - + "import com.google.api.gax.grpc.ProtoOperationTransformers;\n" - + "import com.google.api.gax.longrunning.OperationSnapshot;\n" - + "import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;\n" - + "import com.google.api.gax.retrying.RetrySettings;\n" - + "import com.google.api.gax.rpc.ApiCallContext;\n" - + "import com.google.api.gax.rpc.ApiClientHeaderProvider;\n" - + "import com.google.api.gax.rpc.ClientContext;\n" - + "import com.google.api.gax.rpc.OperationCallSettings;\n" - + "import com.google.api.gax.rpc.PageContext;\n" - + "import com.google.api.gax.rpc.PagedCallSettings;\n" - + "import com.google.api.gax.rpc.PagedListDescriptor;\n" - + "import com.google.api.gax.rpc.PagedListResponseFactory;\n" - + "import com.google.api.gax.rpc.ServerStreamingCallSettings;\n" - + "import com.google.api.gax.rpc.StatusCode;\n" - + "import com.google.api.gax.rpc.StreamingCallSettings;\n" - + "import com.google.api.gax.rpc.StubSettings;\n" - + "import com.google.api.gax.rpc.TransportChannelProvider;\n" - + "import com.google.api.gax.rpc.UnaryCallSettings;\n" - + "import com.google.api.gax.rpc.UnaryCallable;\n" - + "import com.google.common.collect.ImmutableList;\n" - + "import com.google.common.collect.ImmutableMap;\n" - + "import com.google.common.collect.ImmutableSet;\n" - + "import com.google.common.collect.Lists;\n" - + "import com.google.longrunning.Operation;\n" - + "import com.google.showcase.v1beta1.BlockRequest;\n" - + "import com.google.showcase.v1beta1.BlockResponse;\n" - + "import com.google.showcase.v1beta1.EchoRequest;\n" - + "import com.google.showcase.v1beta1.EchoResponse;\n" - + "import com.google.showcase.v1beta1.ExpandRequest;\n" - + "import com.google.showcase.v1beta1.PagedExpandRequest;\n" - + "import com.google.showcase.v1beta1.PagedExpandResponse;\n" - + "import com.google.showcase.v1beta1.WaitMetadata;\n" - + "import com.google.showcase.v1beta1.WaitRequest;\n" - + "import com.google.showcase.v1beta1.WaitResponse;\n" - + "import java.io.IOException;\n" - + "import java.util.List;\n" - + "import java.util.Objects;\n" - + "import javax.annotation.Generated;\n" - + "import org.threeten.bp.Duration;\n" - + "\n" - + "// AUTO-GENERATED DOCUMENTATION AND CLASS.\n" - + "/**\n" - + " * Settings class to configure an instance of {@link EchoStub}.\n" - + " *\n" - + " *

The default instance has everything set to sensible defaults:\n" - + " *\n" - + " *

    \n" - + " *
  • The default service address (localhost) and default port (7469) are used.\n" - + " *
  • Credentials are acquired automatically through Application Default" - + " Credentials.\n" - + " *
  • Retries are configured for idempotent methods but not for non-idempotent" - + " methods.\n" - + " *
\n" - + " *\n" - + " *

The builder of this class is recursive, so contained classes are themselves" - + " builders. When\n" - + " * build() is called, the tree of builders is called to create the complete settings" - + " object.\n" - + " *\n" - + " *

For example, to set the total timeout of echo to 30 seconds:\n" - + " */\n" - + "@BetaApi\n" - + "@Generated(\"by gapic-generator-java\")\n" - + "public class EchoStubSettings extends StubSettings {\n" - + " /** The default scopes of the service. */\n" - + " private static final ImmutableList DEFAULT_SERVICE_SCOPES =\n" - + " " - + " ImmutableList.builder().add(\"https://www.googleapis.com/auth/cloud-platform\").build();\n" - + "\n" - + " private final UnaryCallSettings echoSettings;\n" - + " private final ServerStreamingCallSettings" - + " expandSettings;\n" - + " private final StreamingCallSettings collectSettings;\n" - + " private final StreamingCallSettings chatSettings;\n" - + " private final StreamingCallSettings chatAgainSettings;\n" - + " private final PagedCallSettings\n" - + " pagedExpandSettings;\n" - + " private final UnaryCallSettings waitSettings;\n" - + " private final OperationCallSettings\n" - + " waitOperationSettings;\n" - + " private final UnaryCallSettings blockSettings;\n" - + " private static final PagedListDescriptor\n" - + " PAGED_EXPAND_PAGE_STR_DESC =\n" - + " new PagedListDescriptor() {\n" - + " @Override\n" - + " public String emptyToken() {\n" - + " return \"\";\n" - + " }\n" - + "\n" - + " @Override\n" - + " public PagedExpandRequest injectToken(PagedExpandRequest payload, String" - + " token) {\n" - + " return" - + " PagedExpandRequest.newBuilder(payload).setPageToken(token).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public PagedExpandRequest injectPageSize(PagedExpandRequest payload, int" - + " pageSize) {\n" - + " return" - + " PagedExpandRequest.newBuilder(payload).setPageSize(pageSize).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Integer extractPageSize(PagedExpandRequest payload) {\n" - + " return payload.getPageSize();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String extractNextToken(PagedExpandResponse payload) {\n" - + " return payload.getNextPageToken();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Iterable extractResources(PagedExpandResponse" - + " payload) {\n" - + " return Objects.equals(payload.getResponsesList(), null)\n" - + " ? ImmutableList.of()\n" - + " : payload.getResponsesList();\n" - + " }\n" - + " };\n" - + " private static final PagedListResponseFactory<\n" - + " PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse>\n" - + " PAGED_EXPAND_PAGE_STR_FACT =\n" - + " new PagedListResponseFactory<\n" - + " PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse>()" - + " {\n" - + " @Override\n" - + " public ApiFuture getFuturePagedResponse(\n" - + " UnaryCallable callable,\n" - + " PagedExpandRequest request,\n" - + " ApiCallContext context,\n" - + " ApiFuture futureResponse) {\n" - + " PageContext" - + " pageContext =\n" - + " PageContext.create(callable, PAGED_EXPAND_PAGE_STR_DESC, request," - + " context);\n" - + " return PagedExpandPagedResponse.createAsync(pageContext," - + " futureResponse);\n" - + " }\n" - + " };\n" - + "\n" - + " /** Returns the object with the settings used for calls to echo. */\n" - + " public UnaryCallSettings echoSettings() {\n" - + " return echoSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to expand. */\n" - + " public ServerStreamingCallSettings expandSettings()" - + " {\n" - + " return expandSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to collect. */\n" - + " public StreamingCallSettings collectSettings() {\n" - + " return collectSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to chat. */\n" - + " public StreamingCallSettings chatSettings() {\n" - + " return chatSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to chatAgain. */\n" - + " public StreamingCallSettings chatAgainSettings() {\n" - + " return chatAgainSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to pagedExpand. */\n" - + " public PagedCallSettings\n" - + " pagedExpandSettings() {\n" - + " return pagedExpandSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to wait. */\n" - + " public UnaryCallSettings waitSettings() {\n" - + " return waitSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to wait. */\n" - + " public OperationCallSettings" - + " waitOperationSettings() {\n" - + " return waitOperationSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to block. */\n" - + " public UnaryCallSettings blockSettings() {\n" - + " return blockSettings;\n" - + " }\n" - + "\n" - + " @BetaApi(\"A restructuring of stub classes is planned, so this may break in the" - + " future\")\n" - + " public EchoStub createStub() throws IOException {\n" - + " if (getTransportChannelProvider()\n" - + " .getTransportName()\n" - + " .equals(GrpcTransportChannel.getGrpcTransportName())) {\n" - + " return GrpcEchoStub.create(this);\n" - + " }\n" - + " throw new UnsupportedOperationException(\n" - + " String.format(\n" - + " \"Transport not supported: %s\"," - + " getTransportChannelProvider().getTransportName()));\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default ExecutorProvider for this service. */\n" - + " public static InstantiatingExecutorProvider.Builder" - + " defaultExecutorProviderBuilder() {\n" - + " return InstantiatingExecutorProvider.newBuilder();\n" - + " }\n" - + "\n" - + " /** Returns the default service endpoint. */\n" - + " public static String getDefaultEndpoint() {\n" - + " return \"localhost:7469\";\n" - + " }\n" - + "\n" - + " /** Returns the default service scopes. */\n" - + " public static List getDefaultServiceScopes() {\n" - + " return DEFAULT_SERVICE_SCOPES;\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default credentials for this service. */\n" - + " public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder()" - + " {\n" - + " return" - + " GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES);\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default ChannelProvider for this service. */\n" - + " public static InstantiatingGrpcChannelProvider.Builder" - + " defaultGrpcTransportProviderBuilder() {\n" - + " return InstantiatingGrpcChannelProvider.newBuilder()\n" - + " .setMaxInboundMessageSize(Integer.MAX_VALUE);\n" - + " }\n" - + "\n" - + " public static TransportChannelProvider defaultTransportChannelProvider() {\n" - + " return defaultGrpcTransportProviderBuilder().build();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The surface for customizing headers is not stable yet and may change in" - + " the future.\")\n" - + " public static ApiClientHeaderProvider.Builder" - + " defaultApiClientHeaderProviderBuilder() {\n" - + " return ApiClientHeaderProvider.newBuilder()\n" - + " .setGeneratedLibToken(\"gapic\"," - + " GaxProperties.getLibraryVersion(EchoStubSettings.class))\n" - + " .setTransportToken(\n" - + " GaxGrpcProperties.getGrpcTokenName()," - + " GaxGrpcProperties.getGrpcVersion());\n" - + " }\n" - + "\n" - + " /** Returns a new builder for this class. */\n" - + " public static Builder newBuilder() {\n" - + " return Builder.createDefault();\n" - + " }\n" - + "\n" - + " /** Returns a new builder for this class. */\n" - + " public static Builder newBuilder(ClientContext clientContext) {\n" - + " return new Builder(clientContext);\n" - + " }\n" - + "\n" - + " /** Returns a builder containing all the values of this settings class. */\n" - + " public Builder toBuilder() {\n" - + " return new Builder(this);\n" - + " }\n" - + "\n" - + " protected EchoStubSettings(Builder settingsBuilder) throws IOException {\n" - + " super(settingsBuilder);\n" - + " echoSettings = settingsBuilder.echoSettings().build();\n" - + " expandSettings = settingsBuilder.expandSettings().build();\n" - + " collectSettings = settingsBuilder.collectSettings().build();\n" - + " chatSettings = settingsBuilder.chatSettings().build();\n" - + " chatAgainSettings = settingsBuilder.chatAgainSettings().build();\n" - + " pagedExpandSettings = settingsBuilder.pagedExpandSettings().build();\n" - + " waitSettings = settingsBuilder.waitSettings().build();\n" - + " waitOperationSettings = settingsBuilder.waitOperationSettings().build();\n" - + " blockSettings = settingsBuilder.blockSettings().build();\n" - + " }\n" - + "\n" - + " /** Builder for EchoStubSettings. */\n" - + " public static class Builder extends StubSettings.Builder {\n" - + " private final ImmutableList>" - + " unaryMethodSettingsBuilders;\n" - + " private final UnaryCallSettings.Builder" - + " echoSettings;\n" - + " private final ServerStreamingCallSettings.Builder" - + " expandSettings;\n" - + " private final StreamingCallSettings.Builder" - + " collectSettings;\n" - + " private final StreamingCallSettings.Builder" - + " chatSettings;\n" - + " private final StreamingCallSettings.Builder" - + " chatAgainSettings;\n" - + " private final PagedCallSettings.Builder<\n" - + " PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse>\n" - + " pagedExpandSettings;\n" - + " private final UnaryCallSettings.Builder waitSettings;\n" - + " private final OperationCallSettings.Builder\n" - + " waitOperationSettings;\n" - + " private final UnaryCallSettings.Builder" - + " blockSettings;\n" - + " private static final ImmutableMap>\n" - + " RETRYABLE_CODE_DEFINITIONS;\n" - + "\n" - + " static {\n" - + " ImmutableMap.Builder> definitions =\n" - + " ImmutableMap.builder();\n" - + " definitions.put(\n" - + " \"retry_policy_1_codes\",\n" - + " ImmutableSet.copyOf(\n" - + " Lists.newArrayList(\n" - + " StatusCode.Code.UNAVAILABLE, StatusCode.Code.UNKNOWN)));\n" - + " definitions.put(\n" - + " \"no_retry_0_codes\"," - + " ImmutableSet.copyOf(Lists.newArrayList()));\n" - + " RETRYABLE_CODE_DEFINITIONS = definitions.build();\n" - + " }\n" - + "\n" - + " private static final ImmutableMap" - + " RETRY_PARAM_DEFINITIONS;\n" - + "\n" - + " static {\n" - + " ImmutableMap.Builder definitions =" - + " ImmutableMap.builder();\n" - + " RetrySettings settings = null;\n" - + " settings =\n" - + " RetrySettings.newBuilder()\n" - + " .setInitialRetryDelay(Duration.ofMillis(100L))\n" - + " .setRetryDelayMultiplier(2.0)\n" - + " .setMaxRetryDelay(Duration.ofMillis(3000L))\n" - + " .setInitialRpcTimeout(Duration.ofMillis(10000L))\n" - + " .setRpcTimeoutMultiplier(1.0)\n" - + " .setMaxRpcTimeout(Duration.ofMillis(10000L))\n" - + " .setTotalTimeout(Duration.ofMillis(10000L))\n" - + " .build();\n" - + " definitions.put(\"retry_policy_1_params\", settings);\n" - + " settings =\n" - + " RetrySettings.newBuilder()\n" - + " .setInitialRpcTimeout(Duration.ofMillis(5000L))\n" - + " .setRpcTimeoutMultiplier(1.0)\n" - + " .setMaxRpcTimeout(Duration.ofMillis(5000L))\n" - + " .setTotalTimeout(Duration.ofMillis(5000L))\n" - + " .build();\n" - + " definitions.put(\"no_retry_0_params\", settings);\n" - + " RETRY_PARAM_DEFINITIONS = definitions.build();\n" - + " }\n" - + "\n" - + " protected Builder() {\n" - + " this(((ClientContext) null));\n" - + " }\n" - + "\n" - + " protected Builder(ClientContext clientContext) {\n" - + " super(clientContext);\n" - + " echoSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();\n" - + " expandSettings = ServerStreamingCallSettings.newBuilder();\n" - + " collectSettings = StreamingCallSettings.newBuilder();\n" - + " chatSettings = StreamingCallSettings.newBuilder();\n" - + " chatAgainSettings = StreamingCallSettings.newBuilder();\n" - + " pagedExpandSettings =" - + " PagedCallSettings.newBuilder(PAGED_EXPAND_PAGE_STR_FACT);\n" - + " waitSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();\n" - + " waitOperationSettings = OperationCallSettings.newBuilder();\n" - + " blockSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();\n" - + " unaryMethodSettingsBuilders =\n" - + " ImmutableList.>of(\n" - + " echoSettings, pagedExpandSettings, waitSettings, blockSettings);\n" - + " initDefaults(this);\n" - + " }\n" - + "\n" - + " protected Builder(EchoStubSettings settings) {\n" - + " super(settings);\n" - + " echoSettings = settings.echoSettings.toBuilder();\n" - + " expandSettings = settings.expandSettings.toBuilder();\n" - + " collectSettings = settings.collectSettings.toBuilder();\n" - + " chatSettings = settings.chatSettings.toBuilder();\n" - + " chatAgainSettings = settings.chatAgainSettings.toBuilder();\n" - + " pagedExpandSettings = settings.pagedExpandSettings.toBuilder();\n" - + " waitSettings = settings.waitSettings.toBuilder();\n" - + " waitOperationSettings = settings.waitOperationSettings.toBuilder();\n" - + " blockSettings = settings.blockSettings.toBuilder();\n" - + " unaryMethodSettingsBuilders =\n" - + " ImmutableList.>of(\n" - + " echoSettings, pagedExpandSettings, waitSettings, blockSettings);\n" - + " }\n" - + "\n" - + " private static Builder createDefault() {\n" - + " Builder builder = new Builder(((ClientContext) null));\n" - + " builder.setTransportChannelProvider(defaultTransportChannelProvider());\n" - + " builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());\n" - + " " - + " builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());\n" - + " builder.setEndpoint(getDefaultEndpoint());\n" - + " return initDefaults(builder);\n" - + " }\n" - + "\n" - + " private static Builder initDefaults(Builder builder) {\n" - + " builder\n" - + " .echoSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"));\n" - + " builder\n" - + " .expandSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"));\n" - + " builder\n" - + " .pagedExpandSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"));\n" - + " builder\n" - + " .waitSettings()\n" - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"no_retry_0_codes\"))\n" - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"no_retry_0_params\"));\n" - + " builder\n" - + " .blockSettings()\n" - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"no_retry_0_codes\"))\n" - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"no_retry_0_params\"));\n" - + " builder\n" - + " .waitOperationSettings()\n" - + " .setInitialCallSettings(\n" - + " UnaryCallSettings.newUnaryCallSettingsBuilder()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"no_retry_0_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"no_retry_0_params\"))\n" - + " .build())\n" - + " .setResponseTransformer(\n" - + " " - + " ProtoOperationTransformers.ResponseTransformer.create(WaitResponse.class))\n" - + " .setMetadataTransformer(\n" - + " " - + " ProtoOperationTransformers.MetadataTransformer.create(WaitMetadata.class))\n" - + " .setPollingAlgorithm(\n" - + " OperationTimedPollAlgorithm.create(\n" - + " RetrySettings.newBuilder()\n" - + " .setInitialRetryDelay(Duration.ofMillis(500L))\n" - + " .setRetryDelayMultiplier(1.5)\n" - + " .setMaxRetryDelay(Duration.ofMillis(5000L))\n" - + " .setInitialRpcTimeout(Duration.ZERO)\n" - + " .setRpcTimeoutMultiplier(1.0)\n" - + " .setMaxRpcTimeout(Duration.ZERO)\n" - + " .setTotalTimeout(Duration.ofMillis(300000L))\n" - + " .build()));\n" - + " return builder;\n" - + " }\n" - + "\n" - + " // NEXT_MAJOR_VER: remove 'throws Exception'.\n" - + " /**\n" - + " * Applies the given settings updater function to all of the unary API methods in" - + " this service.\n" - + " *\n" - + " *

Note: This method does not support applying settings to streaming" - + " methods.\n" - + " */\n" - + " public Builder applyToAllUnaryMethods(\n" - + " ApiFunction, Void> settingsUpdater) throws" - + " Exception {\n" - + " super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);\n" - + " return this;\n" - + " }\n" - + "\n" - + " public ImmutableList>" - + " unaryMethodSettingsBuilders() {\n" - + " return unaryMethodSettingsBuilders;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to echo. */\n" - + " public UnaryCallSettings.Builder echoSettings() {\n" - + " return echoSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to expand. */\n" - + " public ServerStreamingCallSettings.Builder" - + " expandSettings() {\n" - + " return expandSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to collect. */\n" - + " public StreamingCallSettings.Builder collectSettings()" - + " {\n" - + " return collectSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to chat. */\n" - + " public StreamingCallSettings.Builder chatSettings()" - + " {\n" - + " return chatSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to chatAgain. */\n" - + " public StreamingCallSettings.Builder" - + " chatAgainSettings() {\n" - + " return chatAgainSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to pagedExpand. */\n" - + " public PagedCallSettings.Builder<\n" - + " PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse>\n" - + " pagedExpandSettings() {\n" - + " return pagedExpandSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to wait. */\n" - + " public UnaryCallSettings.Builder waitSettings() {\n" - + " return waitSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to wait. */\n" - + " @BetaApi(\n" - + " \"The surface for use by generated code is not stable yet and may change in" - + " the future.\")\n" - + " public OperationCallSettings.Builder\n" - + " waitOperationSettings() {\n" - + " return waitOperationSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to block. */\n" - + " public UnaryCallSettings.Builder blockSettings() {\n" - + " return blockSettings;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public EchoStubSettings build() throws IOException {\n" - + " return new EchoStubSettings(this);\n" - + " }\n" - + " }\n" - + "}\n"; - - private static final String EXPECTED_LOGGING_STUB_SETTINGS_STRING = - "package com.google.logging.v2.stub;\n" - + "\n" - + "import static" - + " com.google.logging.v2.LoggingServiceV2Client.ListLogEntriesPagedResponse;\n" - + "import static com.google.logging.v2.LoggingServiceV2Client.ListLogsPagedResponse;\n" - + "import static" - + " com.google.logging.v2.LoggingServiceV2Client.ListMonitoredResourceDescriptorsPagedResponse;\n" - + "\n" - + "import com.google.api.MonitoredResourceDescriptor;\n" - + "import com.google.api.core.ApiFunction;\n" - + "import com.google.api.core.ApiFuture;\n" - + "import com.google.api.core.BetaApi;\n" - + "import com.google.api.gax.batching.BatchingSettings;\n" - + "import com.google.api.gax.batching.FlowControlSettings;\n" - + "import com.google.api.gax.batching.FlowController;\n" - + "import com.google.api.gax.batching.PartitionKey;\n" - + "import com.google.api.gax.batching.RequestBuilder;\n" - + "import com.google.api.gax.core.GaxProperties;\n" - + "import com.google.api.gax.core.GoogleCredentialsProvider;\n" - + "import com.google.api.gax.core.InstantiatingExecutorProvider;\n" - + "import com.google.api.gax.grpc.GaxGrpcProperties;\n" - + "import com.google.api.gax.grpc.GrpcTransportChannel;\n" - + "import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;\n" - + "import com.google.api.gax.retrying.RetrySettings;\n" - + "import com.google.api.gax.rpc.ApiCallContext;\n" - + "import com.google.api.gax.rpc.ApiClientHeaderProvider;\n" - + "import com.google.api.gax.rpc.BatchedRequestIssuer;\n" - + "import com.google.api.gax.rpc.BatchingCallSettings;\n" - + "import com.google.api.gax.rpc.BatchingDescriptor;\n" - + "import com.google.api.gax.rpc.ClientContext;\n" - + "import com.google.api.gax.rpc.PageContext;\n" - + "import com.google.api.gax.rpc.PagedCallSettings;\n" - + "import com.google.api.gax.rpc.PagedListDescriptor;\n" - + "import com.google.api.gax.rpc.PagedListResponseFactory;\n" - + "import com.google.api.gax.rpc.StatusCode;\n" - + "import com.google.api.gax.rpc.StubSettings;\n" - + "import com.google.api.gax.rpc.TransportChannelProvider;\n" - + "import com.google.api.gax.rpc.UnaryCallSettings;\n" - + "import com.google.api.gax.rpc.UnaryCallable;\n" - + "import com.google.common.collect.ImmutableList;\n" - + "import com.google.common.collect.ImmutableMap;\n" - + "import com.google.common.collect.ImmutableSet;\n" - + "import com.google.common.collect.Lists;\n" - + "import com.google.logging.v2.DeleteLogRequest;\n" - + "import com.google.logging.v2.ListLogEntriesRequest;\n" - + "import com.google.logging.v2.ListLogEntriesResponse;\n" - + "import com.google.logging.v2.ListLogsRequest;\n" - + "import com.google.logging.v2.ListLogsResponse;\n" - + "import com.google.logging.v2.ListMonitoredResourceDescriptorsRequest;\n" - + "import com.google.logging.v2.ListMonitoredResourceDescriptorsResponse;\n" - + "import com.google.logging.v2.LogEntry;\n" - + "import com.google.logging.v2.WriteLogEntriesRequest;\n" - + "import com.google.logging.v2.WriteLogEntriesResponse;\n" - + "import com.google.protobuf.Empty;\n" - + "import java.io.IOException;\n" - + "import java.util.Collection;\n" - + "import java.util.List;\n" - + "import java.util.Objects;\n" - + "import javax.annotation.Generated;\n" - + "import org.threeten.bp.Duration;\n" - + "\n" - + "// AUTO-GENERATED DOCUMENTATION AND CLASS.\n" - + "/**\n" - + " * Settings class to configure an instance of {@link LoggingServiceV2Stub}.\n" - + " *\n" - + " *

The default instance has everything set to sensible defaults:\n" - + " *\n" - + " *

    \n" - + " *
  • The default service address (logging.googleapis.com) and default port (443)" - + " are used.\n" - + " *
  • Credentials are acquired automatically through Application Default" - + " Credentials.\n" - + " *
  • Retries are configured for idempotent methods but not for non-idempotent" - + " methods.\n" - + " *
\n" - + " *\n" - + " *

The builder of this class is recursive, so contained classes are themselves" - + " builders. When\n" - + " * build() is called, the tree of builders is called to create the complete settings" - + " object.\n" - + " *\n" - + " *

For example, to set the total timeout of deleteLog to 30 seconds:\n" - + " */\n" - + "@BetaApi\n" - + "@Generated(\"by gapic-generator-java\")\n" - + "public class LoggingServiceV2StubSettings extends" - + " StubSettings {\n" - + " /** The default scopes of the service. */\n" - + " private static final ImmutableList DEFAULT_SERVICE_SCOPES =\n" - + " ImmutableList.builder()\n" - + " .add(\"https://www.googleapis.com/auth/cloud-platform\")\n" - + " .add(\"https://www.googleapis.com/auth/cloud-platform.read-only\")\n" - + " .add(\"https://www.googleapis.com/auth/logging.admin\")\n" - + " .add(\"https://www.googleapis.com/auth/logging.read\")\n" - + " .add(\"https://www.googleapis.com/auth/logging.write\")\n" - + " .build();\n" - + "\n" - + " private final UnaryCallSettings deleteLogSettings;\n" - + " private final BatchingCallSettings\n" - + " writeLogEntriesSettings;\n" - + " private final PagedCallSettings<\n" - + " ListLogEntriesRequest, ListLogEntriesResponse," - + " ListLogEntriesPagedResponse>\n" - + " listLogEntriesSettings;\n" - + " private final PagedCallSettings<\n" - + " ListMonitoredResourceDescriptorsRequest,\n" - + " ListMonitoredResourceDescriptorsResponse,\n" - + " ListMonitoredResourceDescriptorsPagedResponse>\n" - + " listMonitoredResourceDescriptorsSettings;\n" - + " private final PagedCallSettings\n" - + " listLogsSettings;\n" - + " private static final PagedListDescriptor\n" - + " LIST_LOG_ENTRIES_PAGE_STR_DESC =\n" - + " new PagedListDescriptor() {\n" - + " @Override\n" - + " public String emptyToken() {\n" - + " return \"\";\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListLogEntriesRequest injectToken(ListLogEntriesRequest payload," - + " String token) {\n" - + " return" - + " ListLogEntriesRequest.newBuilder(payload).setPageToken(token).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListLogEntriesRequest injectPageSize(\n" - + " ListLogEntriesRequest payload, int pageSize) {\n" - + " return" - + " ListLogEntriesRequest.newBuilder(payload).setPageSize(pageSize).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Integer extractPageSize(ListLogEntriesRequest payload) {\n" - + " return payload.getPageSize();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String extractNextToken(ListLogEntriesResponse payload) {\n" - + " return payload.getNextPageToken();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Iterable extractResources(ListLogEntriesResponse" - + " payload) {\n" - + " return Objects.equals(payload.getResponsesList(), null)\n" - + " ? ImmutableList.of()\n" - + " : payload.getResponsesList();\n" - + " }\n" - + " };\n" - + " private static final PagedListDescriptor<\n" - + " ListMonitoredResourceDescriptorsRequest,\n" - + " ListMonitoredResourceDescriptorsResponse,\n" - + " MonitoredResourceDescriptor>\n" - + " LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC =\n" - + " new PagedListDescriptor<\n" - + " ListMonitoredResourceDescriptorsRequest,\n" - + " ListMonitoredResourceDescriptorsResponse,\n" - + " MonitoredResourceDescriptor>() {\n" - + " @Override\n" - + " public String emptyToken() {\n" - + " return \"\";\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListMonitoredResourceDescriptorsRequest injectToken(\n" - + " ListMonitoredResourceDescriptorsRequest payload, String token) {\n" - + " return ListMonitoredResourceDescriptorsRequest.newBuilder(payload)\n" - + " .setPageToken(token)\n" - + " .build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListMonitoredResourceDescriptorsRequest injectPageSize(\n" - + " ListMonitoredResourceDescriptorsRequest payload, int pageSize) {\n" - + " return ListMonitoredResourceDescriptorsRequest.newBuilder(payload)\n" - + " .setPageSize(pageSize)\n" - + " .build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Integer extractPageSize(ListMonitoredResourceDescriptorsRequest" - + " payload) {\n" - + " return payload.getPageSize();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String extractNextToken(ListMonitoredResourceDescriptorsResponse" - + " payload) {\n" - + " return payload.getNextPageToken();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Iterable extractResources(\n" - + " ListMonitoredResourceDescriptorsResponse payload) {\n" - + " return Objects.equals(payload.getResponsesList(), null)\n" - + " ? ImmutableList.of()\n" - + " : payload.getResponsesList();\n" - + " }\n" - + " };\n" - + " private static final PagedListDescriptor\n" - + " LIST_LOGS_PAGE_STR_DESC =\n" - + " new PagedListDescriptor() {\n" - + " @Override\n" - + " public String emptyToken() {\n" - + " return \"\";\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListLogsRequest injectToken(ListLogsRequest payload, String token)" - + " {\n" - + " return" - + " ListLogsRequest.newBuilder(payload).setPageToken(token).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListLogsRequest injectPageSize(ListLogsRequest payload, int" - + " pageSize) {\n" - + " return" - + " ListLogsRequest.newBuilder(payload).setPageSize(pageSize).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Integer extractPageSize(ListLogsRequest payload) {\n" - + " return payload.getPageSize();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String extractNextToken(ListLogsResponse payload) {\n" - + " return payload.getNextPageToken();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Iterable extractResources(ListLogsResponse payload) {\n" - + " return Objects.equals(payload.getResponsesList(), null)\n" - + " ? ImmutableList.of()\n" - + " : payload.getResponsesList();\n" - + " }\n" - + " };\n" - + " private static final PagedListResponseFactory<\n" - + " ListLogEntriesRequest, ListLogEntriesResponse," - + " ListLogEntriesPagedResponse>\n" - + " LIST_LOG_ENTRIES_PAGE_STR_FACT =\n" - + " new PagedListResponseFactory<\n" - + " ListLogEntriesRequest, ListLogEntriesResponse," - + " ListLogEntriesPagedResponse>() {\n" - + " @Override\n" - + " public ApiFuture getFuturePagedResponse(\n" - + " UnaryCallable" - + " callable,\n" - + " ListLogEntriesRequest request,\n" - + " ApiCallContext context,\n" - + " ApiFuture futureResponse) {\n" - + " PageContext" - + " pageContext =\n" - + " PageContext.create(callable, LIST_LOG_ENTRIES_PAGE_STR_DESC," - + " request, context);\n" - + " return ListLogEntriesPagedResponse.createAsync(pageContext," - + " futureResponse);\n" - + " }\n" - + " };\n" - + " private static final PagedListResponseFactory<\n" - + " ListMonitoredResourceDescriptorsRequest,\n" - + " ListMonitoredResourceDescriptorsResponse,\n" - + " ListMonitoredResourceDescriptorsPagedResponse>\n" - + " LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_FACT =\n" - + " new PagedListResponseFactory<\n" - + " ListMonitoredResourceDescriptorsRequest,\n" - + " ListMonitoredResourceDescriptorsResponse,\n" - + " ListMonitoredResourceDescriptorsPagedResponse>() {\n" - + " @Override\n" - + " public ApiFuture" - + " getFuturePagedResponse(\n" - + " UnaryCallable<\n" - + " ListMonitoredResourceDescriptorsRequest,\n" - + " ListMonitoredResourceDescriptorsResponse>\n" - + " callable,\n" - + " ListMonitoredResourceDescriptorsRequest request,\n" - + " ApiCallContext context,\n" - + " ApiFuture futureResponse)" - + " {\n" - + " PageContext<\n" - + " ListMonitoredResourceDescriptorsRequest,\n" - + " ListMonitoredResourceDescriptorsResponse,\n" - + " MonitoredResourceDescriptor>\n" - + " pageContext =\n" - + " PageContext.create(\n" - + " callable,\n" - + " LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC,\n" - + " request,\n" - + " context);\n" - + " return ListMonitoredResourceDescriptorsPagedResponse.createAsync(\n" - + " pageContext, futureResponse);\n" - + " }\n" - + " };\n" - + " private static final PagedListResponseFactory<\n" - + " ListLogsRequest, ListLogsResponse, ListLogsPagedResponse>\n" - + " LIST_LOGS_PAGE_STR_FACT =\n" - + " new PagedListResponseFactory() {\n" - + " @Override\n" - + " public ApiFuture getFuturePagedResponse(\n" - + " UnaryCallable callable,\n" - + " ListLogsRequest request,\n" - + " ApiCallContext context,\n" - + " ApiFuture futureResponse) {\n" - + " PageContext pageContext =\n" - + " PageContext.create(callable, LIST_LOGS_PAGE_STR_DESC, request," - + " context);\n" - + " return ListLogsPagedResponse.createAsync(pageContext," - + " futureResponse);\n" - + " }\n" - + " };\n" - + " private static final BatchingDescriptor\n" - + " WRITE_LOG_ENTRIES_BATCHING_DESC =\n" - + " new BatchingDescriptor()" - + " {\n" - + " @Override\n" - + " public PartitionKey getBatchPartitionKey(WriteLogEntriesRequest request)" - + " {\n" - + " return new PartitionKey(\n" - + " request.getLogName(), request.getResource()," - + " request.getLabels());\n" - + " }\n" - + "\n" - + " @Override\n" - + " public RequestBuilder getRequestBuilder() {\n" - + " return new RequestBuilder() {\n" - + " private RequestBuilder builder;\n" - + "\n" - + " @Override\n" - + " public void appendRequest(WriteLogEntriesRequest request) {\n" - + " if (Objects.isNull(builder)) {\n" - + " builder = request.toBuilder();\n" - + " } else {\n" - + " builder.addAllEntries(request.getEntriesList());\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public WriteLogEntriesRequest build() {\n" - + " return builder.build();\n" - + " }\n" - + " };\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void splitResponse(\n" - + " WriteLogEntriesResponse batchResponse,\n" - + " Collection>" - + " batch) {\n" - + " for (BatchedRequestIssuer responder : batch)" - + " {\n" - + " WriteLogEntriesResponse response =" - + " WriteLogEntriesResponse.newBuilder().build();\n" - + " responder.setResponse(response);\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void splitException(\n" - + " Throwable throwable,\n" - + " Collection>" - + " batch) {\n" - + " for (BatchedRequestIssuer responder : batch)" - + " {\n" - + " responder.setException(throwable);\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public long countElements(WriteLogEntriesRequest request) {\n" - + " return request.getEntriesCount();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public long countBytes(WriteLogEntriesRequest request) {\n" - + " return request.getSerializedSize();\n" - + " }\n" - + " };\n" - + "\n" - + " /** Returns the object with the settings used for calls to deleteLog. */\n" - + " public UnaryCallSettings deleteLogSettings() {\n" - + " return deleteLogSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to writeLogEntries. */\n" - + " public BatchingCallSettings\n" - + " writeLogEntriesSettings() {\n" - + " return writeLogEntriesSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to listLogEntries. */\n" - + " public PagedCallSettings<\n" - + " ListLogEntriesRequest, ListLogEntriesResponse," - + " ListLogEntriesPagedResponse>\n" - + " listLogEntriesSettings() {\n" - + " return listLogEntriesSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to" - + " listMonitoredResourceDescriptors. */\n" - + " public PagedCallSettings<\n" - + " ListMonitoredResourceDescriptorsRequest,\n" - + " ListMonitoredResourceDescriptorsResponse,\n" - + " ListMonitoredResourceDescriptorsPagedResponse>\n" - + " listMonitoredResourceDescriptorsSettings() {\n" - + " return listMonitoredResourceDescriptorsSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to listLogs. */\n" - + " public PagedCallSettings\n" - + " listLogsSettings() {\n" - + " return listLogsSettings;\n" - + " }\n" - + "\n" - + " @BetaApi(\"A restructuring of stub classes is planned, so this may break in the" - + " future\")\n" - + " public LoggingServiceV2Stub createStub() throws IOException {\n" - + " if (getTransportChannelProvider()\n" - + " .getTransportName()\n" - + " .equals(GrpcTransportChannel.getGrpcTransportName())) {\n" - + " return GrpcLoggingServiceV2Stub.create(this);\n" - + " }\n" - + " throw new UnsupportedOperationException(\n" - + " String.format(\n" - + " \"Transport not supported: %s\"," - + " getTransportChannelProvider().getTransportName()));\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default ExecutorProvider for this service. */\n" - + " public static InstantiatingExecutorProvider.Builder" - + " defaultExecutorProviderBuilder() {\n" - + " return InstantiatingExecutorProvider.newBuilder();\n" - + " }\n" - + "\n" - + " /** Returns the default service endpoint. */\n" - + " public static String getDefaultEndpoint() {\n" - + " return \"logging.googleapis.com:443\";\n" - + " }\n" - + "\n" - + " /** Returns the default service scopes. */\n" - + " public static List getDefaultServiceScopes() {\n" - + " return DEFAULT_SERVICE_SCOPES;\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default credentials for this service. */\n" - + " public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder()" - + " {\n" - + " return" - + " GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES);\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default ChannelProvider for this service. */\n" - + " public static InstantiatingGrpcChannelProvider.Builder" - + " defaultGrpcTransportProviderBuilder() {\n" - + " return InstantiatingGrpcChannelProvider.newBuilder()\n" - + " .setMaxInboundMessageSize(Integer.MAX_VALUE);\n" - + " }\n" - + "\n" - + " public static TransportChannelProvider defaultTransportChannelProvider() {\n" - + " return defaultGrpcTransportProviderBuilder().build();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The surface for customizing headers is not stable yet and may change in" - + " the future.\")\n" - + " public static ApiClientHeaderProvider.Builder" - + " defaultApiClientHeaderProviderBuilder() {\n" - + " return ApiClientHeaderProvider.newBuilder()\n" - + " .setGeneratedLibToken(\n" - + " \"gapic\"," - + " GaxProperties.getLibraryVersion(LoggingServiceV2StubSettings.class))\n" - + " .setTransportToken(\n" - + " GaxGrpcProperties.getGrpcTokenName()," - + " GaxGrpcProperties.getGrpcVersion());\n" - + " }\n" - + "\n" - + " /** Returns a new builder for this class. */\n" - + " public static Builder newBuilder() {\n" - + " return Builder.createDefault();\n" - + " }\n" - + "\n" - + " /** Returns a new builder for this class. */\n" - + " public static Builder newBuilder(ClientContext clientContext) {\n" - + " return new Builder(clientContext);\n" - + " }\n" - + "\n" - + " /** Returns a builder containing all the values of this settings class. */\n" - + " public Builder toBuilder() {\n" - + " return new Builder(this);\n" - + " }\n" - + "\n" - + " protected LoggingServiceV2StubSettings(Builder settingsBuilder) throws IOException" - + " {\n" - + " super(settingsBuilder);\n" - + " deleteLogSettings = settingsBuilder.deleteLogSettings().build();\n" - + " writeLogEntriesSettings = settingsBuilder.writeLogEntriesSettings().build();\n" - + " listLogEntriesSettings = settingsBuilder.listLogEntriesSettings().build();\n" - + " listMonitoredResourceDescriptorsSettings =\n" - + " settingsBuilder.listMonitoredResourceDescriptorsSettings().build();\n" - + " listLogsSettings = settingsBuilder.listLogsSettings().build();\n" - + " }\n" - + "\n" - + " /** Builder for LoggingServiceV2StubSettings. */\n" - + " public static class Builder extends StubSettings.Builder {\n" - + " private final ImmutableList>" - + " unaryMethodSettingsBuilders;\n" - + " private final UnaryCallSettings.Builder" - + " deleteLogSettings;\n" - + " private final BatchingCallSettings.Builder\n" - + " writeLogEntriesSettings;\n" - + " private final PagedCallSettings.Builder<\n" - + " ListLogEntriesRequest, ListLogEntriesResponse," - + " ListLogEntriesPagedResponse>\n" - + " listLogEntriesSettings;\n" - + " private final PagedCallSettings.Builder<\n" - + " ListMonitoredResourceDescriptorsRequest,\n" - + " ListMonitoredResourceDescriptorsResponse,\n" - + " ListMonitoredResourceDescriptorsPagedResponse>\n" - + " listMonitoredResourceDescriptorsSettings;\n" - + " private final PagedCallSettings.Builder<\n" - + " ListLogsRequest, ListLogsResponse, ListLogsPagedResponse>\n" - + " listLogsSettings;\n" - + " private static final ImmutableMap>\n" - + " RETRYABLE_CODE_DEFINITIONS;\n" - + "\n" - + " static {\n" - + " ImmutableMap.Builder> definitions =\n" - + " ImmutableMap.builder();\n" - + " definitions.put(\n" - + " \"retry_policy_1_codes\",\n" - + " ImmutableSet.copyOf(\n" - + " Lists.newArrayList(\n" - + " StatusCode.Code.DEADLINE_EXCEEDED,\n" - + " StatusCode.Code.INTERNAL,\n" - + " StatusCode.Code.UNAVAILABLE)));\n" - + " RETRYABLE_CODE_DEFINITIONS = definitions.build();\n" - + " }\n" - + "\n" - + " private static final ImmutableMap" - + " RETRY_PARAM_DEFINITIONS;\n" - + "\n" - + " static {\n" - + " ImmutableMap.Builder definitions =" - + " ImmutableMap.builder();\n" - + " RetrySettings settings = null;\n" - + " settings =\n" - + " RetrySettings.newBuilder()\n" - + " .setInitialRetryDelay(Duration.ofMillis(100L))\n" - + " .setRetryDelayMultiplier(1.3)\n" - + " .setMaxRetryDelay(Duration.ofMillis(60000L))\n" - + " .setInitialRpcTimeout(Duration.ofMillis(60000L))\n" - + " .setRpcTimeoutMultiplier(1.0)\n" - + " .setMaxRpcTimeout(Duration.ofMillis(60000L))\n" - + " .setTotalTimeout(Duration.ofMillis(60000L))\n" - + " .build();\n" - + " definitions.put(\"retry_policy_1_params\", settings);\n" - + " RETRY_PARAM_DEFINITIONS = definitions.build();\n" - + " }\n" - + "\n" - + " protected Builder() {\n" - + " this(((ClientContext) null));\n" - + " }\n" - + "\n" - + " protected Builder(ClientContext clientContext) {\n" - + " super(clientContext);\n" - + " deleteLogSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();\n" - + " writeLogEntriesSettings =\n" - + " BatchingCallSettings.newBuilder(WRITE_LOG_ENTRIES_BATCHING_DESC)\n" - + " .setBatchingSettings(BatchingSettings.newBuilder().build());\n" - + " listLogEntriesSettings =" - + " PagedCallSettings.newBuilder(LIST_LOG_ENTRIES_PAGE_STR_FACT);\n" - + " listMonitoredResourceDescriptorsSettings =\n" - + " " - + " PagedCallSettings.newBuilder(LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_FACT);\n" - + " listLogsSettings = PagedCallSettings.newBuilder(LIST_LOGS_PAGE_STR_FACT);\n" - + " unaryMethodSettingsBuilders =\n" - + " ImmutableList.>of(\n" - + " deleteLogSettings,\n" - + " writeLogEntriesSettings,\n" - + " listLogEntriesSettings,\n" - + " listMonitoredResourceDescriptorsSettings,\n" - + " listLogsSettings);\n" - + " initDefaults(this);\n" - + " }\n" - + "\n" - + " protected Builder(LoggingServiceV2StubSettings settings) {\n" - + " super(settings);\n" - + " deleteLogSettings = settings.deleteLogSettings.toBuilder();\n" - + " writeLogEntriesSettings = settings.writeLogEntriesSettings.toBuilder();\n" - + " listLogEntriesSettings = settings.listLogEntriesSettings.toBuilder();\n" - + " listMonitoredResourceDescriptorsSettings =\n" - + " settings.listMonitoredResourceDescriptorsSettings.toBuilder();\n" - + " listLogsSettings = settings.listLogsSettings.toBuilder();\n" - + " unaryMethodSettingsBuilders =\n" - + " ImmutableList.>of(\n" - + " deleteLogSettings,\n" - + " writeLogEntriesSettings,\n" - + " listLogEntriesSettings,\n" - + " listMonitoredResourceDescriptorsSettings,\n" - + " listLogsSettings);\n" - + " }\n" - + "\n" - + " private static Builder createDefault() {\n" - + " Builder builder = new Builder(((ClientContext) null));\n" - + " builder.setTransportChannelProvider(defaultTransportChannelProvider());\n" - + " builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());\n" - + " " - + " builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());\n" - + " builder.setEndpoint(getDefaultEndpoint());\n" - + " return initDefaults(builder);\n" - + " }\n" - + "\n" - + " private static Builder initDefaults(Builder builder) {\n" - + " builder\n" - + " .deleteLogSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"));\n" - + " builder\n" - + " .writeLogEntriesSettings()\n" - + " .setBatchingSettings(\n" - + " BatchingSettings.newBuilder()\n" - + " .setElementCountThreshold(1000L)\n" - + " .setRequestByteThreshold(1048576L)\n" - + " .setDelayThreshold(Duration.ofMillis(50L))\n" - + " .setFlowControlSettings(\n" - + " FlowControlSettings.newBuilder()\n" - + " .setMaxOutstandingElementCount(100000L)\n" - + " .setMaxOutstandingRequestBytes(10485760L)\n" - + " .setLimitExceededBehavior(\n" - + " FlowController.LimitExceededBehavior.ThrowException)\n" - + " .build())\n" - + " .build());\n" - + " builder\n" - + " .writeLogEntriesSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"));\n" - + " builder\n" - + " .listLogEntriesSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"));\n" - + " builder\n" - + " .listMonitoredResourceDescriptorsSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"));\n" - + " builder\n" - + " .listLogsSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"));\n" - + " return builder;\n" - + " }\n" - + "\n" - + " // NEXT_MAJOR_VER: remove 'throws Exception'.\n" - + " /**\n" - + " * Applies the given settings updater function to all of the unary API methods in" - + " this service.\n" - + " *\n" - + " *

Note: This method does not support applying settings to streaming" - + " methods.\n" - + " */\n" - + " public Builder applyToAllUnaryMethods(\n" - + " ApiFunction, Void> settingsUpdater) throws" - + " Exception {\n" - + " super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);\n" - + " return this;\n" - + " }\n" - + "\n" - + " public ImmutableList>" - + " unaryMethodSettingsBuilders() {\n" - + " return unaryMethodSettingsBuilders;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to deleteLog. */\n" - + " public UnaryCallSettings.Builder deleteLogSettings() {\n" - + " return deleteLogSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to writeLogEntries. */\n" - + " public BatchingCallSettings.Builder\n" - + " writeLogEntriesSettings() {\n" - + " return writeLogEntriesSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to listLogEntries. */\n" - + " public PagedCallSettings.Builder<\n" - + " ListLogEntriesRequest, ListLogEntriesResponse," - + " ListLogEntriesPagedResponse>\n" - + " listLogEntriesSettings() {\n" - + " return listLogEntriesSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to" - + " listMonitoredResourceDescriptors. */\n" - + " public PagedCallSettings.Builder<\n" - + " ListMonitoredResourceDescriptorsRequest,\n" - + " ListMonitoredResourceDescriptorsResponse,\n" - + " ListMonitoredResourceDescriptorsPagedResponse>\n" - + " listMonitoredResourceDescriptorsSettings() {\n" - + " return listMonitoredResourceDescriptorsSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to listLogs. */\n" - + " public PagedCallSettings.Builder\n" - + " listLogsSettings() {\n" - + " return listLogsSettings;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public LoggingServiceV2StubSettings build() throws IOException {\n" - + " return new LoggingServiceV2StubSettings(this);\n" - + " }\n" - + " }\n" - + "}\n"; - - private static final String EXPECTED_PUBLISHER_STUB_SETTINGS_STRING = - "package com.google.pubsub.v1.stub;\n" - + "\n" - + "import static com.google.pubsub.v1.PublisherClient.ListTopicSnapshotsPagedResponse;\n" - + "import static" - + " com.google.pubsub.v1.PublisherClient.ListTopicSubscriptionsPagedResponse;\n" - + "import static com.google.pubsub.v1.PublisherClient.ListTopicsPagedResponse;\n" - + "\n" - + "import com.google.api.core.ApiFunction;\n" - + "import com.google.api.core.ApiFuture;\n" - + "import com.google.api.core.BetaApi;\n" - + "import com.google.api.gax.batching.BatchingSettings;\n" - + "import com.google.api.gax.batching.FlowControlSettings;\n" - + "import com.google.api.gax.batching.FlowController;\n" - + "import com.google.api.gax.batching.PartitionKey;\n" - + "import com.google.api.gax.batching.RequestBuilder;\n" - + "import com.google.api.gax.core.GaxProperties;\n" - + "import com.google.api.gax.core.GoogleCredentialsProvider;\n" - + "import com.google.api.gax.core.InstantiatingExecutorProvider;\n" - + "import com.google.api.gax.grpc.GaxGrpcProperties;\n" - + "import com.google.api.gax.grpc.GrpcTransportChannel;\n" - + "import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;\n" - + "import com.google.api.gax.retrying.RetrySettings;\n" - + "import com.google.api.gax.rpc.ApiCallContext;\n" - + "import com.google.api.gax.rpc.ApiClientHeaderProvider;\n" - + "import com.google.api.gax.rpc.BatchedRequestIssuer;\n" - + "import com.google.api.gax.rpc.BatchingCallSettings;\n" - + "import com.google.api.gax.rpc.BatchingDescriptor;\n" - + "import com.google.api.gax.rpc.ClientContext;\n" - + "import com.google.api.gax.rpc.PageContext;\n" - + "import com.google.api.gax.rpc.PagedCallSettings;\n" - + "import com.google.api.gax.rpc.PagedListDescriptor;\n" - + "import com.google.api.gax.rpc.PagedListResponseFactory;\n" - + "import com.google.api.gax.rpc.StatusCode;\n" - + "import com.google.api.gax.rpc.StubSettings;\n" - + "import com.google.api.gax.rpc.TransportChannelProvider;\n" - + "import com.google.api.gax.rpc.UnaryCallSettings;\n" - + "import com.google.api.gax.rpc.UnaryCallable;\n" - + "import com.google.common.collect.ImmutableList;\n" - + "import com.google.common.collect.ImmutableMap;\n" - + "import com.google.common.collect.ImmutableSet;\n" - + "import com.google.common.collect.Lists;\n" - + "import com.google.protobuf.Empty;\n" - + "import com.google.pubsub.v1.DeleteTopicRequest;\n" - + "import com.google.pubsub.v1.DetachSubscriptionRequest;\n" - + "import com.google.pubsub.v1.DetachSubscriptionResponse;\n" - + "import com.google.pubsub.v1.GetTopicRequest;\n" - + "import com.google.pubsub.v1.ListTopicSnapshotsRequest;\n" - + "import com.google.pubsub.v1.ListTopicSnapshotsResponse;\n" - + "import com.google.pubsub.v1.ListTopicSubscriptionsRequest;\n" - + "import com.google.pubsub.v1.ListTopicSubscriptionsResponse;\n" - + "import com.google.pubsub.v1.ListTopicsRequest;\n" - + "import com.google.pubsub.v1.ListTopicsResponse;\n" - + "import com.google.pubsub.v1.PublishRequest;\n" - + "import com.google.pubsub.v1.PublishResponse;\n" - + "import com.google.pubsub.v1.Topic;\n" - + "import com.google.pubsub.v1.UpdateTopicRequest;\n" - + "import java.io.IOException;\n" - + "import java.util.ArrayList;\n" - + "import java.util.Collection;\n" - + "import java.util.List;\n" - + "import java.util.Objects;\n" - + "import javax.annotation.Generated;\n" - + "import org.threeten.bp.Duration;\n" - + "\n" - + "// AUTO-GENERATED DOCUMENTATION AND CLASS.\n" - + "/**\n" - + " * Settings class to configure an instance of {@link PublisherStub}.\n" - + " *\n" - + " *

The default instance has everything set to sensible defaults:\n" - + " *\n" - + " *

    \n" - + " *
  • The default service address (pubsub.googleapis.com) and default port (443)" - + " are used.\n" - + " *
  • Credentials are acquired automatically through Application Default" - + " Credentials.\n" - + " *
  • Retries are configured for idempotent methods but not for non-idempotent" - + " methods.\n" - + " *
\n" - + " *\n" - + " *

The builder of this class is recursive, so contained classes are themselves" - + " builders. When\n" - + " * build() is called, the tree of builders is called to create the complete settings" - + " object.\n" - + " *\n" - + " *

For example, to set the total timeout of createTopic to 30 seconds:\n" - + " */\n" - + "@BetaApi\n" - + "@Generated(\"by gapic-generator-java\")\n" - + "public class PublisherStubSettings extends StubSettings {\n" - + " /** The default scopes of the service. */\n" - + " private static final ImmutableList DEFAULT_SERVICE_SCOPES =\n" - + " ImmutableList.builder()\n" - + " .add(\"https://www.googleapis.com/auth/cloud-platform\")\n" - + " .add(\"https://www.googleapis.com/auth/pubsub\")\n" - + " .build();\n" - + "\n" - + " private final UnaryCallSettings createTopicSettings;\n" - + " private final UnaryCallSettings updateTopicSettings;\n" - + " private final BatchingCallSettings" - + " publishSettings;\n" - + " private final UnaryCallSettings getTopicSettings;\n" - + " private final PagedCallSettings\n" - + " listTopicsSettings;\n" - + " private final PagedCallSettings<\n" - + " ListTopicSubscriptionsRequest,\n" - + " ListTopicSubscriptionsResponse,\n" - + " ListTopicSubscriptionsPagedResponse>\n" - + " listTopicSubscriptionsSettings;\n" - + " private final PagedCallSettings<\n" - + " ListTopicSnapshotsRequest, ListTopicSnapshotsResponse," - + " ListTopicSnapshotsPagedResponse>\n" - + " listTopicSnapshotsSettings;\n" - + " private final UnaryCallSettings deleteTopicSettings;\n" - + " private final UnaryCallSettings\n" - + " detachSubscriptionSettings;\n" - + " private static final PagedListDescriptor\n" - + " LIST_TOPICS_PAGE_STR_DESC =\n" - + " new PagedListDescriptor() {\n" - + " @Override\n" - + " public String emptyToken() {\n" - + " return \"\";\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListTopicsRequest injectToken(ListTopicsRequest payload, String" - + " token) {\n" - + " return" - + " ListTopicsRequest.newBuilder(payload).setPageToken(token).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListTopicsRequest injectPageSize(ListTopicsRequest payload, int" - + " pageSize) {\n" - + " return" - + " ListTopicsRequest.newBuilder(payload).setPageSize(pageSize).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Integer extractPageSize(ListTopicsRequest payload) {\n" - + " return payload.getPageSize();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String extractNextToken(ListTopicsResponse payload) {\n" - + " return payload.getNextPageToken();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Iterable extractResources(ListTopicsResponse payload) {\n" - + " return Objects.equals(payload.getResponsesList(), null)\n" - + " ? ImmutableList.of()\n" - + " : payload.getResponsesList();\n" - + " }\n" - + " };\n" - + " private static final PagedListDescriptor<\n" - + " ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String>\n" - + " LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_DESC =\n" - + " new PagedListDescriptor<\n" - + " ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse," - + " String>() {\n" - + " @Override\n" - + " public String emptyToken() {\n" - + " return \"\";\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListTopicSubscriptionsRequest injectToken(\n" - + " ListTopicSubscriptionsRequest payload, String token) {\n" - + " return" - + " ListTopicSubscriptionsRequest.newBuilder(payload).setPageToken(token).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListTopicSubscriptionsRequest injectPageSize(\n" - + " ListTopicSubscriptionsRequest payload, int pageSize) {\n" - + " return ListTopicSubscriptionsRequest.newBuilder(payload)\n" - + " .setPageSize(pageSize)\n" - + " .build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Integer extractPageSize(ListTopicSubscriptionsRequest payload) {\n" - + " return payload.getPageSize();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String extractNextToken(ListTopicSubscriptionsResponse payload)" - + " {\n" - + " return payload.getNextPageToken();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Iterable extractResources(ListTopicSubscriptionsResponse" - + " payload) {\n" - + " return Objects.equals(payload.getResponsesList(), null)\n" - + " ? ImmutableList.of()\n" - + " : payload.getResponsesList();\n" - + " }\n" - + " };\n" - + " private static final PagedListDescriptor<\n" - + " ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, String>\n" - + " LIST_TOPIC_SNAPSHOTS_PAGE_STR_DESC =\n" - + " new PagedListDescriptor() {\n" - + " @Override\n" - + " public String emptyToken() {\n" - + " return \"\";\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListTopicSnapshotsRequest injectToken(\n" - + " ListTopicSnapshotsRequest payload, String token) {\n" - + " return" - + " ListTopicSnapshotsRequest.newBuilder(payload).setPageToken(token).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public ListTopicSnapshotsRequest injectPageSize(\n" - + " ListTopicSnapshotsRequest payload, int pageSize) {\n" - + " return" - + " ListTopicSnapshotsRequest.newBuilder(payload).setPageSize(pageSize).build();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Integer extractPageSize(ListTopicSnapshotsRequest payload) {\n" - + " return payload.getPageSize();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public String extractNextToken(ListTopicSnapshotsResponse payload) {\n" - + " return payload.getNextPageToken();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public Iterable extractResources(ListTopicSnapshotsResponse" - + " payload) {\n" - + " return Objects.equals(payload.getResponsesList(), null)\n" - + " ? ImmutableList.of()\n" - + " : payload.getResponsesList();\n" - + " }\n" - + " };\n" - + " private static final PagedListResponseFactory<\n" - + " ListTopicsRequest, ListTopicsResponse, ListTopicsPagedResponse>\n" - + " LIST_TOPICS_PAGE_STR_FACT =\n" - + " new PagedListResponseFactory<\n" - + " ListTopicsRequest, ListTopicsResponse, ListTopicsPagedResponse>() {\n" - + " @Override\n" - + " public ApiFuture getFuturePagedResponse(\n" - + " UnaryCallable callable,\n" - + " ListTopicsRequest request,\n" - + " ApiCallContext context,\n" - + " ApiFuture futureResponse) {\n" - + " PageContext pageContext" - + " =\n" - + " PageContext.create(callable, LIST_TOPICS_PAGE_STR_DESC, request," - + " context);\n" - + " return ListTopicsPagedResponse.createAsync(pageContext," - + " futureResponse);\n" - + " }\n" - + " };\n" - + " private static final PagedListResponseFactory<\n" - + " ListTopicSubscriptionsRequest,\n" - + " ListTopicSubscriptionsResponse,\n" - + " ListTopicSubscriptionsPagedResponse>\n" - + " LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_FACT =\n" - + " new PagedListResponseFactory<\n" - + " ListTopicSubscriptionsRequest,\n" - + " ListTopicSubscriptionsResponse,\n" - + " ListTopicSubscriptionsPagedResponse>() {\n" - + " @Override\n" - + " public ApiFuture" - + " getFuturePagedResponse(\n" - + " UnaryCallable\n" - + " callable,\n" - + " ListTopicSubscriptionsRequest request,\n" - + " ApiCallContext context,\n" - + " ApiFuture futureResponse) {\n" - + " PageContext\n" - + " pageContext =\n" - + " PageContext.create(\n" - + " callable, LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_DESC, request," - + " context);\n" - + " return ListTopicSubscriptionsPagedResponse.createAsync(pageContext," - + " futureResponse);\n" - + " }\n" - + " };\n" - + " private static final PagedListResponseFactory<\n" - + " ListTopicSnapshotsRequest, ListTopicSnapshotsResponse," - + " ListTopicSnapshotsPagedResponse>\n" - + " LIST_TOPIC_SNAPSHOTS_PAGE_STR_FACT =\n" - + " new PagedListResponseFactory<\n" - + " ListTopicSnapshotsRequest,\n" - + " ListTopicSnapshotsResponse,\n" - + " ListTopicSnapshotsPagedResponse>() {\n" - + " @Override\n" - + " public ApiFuture" - + " getFuturePagedResponse(\n" - + " UnaryCallable" - + " callable,\n" - + " ListTopicSnapshotsRequest request,\n" - + " ApiCallContext context,\n" - + " ApiFuture futureResponse) {\n" - + " PageContext\n" - + " pageContext =\n" - + " PageContext.create(\n" - + " callable, LIST_TOPIC_SNAPSHOTS_PAGE_STR_DESC, request," - + " context);\n" - + " return ListTopicSnapshotsPagedResponse.createAsync(pageContext," - + " futureResponse);\n" - + " }\n" - + " };\n" - + " private static final BatchingDescriptor" - + " PUBLISH_BATCHING_DESC =\n" - + " new BatchingDescriptor() {\n" - + " @Override\n" - + " public PartitionKey getBatchPartitionKey(PublishRequest request) {\n" - + " return new PartitionKey(request.getTopic());\n" - + " }\n" - + "\n" - + " @Override\n" - + " public RequestBuilder getRequestBuilder() {\n" - + " return new RequestBuilder() {\n" - + " private RequestBuilder builder;\n" - + "\n" - + " @Override\n" - + " public void appendRequest(PublishRequest request) {\n" - + " if (Objects.isNull(builder)) {\n" - + " builder = request.toBuilder();\n" - + " } else {\n" - + " builder.addAllMessages(request.getMessagesList());\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public PublishRequest build() {\n" - + " return builder.build();\n" - + " }\n" - + " };\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void splitResponse(\n" - + " PublishResponse batchResponse,\n" - + " Collection> batch) {\n" - + " int batchMessageIndex = 0;\n" - + " for (BatchedRequestIssuer responder : batch) {\n" - + " List subresponseElements = new ArrayList<>();\n" - + " long subresponseCount = responder.getMessageCount();\n" - + " for (int i = 0; i < subresponseCount; i++) {\n" - + " " - + " subresponseElements.add(batchResponse.getMessageIds(batchMessageIndex));\n" - + " }\n" - + " PublishResponse response =\n" - + " " - + " PublishResponse.newBuilder().addAllMessageIds(subresponseElements).build();\n" - + " responder.setResponse(response);\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void splitException(\n" - + " Throwable throwable,\n" - + " Collection> batch) {\n" - + " for (BatchedRequestIssuer responder : batch) {\n" - + " responder.setException(throwable);\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public long countElements(PublishRequest request) {\n" - + " return request.getMessagesCount();\n" - + " }\n" - + "\n" - + " @Override\n" - + " public long countBytes(PublishRequest request) {\n" - + " return request.getSerializedSize();\n" - + " }\n" - + " };\n" - + "\n" - + " /** Returns the object with the settings used for calls to createTopic. */\n" - + " public UnaryCallSettings createTopicSettings() {\n" - + " return createTopicSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to updateTopic. */\n" - + " public UnaryCallSettings updateTopicSettings() {\n" - + " return updateTopicSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to publish. */\n" - + " public BatchingCallSettings publishSettings() {\n" - + " return publishSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to getTopic. */\n" - + " public UnaryCallSettings getTopicSettings() {\n" - + " return getTopicSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to listTopics. */\n" - + " public PagedCallSettings\n" - + " listTopicsSettings() {\n" - + " return listTopicsSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to listTopicSubscriptions." - + " */\n" - + " public PagedCallSettings<\n" - + " ListTopicSubscriptionsRequest,\n" - + " ListTopicSubscriptionsResponse,\n" - + " ListTopicSubscriptionsPagedResponse>\n" - + " listTopicSubscriptionsSettings() {\n" - + " return listTopicSubscriptionsSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to listTopicSnapshots. */\n" - + " public PagedCallSettings<\n" - + " ListTopicSnapshotsRequest, ListTopicSnapshotsResponse," - + " ListTopicSnapshotsPagedResponse>\n" - + " listTopicSnapshotsSettings() {\n" - + " return listTopicSnapshotsSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to deleteTopic. */\n" - + " public UnaryCallSettings deleteTopicSettings() {\n" - + " return deleteTopicSettings;\n" - + " }\n" - + "\n" - + " /** Returns the object with the settings used for calls to detachSubscription. */\n" - + " public UnaryCallSettings\n" - + " detachSubscriptionSettings() {\n" - + " return detachSubscriptionSettings;\n" - + " }\n" - + "\n" - + " @BetaApi(\"A restructuring of stub classes is planned, so this may break in the" - + " future\")\n" - + " public PublisherStub createStub() throws IOException {\n" - + " if (getTransportChannelProvider()\n" - + " .getTransportName()\n" - + " .equals(GrpcTransportChannel.getGrpcTransportName())) {\n" - + " return GrpcPublisherStub.create(this);\n" - + " }\n" - + " throw new UnsupportedOperationException(\n" - + " String.format(\n" - + " \"Transport not supported: %s\"," - + " getTransportChannelProvider().getTransportName()));\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default ExecutorProvider for this service. */\n" - + " public static InstantiatingExecutorProvider.Builder" - + " defaultExecutorProviderBuilder() {\n" - + " return InstantiatingExecutorProvider.newBuilder();\n" - + " }\n" - + "\n" - + " /** Returns the default service endpoint. */\n" - + " public static String getDefaultEndpoint() {\n" - + " return \"pubsub.googleapis.com:443\";\n" - + " }\n" - + "\n" - + " /** Returns the default service scopes. */\n" - + " public static List getDefaultServiceScopes() {\n" - + " return DEFAULT_SERVICE_SCOPES;\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default credentials for this service. */\n" - + " public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder()" - + " {\n" - + " return" - + " GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES);\n" - + " }\n" - + "\n" - + " /** Returns a builder for the default ChannelProvider for this service. */\n" - + " public static InstantiatingGrpcChannelProvider.Builder" - + " defaultGrpcTransportProviderBuilder() {\n" - + " return InstantiatingGrpcChannelProvider.newBuilder()\n" - + " .setMaxInboundMessageSize(Integer.MAX_VALUE);\n" - + " }\n" - + "\n" - + " public static TransportChannelProvider defaultTransportChannelProvider() {\n" - + " return defaultGrpcTransportProviderBuilder().build();\n" - + " }\n" - + "\n" - + " @BetaApi(\"The surface for customizing headers is not stable yet and may change in" - + " the future.\")\n" - + " public static ApiClientHeaderProvider.Builder" - + " defaultApiClientHeaderProviderBuilder() {\n" - + " return ApiClientHeaderProvider.newBuilder()\n" - + " .setGeneratedLibToken(\"gapic\"," - + " GaxProperties.getLibraryVersion(PublisherStubSettings.class))\n" - + " .setTransportToken(\n" - + " GaxGrpcProperties.getGrpcTokenName()," - + " GaxGrpcProperties.getGrpcVersion());\n" - + " }\n" - + "\n" - + " /** Returns a new builder for this class. */\n" - + " public static Builder newBuilder() {\n" - + " return Builder.createDefault();\n" - + " }\n" - + "\n" - + " /** Returns a new builder for this class. */\n" - + " public static Builder newBuilder(ClientContext clientContext) {\n" - + " return new Builder(clientContext);\n" - + " }\n" - + "\n" - + " /** Returns a builder containing all the values of this settings class. */\n" - + " public Builder toBuilder() {\n" - + " return new Builder(this);\n" - + " }\n" - + "\n" - + " protected PublisherStubSettings(Builder settingsBuilder) throws IOException {\n" - + " super(settingsBuilder);\n" - + " createTopicSettings = settingsBuilder.createTopicSettings().build();\n" - + " updateTopicSettings = settingsBuilder.updateTopicSettings().build();\n" - + " publishSettings = settingsBuilder.publishSettings().build();\n" - + " getTopicSettings = settingsBuilder.getTopicSettings().build();\n" - + " listTopicsSettings = settingsBuilder.listTopicsSettings().build();\n" - + " listTopicSubscriptionsSettings =" - + " settingsBuilder.listTopicSubscriptionsSettings().build();\n" - + " listTopicSnapshotsSettings =" - + " settingsBuilder.listTopicSnapshotsSettings().build();\n" - + " deleteTopicSettings = settingsBuilder.deleteTopicSettings().build();\n" - + " detachSubscriptionSettings =" - + " settingsBuilder.detachSubscriptionSettings().build();\n" - + " }\n" - + "\n" - + " /** Builder for PublisherStubSettings. */\n" - + " public static class Builder extends StubSettings.Builder" - + " {\n" - + " private final ImmutableList>" - + " unaryMethodSettingsBuilders;\n" - + " private final UnaryCallSettings.Builder createTopicSettings;\n" - + " private final UnaryCallSettings.Builder" - + " updateTopicSettings;\n" - + " private final BatchingCallSettings.Builder" - + " publishSettings;\n" - + " private final UnaryCallSettings.Builder" - + " getTopicSettings;\n" - + " private final PagedCallSettings.Builder<\n" - + " ListTopicsRequest, ListTopicsResponse, ListTopicsPagedResponse>\n" - + " listTopicsSettings;\n" - + " private final PagedCallSettings.Builder<\n" - + " ListTopicSubscriptionsRequest,\n" - + " ListTopicSubscriptionsResponse,\n" - + " ListTopicSubscriptionsPagedResponse>\n" - + " listTopicSubscriptionsSettings;\n" - + " private final PagedCallSettings.Builder<\n" - + " ListTopicSnapshotsRequest, ListTopicSnapshotsResponse," - + " ListTopicSnapshotsPagedResponse>\n" - + " listTopicSnapshotsSettings;\n" - + " private final UnaryCallSettings.Builder" - + " deleteTopicSettings;\n" - + " private final UnaryCallSettings.Builder\n" - + " detachSubscriptionSettings;\n" - + " private static final ImmutableMap>\n" - + " RETRYABLE_CODE_DEFINITIONS;\n" - + "\n" - + " static {\n" - + " ImmutableMap.Builder> definitions =\n" - + " ImmutableMap.builder();\n" - + " definitions.put(\n" - + " \"retry_policy_0_codes\",\n" - + " " - + " ImmutableSet.copyOf(Lists.newArrayList(StatusCode.Code.UNAVAILABLE)));\n" - + " definitions.put(\n" - + " \"retry_policy_1_codes\",\n" - + " ImmutableSet.copyOf(\n" - + " Lists.newArrayList(\n" - + " StatusCode.Code.ABORTED,\n" - + " StatusCode.Code.CANCELLED,\n" - + " StatusCode.Code.INTERNAL,\n" - + " StatusCode.Code.RESOURCE_EXHAUSTED,\n" - + " StatusCode.Code.UNKNOWN,\n" - + " StatusCode.Code.UNAVAILABLE,\n" - + " StatusCode.Code.DEADLINE_EXCEEDED)));\n" - + " definitions.put(\n" - + " \"retry_policy_2_codes\",\n" - + " ImmutableSet.copyOf(\n" - + " Lists.newArrayList(\n" - + " StatusCode.Code.UNKNOWN, StatusCode.Code.ABORTED," - + " StatusCode.Code.UNAVAILABLE)));\n" - + " RETRYABLE_CODE_DEFINITIONS = definitions.build();\n" - + " }\n" - + "\n" - + " private static final ImmutableMap" - + " RETRY_PARAM_DEFINITIONS;\n" - + "\n" - + " static {\n" - + " ImmutableMap.Builder definitions =" - + " ImmutableMap.builder();\n" - + " RetrySettings settings = null;\n" - + " settings =\n" - + " RetrySettings.newBuilder()\n" - + " .setInitialRetryDelay(Duration.ofMillis(100L))\n" - + " .setRetryDelayMultiplier(1.3)\n" - + " .setMaxRetryDelay(Duration.ofMillis(60000L))\n" - + " .setInitialRpcTimeout(Duration.ofMillis(60000L))\n" - + " .setRpcTimeoutMultiplier(1.0)\n" - + " .setMaxRpcTimeout(Duration.ofMillis(60000L))\n" - + " .setTotalTimeout(Duration.ofMillis(60000L))\n" - + " .build();\n" - + " definitions.put(\"retry_policy_0_params\", settings);\n" - + " settings =\n" - + " RetrySettings.newBuilder()\n" - + " .setInitialRetryDelay(Duration.ofMillis(100L))\n" - + " .setRetryDelayMultiplier(1.3)\n" - + " .setMaxRetryDelay(Duration.ofMillis(60000L))\n" - + " .setInitialRpcTimeout(Duration.ofMillis(60000L))\n" - + " .setRpcTimeoutMultiplier(1.0)\n" - + " .setMaxRpcTimeout(Duration.ofMillis(60000L))\n" - + " .setTotalTimeout(Duration.ofMillis(60000L))\n" - + " .build();\n" - + " definitions.put(\"retry_policy_1_params\", settings);\n" - + " settings =\n" - + " RetrySettings.newBuilder()\n" - + " .setInitialRetryDelay(Duration.ofMillis(100L))\n" - + " .setRetryDelayMultiplier(1.3)\n" - + " .setMaxRetryDelay(Duration.ofMillis(60000L))\n" - + " .setInitialRpcTimeout(Duration.ofMillis(60000L))\n" - + " .setRpcTimeoutMultiplier(1.0)\n" - + " .setMaxRpcTimeout(Duration.ofMillis(60000L))\n" - + " .setTotalTimeout(Duration.ofMillis(60000L))\n" - + " .build();\n" - + " definitions.put(\"retry_policy_2_params\", settings);\n" - + " RETRY_PARAM_DEFINITIONS = definitions.build();\n" - + " }\n" - + "\n" - + " protected Builder() {\n" - + " this(((ClientContext) null));\n" - + " }\n" - + "\n" - + " protected Builder(ClientContext clientContext) {\n" - + " super(clientContext);\n" - + " createTopicSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();\n" - + " updateTopicSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();\n" - + " publishSettings =\n" - + " BatchingCallSettings.newBuilder(PUBLISH_BATCHING_DESC)\n" - + " .setBatchingSettings(BatchingSettings.newBuilder().build());\n" - + " getTopicSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();\n" - + " listTopicsSettings = PagedCallSettings.newBuilder(LIST_TOPICS_PAGE_STR_FACT);\n" - + " listTopicSubscriptionsSettings =\n" - + " PagedCallSettings.newBuilder(LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_FACT);\n" - + " listTopicSnapshotsSettings =" - + " PagedCallSettings.newBuilder(LIST_TOPIC_SNAPSHOTS_PAGE_STR_FACT);\n" - + " deleteTopicSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();\n" - + " detachSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();\n" - + " unaryMethodSettingsBuilders =\n" - + " ImmutableList.>of(\n" - + " createTopicSettings,\n" - + " updateTopicSettings,\n" - + " publishSettings,\n" - + " getTopicSettings,\n" - + " listTopicsSettings,\n" - + " listTopicSubscriptionsSettings,\n" - + " listTopicSnapshotsSettings,\n" - + " deleteTopicSettings,\n" - + " detachSubscriptionSettings);\n" - + " initDefaults(this);\n" - + " }\n" - + "\n" - + " protected Builder(PublisherStubSettings settings) {\n" - + " super(settings);\n" - + " createTopicSettings = settings.createTopicSettings.toBuilder();\n" - + " updateTopicSettings = settings.updateTopicSettings.toBuilder();\n" - + " publishSettings = settings.publishSettings.toBuilder();\n" - + " getTopicSettings = settings.getTopicSettings.toBuilder();\n" - + " listTopicsSettings = settings.listTopicsSettings.toBuilder();\n" - + " listTopicSubscriptionsSettings =" - + " settings.listTopicSubscriptionsSettings.toBuilder();\n" - + " listTopicSnapshotsSettings = settings.listTopicSnapshotsSettings.toBuilder();\n" - + " deleteTopicSettings = settings.deleteTopicSettings.toBuilder();\n" - + " detachSubscriptionSettings = settings.detachSubscriptionSettings.toBuilder();\n" - + " unaryMethodSettingsBuilders =\n" - + " ImmutableList.>of(\n" - + " createTopicSettings,\n" - + " updateTopicSettings,\n" - + " publishSettings,\n" - + " getTopicSettings,\n" - + " listTopicsSettings,\n" - + " listTopicSubscriptionsSettings,\n" - + " listTopicSnapshotsSettings,\n" - + " deleteTopicSettings,\n" - + " detachSubscriptionSettings);\n" - + " }\n" - + "\n" - + " private static Builder createDefault() {\n" - + " Builder builder = new Builder(((ClientContext) null));\n" - + " builder.setTransportChannelProvider(defaultTransportChannelProvider());\n" - + " builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());\n" - + " " - + " builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());\n" - + " builder.setEndpoint(getDefaultEndpoint());\n" - + " return initDefaults(builder);\n" - + " }\n" - + "\n" - + " private static Builder initDefaults(Builder builder) {\n" - + " builder\n" - + " .createTopicSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_0_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_0_params\"));\n" - + " builder\n" - + " .updateTopicSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_0_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_0_params\"));\n" - + " builder\n" - + " .publishSettings()\n" - + " .setBatchingSettings(\n" - + " BatchingSettings.newBuilder()\n" - + " .setElementCountThreshold(100L)\n" - + " .setRequestByteThreshold(1048576L)\n" - + " .setDelayThreshold(Duration.ofMillis(10L))\n" - + " .setFlowControlSettings(\n" - + " FlowControlSettings.newBuilder()\n" - + " " - + " .setLimitExceededBehavior(FlowController.LimitExceededBehavior.Ignore)\n" - + " .build())\n" - + " .build());\n" - + " builder\n" - + " .publishSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"));\n" - + " builder\n" - + " .getTopicSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_2_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_2_params\"));\n" - + " builder\n" - + " .listTopicsSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_2_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_2_params\"));\n" - + " builder\n" - + " .listTopicSubscriptionsSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_2_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_2_params\"));\n" - + " builder\n" - + " .listTopicSnapshotsSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_2_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_2_params\"));\n" - + " builder\n" - + " .deleteTopicSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_0_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_0_params\"));\n" - + " builder\n" - + " .detachSubscriptionSettings()\n" - + " " - + " .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_0_codes\"))\n" - + " " - + " .setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_0_params\"));\n" - + " return builder;\n" - + " }\n" - + "\n" - + " // NEXT_MAJOR_VER: remove 'throws Exception'.\n" - + " /**\n" - + " * Applies the given settings updater function to all of the unary API methods in" - + " this service.\n" - + " *\n" - + " *

Note: This method does not support applying settings to streaming" - + " methods.\n" - + " */\n" - + " public Builder applyToAllUnaryMethods(\n" - + " ApiFunction, Void> settingsUpdater) throws" - + " Exception {\n" - + " super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);\n" - + " return this;\n" - + " }\n" - + "\n" - + " public ImmutableList>" - + " unaryMethodSettingsBuilders() {\n" - + " return unaryMethodSettingsBuilders;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to createTopic. */\n" - + " public UnaryCallSettings.Builder createTopicSettings() {\n" - + " return createTopicSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to updateTopic. */\n" - + " public UnaryCallSettings.Builder updateTopicSettings()" - + " {\n" - + " return updateTopicSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to publish. */\n" - + " public BatchingCallSettings.Builder" - + " publishSettings() {\n" - + " return publishSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to getTopic. */\n" - + " public UnaryCallSettings.Builder getTopicSettings() {\n" - + " return getTopicSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to listTopics. */\n" - + " public PagedCallSettings.Builder\n" - + " listTopicsSettings() {\n" - + " return listTopicsSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to" - + " listTopicSubscriptions. */\n" - + " public PagedCallSettings.Builder<\n" - + " ListTopicSubscriptionsRequest,\n" - + " ListTopicSubscriptionsResponse,\n" - + " ListTopicSubscriptionsPagedResponse>\n" - + " listTopicSubscriptionsSettings() {\n" - + " return listTopicSubscriptionsSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to listTopicSnapshots." - + " */\n" - + " public PagedCallSettings.Builder<\n" - + " ListTopicSnapshotsRequest, ListTopicSnapshotsResponse," - + " ListTopicSnapshotsPagedResponse>\n" - + " listTopicSnapshotsSettings() {\n" - + " return listTopicSnapshotsSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to deleteTopic. */\n" - + " public UnaryCallSettings.Builder deleteTopicSettings()" - + " {\n" - + " return deleteTopicSettings;\n" - + " }\n" - + "\n" - + " /** Returns the builder for the settings used for calls to detachSubscription." - + " */\n" - + " public UnaryCallSettings.Builder\n" - + " detachSubscriptionSettings() {\n" - + " return detachSubscriptionSettings;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public PublisherStubSettings build() throws IOException {\n" - + " return new PublisherStubSettings(this);\n" - + " }\n" - + " }\n" - + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ComposerTest.golden new file mode 100644 index 0000000000..ad531d6d09 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ComposerTest.golden @@ -0,0 +1,19 @@ +/* + * 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 + * + * https://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.showcase.v1beta1.stub; + +public class EchoStubSettings {} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceCallableFactoryClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceCallableFactoryClassComposerTest.golden new file mode 100644 index 0000000000..0786cd3d1b --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceCallableFactoryClassComposerTest.golden @@ -0,0 +1,97 @@ +package com.google.showcase.v1beta1.stub; + +import com.google.api.gax.grpc.GrpcCallSettings; +import com.google.api.gax.grpc.GrpcCallableFactory; +import com.google.api.gax.grpc.GrpcStubCallableFactory; +import com.google.api.gax.rpc.BatchingCallSettings; +import com.google.api.gax.rpc.BidiStreamingCallable; +import com.google.api.gax.rpc.ClientContext; +import com.google.api.gax.rpc.ClientStreamingCallable; +import com.google.api.gax.rpc.OperationCallSettings; +import com.google.api.gax.rpc.OperationCallable; +import com.google.api.gax.rpc.PagedCallSettings; +import com.google.api.gax.rpc.ServerStreamingCallSettings; +import com.google.api.gax.rpc.ServerStreamingCallable; +import com.google.api.gax.rpc.StreamingCallSettings; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.longrunning.Operation; +import com.google.longrunning.stub.OperationsStub; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * gRPC callable factory implementation for the Echo service API. + * + *

This class is for advanced usage. + */ +@Generated("by gapic-generator") +public class GrpcEchoCallableFactory implements GrpcStubCallableFactory { + + @Override + public UnaryCallable createUnaryCallable( + GrpcCallSettings grpcCallSettings, + UnaryCallSettings callSettings, + ClientContext clientContext) { + return GrpcCallableFactory.createUnaryCallable(grpcCallSettings, callSettings, clientContext); + } + + @Override + public + UnaryCallable createPagedCallable( + GrpcCallSettings grpcCallSettings, + PagedCallSettings callSettings, + ClientContext clientContext) { + return GrpcCallableFactory.createPagedCallable(grpcCallSettings, callSettings, clientContext); + } + + @Override + public UnaryCallable createBatchingCallable( + GrpcCallSettings grpcCallSettings, + BatchingCallSettings callSettings, + ClientContext clientContext) { + return GrpcCallableFactory.createBatchingCallable( + grpcCallSettings, callSettings, clientContext); + } + + @Override + public + OperationCallable createOperationCallable( + GrpcCallSettings grpcCallSettings, + OperationCallSettings callSettings, + ClientContext clientContext, + OperationsStub operationsStub) { + return GrpcCallableFactory.createOperationCallable( + grpcCallSettings, callSettings, clientContext, operationsStub); + } + + @Override + public + BidiStreamingCallable createBidiStreamingCallable( + GrpcCallSettings grpcCallSettings, + StreamingCallSettings callSettings, + ClientContext clientContext) { + return GrpcCallableFactory.createBidiStreamingCallable( + grpcCallSettings, callSettings, clientContext); + } + + @Override + public + ServerStreamingCallable createServerStreamingCallable( + GrpcCallSettings grpcCallSettings, + ServerStreamingCallSettings callSettings, + ClientContext clientContext) { + return GrpcCallableFactory.createServerStreamingCallable( + grpcCallSettings, callSettings, clientContext); + } + + @Override + public + ClientStreamingCallable createClientStreamingCallable( + GrpcCallSettings grpcCallSettings, + StreamingCallSettings callSettings, + ClientContext clientContext) { + return GrpcCallableFactory.createClientStreamingCallable( + grpcCallSettings, callSettings, clientContext); + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceStubClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceStubClassComposerTest.golden new file mode 100644 index 0000000000..9068e90730 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceStubClassComposerTest.golden @@ -0,0 +1,278 @@ +package com.google.showcase.v1beta1.stub; + +import static com.google.showcase.v1beta1.EchoClient.PagedExpandPagedResponse; + +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.core.BackgroundResourceAggregation; +import com.google.api.gax.grpc.GrpcCallSettings; +import com.google.api.gax.grpc.GrpcStubCallableFactory; +import com.google.api.gax.rpc.BidiStreamingCallable; +import com.google.api.gax.rpc.ClientContext; +import com.google.api.gax.rpc.ClientStreamingCallable; +import com.google.api.gax.rpc.OperationCallable; +import com.google.api.gax.rpc.ServerStreamingCallable; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.longrunning.Operation; +import com.google.longrunning.stub.GrpcOperationsStub; +import com.google.showcase.v1beta1.BlockRequest; +import com.google.showcase.v1beta1.BlockResponse; +import com.google.showcase.v1beta1.EchoRequest; +import com.google.showcase.v1beta1.EchoResponse; +import com.google.showcase.v1beta1.ExpandRequest; +import com.google.showcase.v1beta1.PagedExpandRequest; +import com.google.showcase.v1beta1.PagedExpandResponse; +import com.google.showcase.v1beta1.WaitMetadata; +import com.google.showcase.v1beta1.WaitRequest; +import com.google.showcase.v1beta1.WaitResponse; +import io.grpc.MethodDescriptor; +import io.grpc.protobuf.ProtoUtils; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * gRPC stub implementation for the Echo service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public class GrpcEchoStub extends EchoStub { + private static final MethodDescriptor echoMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.showcase.v1beta1.Echo/Echo") + .setRequestMarshaller(ProtoUtils.marshaller(EchoRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(EchoResponse.getDefaultInstance())) + .build(); + private static final MethodDescriptor expandMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.SERVER_STREAMING) + .setFullMethodName("google.showcase.v1beta1.Echo/Expand") + .setRequestMarshaller(ProtoUtils.marshaller(ExpandRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(EchoResponse.getDefaultInstance())) + .build(); + private static final MethodDescriptor collectMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.CLIENT_STREAMING) + .setFullMethodName("google.showcase.v1beta1.Echo/Collect") + .setRequestMarshaller(ProtoUtils.marshaller(EchoRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(EchoResponse.getDefaultInstance())) + .build(); + private static final MethodDescriptor chatMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.BIDI_STREAMING) + .setFullMethodName("google.showcase.v1beta1.Echo/Chat") + .setRequestMarshaller(ProtoUtils.marshaller(EchoRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(EchoResponse.getDefaultInstance())) + .build(); + private static final MethodDescriptor chatAgainMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.BIDI_STREAMING) + .setFullMethodName("google.showcase.v1beta1.Echo/ChatAgain") + .setRequestMarshaller(ProtoUtils.marshaller(EchoRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(EchoResponse.getDefaultInstance())) + .build(); + private static final MethodDescriptor + pagedExpandMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.showcase.v1beta1.Echo/PagedExpand") + .setRequestMarshaller(ProtoUtils.marshaller(PagedExpandRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(PagedExpandResponse.getDefaultInstance())) + .build(); + private static final MethodDescriptor waitMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.showcase.v1beta1.Echo/Wait") + .setRequestMarshaller(ProtoUtils.marshaller(WaitRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) + .build(); + private static final MethodDescriptor blockMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.showcase.v1beta1.Echo/Block") + .setRequestMarshaller(ProtoUtils.marshaller(BlockRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(BlockResponse.getDefaultInstance())) + .build(); + private final UnaryCallable echoCallable; + private final ServerStreamingCallable expandCallable; + private final ClientStreamingCallable collectCallable; + private final BidiStreamingCallable chatCallable; + private final BidiStreamingCallable chatAgainCallable; + private final UnaryCallable pagedExpandCallable; + private final UnaryCallable + pagedExpandPagedCallable; + private final UnaryCallable waitCallable; + private final OperationCallable waitOperationCallable; + private final UnaryCallable blockCallable; + private final BackgroundResource backgroundResources; + private final GrpcOperationsStub operationsStub; + private final GrpcStubCallableFactory callableFactory; + + public static final GrpcEchoStub create(EchoStubSettings settings) throws IOException { + return new GrpcEchoStub(settings, ClientContext.create(settings)); + } + + public static final GrpcEchoStub create(ClientContext clientContext) throws IOException { + return new GrpcEchoStub(EchoStubSettings.newBuilder().build(), clientContext); + } + + public static final GrpcEchoStub create( + ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { + return new GrpcEchoStub(EchoStubSettings.newBuilder().build(), clientContext, callableFactory); + } + + protected GrpcEchoStub(EchoStubSettings settings, ClientContext clientContext) + throws IOException { + this(settings, clientContext, new GrpcEchoCallableFactory()); + } + + protected GrpcEchoStub( + EchoStubSettings settings, + ClientContext clientContext, + GrpcStubCallableFactory callableFactory) + throws IOException { + this.callableFactory = callableFactory; + this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); + GrpcCallSettings echoTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(echoMethodDescriptor) + .build(); + GrpcCallSettings expandTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(expandMethodDescriptor) + .build(); + GrpcCallSettings collectTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(collectMethodDescriptor) + .build(); + GrpcCallSettings chatTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(chatMethodDescriptor) + .build(); + GrpcCallSettings chatAgainTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(chatAgainMethodDescriptor) + .build(); + GrpcCallSettings pagedExpandTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(pagedExpandMethodDescriptor) + .build(); + GrpcCallSettings waitTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(waitMethodDescriptor) + .build(); + GrpcCallSettings blockTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(blockMethodDescriptor) + .build(); + this.echoCallable = + callableFactory.createUnaryCallable( + echoTransportSettings, settings.echoSettings(), clientContext); + this.expandCallable = + callableFactory.createServerStreamingCallable( + expandTransportSettings, settings.expandSettings(), clientContext); + this.collectCallable = + callableFactory.createClientStreamingCallable( + collectTransportSettings, settings.collectSettings(), clientContext); + this.chatCallable = + callableFactory.createBidiStreamingCallable( + chatTransportSettings, settings.chatSettings(), clientContext); + this.chatAgainCallable = + callableFactory.createBidiStreamingCallable( + chatAgainTransportSettings, settings.chatAgainSettings(), clientContext); + this.pagedExpandCallable = + callableFactory.createUnaryCallable( + pagedExpandTransportSettings, settings.pagedExpandSettings(), clientContext); + this.pagedExpandPagedCallable = + callableFactory.createUnaryCallable( + pagedExpandTransportSettings, settings.pagedExpandSettings(), clientContext); + this.waitCallable = + callableFactory.createUnaryCallable( + waitTransportSettings, settings.waitSettings(), clientContext); + this.waitOperationCallable = + callableFactory.createOperationCallable( + waitTransportSettings, settings.waitOperationSettings(), clientContext, operationsStub); + this.blockCallable = + callableFactory.createUnaryCallable( + blockTransportSettings, settings.blockSettings(), clientContext); + this.backgroundResources = + new BackgroundResourceAggregation(clientContext.getBackgroundResources()); + } + + public GrpcOperationsStub getOperationsStub() { + return operationsStub; + } + + public UnaryCallable echoCallable() { + return echoCallable; + } + + public ServerStreamingCallable expandCallable() { + return expandCallable; + } + + public ClientStreamingCallable collectCallable() { + return collectCallable; + } + + public BidiStreamingCallable chatCallable() { + return chatCallable; + } + + public BidiStreamingCallable chatAgainCallable() { + return chatAgainCallable; + } + + public UnaryCallable pagedExpandCallable() { + return pagedExpandCallable; + } + + public UnaryCallable pagedExpandPagedCallable() { + return pagedExpandPagedCallable; + } + + public UnaryCallable waitCallable() { + return waitCallable; + } + + public OperationCallable waitOperationCallable() { + return waitOperationCallable; + } + + public UnaryCallable blockCallable() { + return blockCallable; + } + + @Override + public final void close() { + shutdown(); + } + + @Override + public void shutdown() { + backgroundResources.shutdown(); + } + + @Override + public boolean isShutdown() { + return backgroundResources.isShutdown(); + } + + @Override + public boolean isTerminated() { + return backgroundResources.isTerminated(); + } + + @Override + public void shutdownNow() { + backgroundResources.shutdownNow(); + } + + @Override + public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { + return backgroundResources.awaitTermination(duration, unit); + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceClassComposerTest.golden new file mode 100644 index 0000000000..57c735b964 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceClassComposerTest.golden @@ -0,0 +1,43 @@ +package com.google.showcase.v1beta1; + +import com.google.api.core.BetaApi; +import com.google.api.gax.grpc.testing.MockGrpcService; +import com.google.protobuf.AbstractMessage; +import io.grpc.ServerServiceDefinition; +import java.util.List; +import javax.annotation.Generated; + +@BetaApi +@Generated("by gapic-generator-java") +public class MockEcho implements MockGrpcService { + private final MockEchoImpl serviceImpl; + + public MockEcho() { + serviceImpl = new MockEchoImpl(); + } + + @Override + public List getRequests() { + return serviceImpl.getRequests(); + } + + @Override + public void addResponse(AbstractMessage response) { + serviceImpl.addResponse(response); + } + + @Override + public void addException(Exception exception) { + serviceImpl.addException(exception); + } + + @Override + public ServerServiceDefinition getServiceDefinition() { + return serviceImpl.bindService(); + } + + @Override + public void reset() { + serviceImpl.reset(); + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceImplClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceImplClassComposerTest.golden new file mode 100644 index 0000000000..05641e4794 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceImplClassComposerTest.golden @@ -0,0 +1,212 @@ +package com.google.showcase.v1beta1; + +import com.google.api.core.BetaApi; +import com.google.longrunning.Operation; +import com.google.protobuf.AbstractMessage; +import com.google.showcase.v1beta1.EchoGrpc.EchoImplBase; +import io.grpc.stub.StreamObserver; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import javax.annotation.Generated; + +@BetaApi +@Generated("by gapic-generator-java") +public class MockEchoImpl extends EchoImplBase { + private List requests; + private Queue responses; + + public MockEchoImpl() { + requests = new ArrayList<>(); + responses = new LinkedList<>(); + } + + @Override + public List getRequests() { + return requests; + } + + @Override + public void addResponse(AbstractMessage response) { + responses.add(response); + } + + @Override + public void setResponses(List responses) { + this.responses = new LinkedList(responses); + } + + @Override + public void addException(Exception exception) { + responses.add(exception); + } + + @Override + public void reset() { + requests = new ArrayList<>(); + responses = new LinkedList<>(); + } + + @Override + public void echo(EchoRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof EchoResponse) { + requests.add(request); + responseObserver.onNext(((EchoResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void expand(ExpandRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof EchoResponse) { + requests.add(request); + responseObserver.onNext(((EchoResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public StreamObserver collect(final StreamObserver responseObserver) { + StreamObserver requestObserver = + new StreamObserver() { + @Override + public void onNext(EchoRequest value) { + requests.add(value); + final Object response = responses.remove(); + if (response instanceof EchoResponse) { + responseObserver.onNext(((EchoResponse) response)); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void onError(Throwable t) { + responseObserver.onError(t); + } + + @Override + public void onCompleted() { + responseObserver.onCompleted(); + } + }; + return requestObserver; + } + + @Override + public StreamObserver chat(final StreamObserver responseObserver) { + StreamObserver requestObserver = + new StreamObserver() { + @Override + public void onNext(EchoRequest value) { + requests.add(value); + final Object response = responses.remove(); + if (response instanceof EchoResponse) { + responseObserver.onNext(((EchoResponse) response)); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void onError(Throwable t) { + responseObserver.onError(t); + } + + @Override + public void onCompleted() { + responseObserver.onCompleted(); + } + }; + return requestObserver; + } + + @Override + public StreamObserver chatAgain( + final StreamObserver responseObserver) { + StreamObserver requestObserver = + new StreamObserver() { + @Override + public void onNext(EchoRequest value) { + requests.add(value); + final Object response = responses.remove(); + if (response instanceof EchoResponse) { + responseObserver.onNext(((EchoResponse) response)); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void onError(Throwable t) { + responseObserver.onError(t); + } + + @Override + public void onCompleted() { + responseObserver.onCompleted(); + } + }; + return requestObserver; + } + + @Override + public void pagedExpand( + PagedExpandRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof PagedExpandResponse) { + requests.add(request); + responseObserver.onNext(((PagedExpandResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void wait(WaitRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof Operation) { + requests.add(request); + responseObserver.onNext(((Operation) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void block(BlockRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof BlockResponse) { + requests.add(request); + responseObserver.onNext(((BlockResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestMultiPattern.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestMultiPattern.golden new file mode 100644 index 0000000000..0b6beb27cb --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestMultiPattern.golden @@ -0,0 +1,314 @@ +package com.google.showcase.v1beta1; + +import com.google.api.core.BetaApi; +import com.google.api.pathtemplate.PathTemplate; +import com.google.api.pathtemplate.ValidationException; +import com.google.api.resourcenames.ResourceName; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +@Generated("by gapic-generator-java") +public class FoobarName implements ResourceName { + private static final PathTemplate PROJECT_FOOBAR = + PathTemplate.createWithoutUrlEncoding("projects/{project}/foobars/{foobar}"); + private static final PathTemplate PROJECT_VARIANT_FOOBAR = + PathTemplate.createWithoutUrlEncoding( + "projects/{project}/chocolate/variants/{variant}/foobars/{foobar}"); + private static final PathTemplate FOOBAR = + PathTemplate.createWithoutUrlEncoding("foobars/{foobar}"); + private volatile Map fieldValuesMap; + private PathTemplate pathTemplate; + private String fixedValue; + private final String project; + private final String foobar; + private final String variant; + + @Deprecated + protected FoobarName() {} + + private FoobarName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + foobar = Preconditions.checkNotNull(builder.getFoobar()); + pathTemplate = PROJECT_FOOBAR; + } + + private FoobarName(ProjectVariantFoobarBuilder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + variant = Preconditions.checkNotNull(builder.getVariant()); + foobar = Preconditions.checkNotNull(builder.getFoobar()); + pathTemplate = PROJECT_VARIANT_FOOBAR; + } + + private FoobarName(FoobarBuilder builder) { + foobar = Preconditions.checkNotNull(builder.getFoobar()); + pathTemplate = FOOBAR; + } + + public String getProject() { + return project; + } + + public String getFoobar() { + return foobar; + } + + public String getVariant() { + return variant; + } + + public static Builder newBuilder() { + return new Builder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static Builder newProjectFoobarBuilder() { + return new Builder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static ProjectVariantFoobarBuilder newProjectVariantFoobarBuilder() { + return new ProjectVariantFoobarBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static FoobarBuilder newFoobarBuilder() { + return new FoobarBuilder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static FoobarName of(String project, String foobar) { + return newBuilder().setProject(project).setFoobar(foobar).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static FoobarName ofProjectFoobarBuilder(String project, String foobar) { + return newBuilder().setProject(project).setFoobar(foobar).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static FoobarName ofProjectVariantFoobarBuilder( + String project, String variant, String foobar) { + return newProjectVariantFoobarBuilder() + .setProject(project) + .setVariant(variant) + .setFoobar(foobar) + .build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static FoobarName ofFoobarBuilder(String foobar) { + return newFoobarBuilder().setFoobar(foobar).build(); + } + + public static String format(String project, String foobar) { + return newBuilder().setProject(project).setFoobar(foobar).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatProjectFoobarBuilder(String project, String foobar) { + return newBuilder().setProject(project).setFoobar(foobar).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatProjectVariantFoobarBuilder( + String project, String variant, String foobar) { + return newProjectVariantFoobarBuilder() + .setProject(project) + .setVariant(variant) + .setFoobar(foobar) + .build() + .toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatFoobarBuilder(String foobar) { + return newFoobarBuilder().setFoobar(foobar).build().toString(); + } + + public static FoobarName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + if (PROJECT_FOOBAR.matches(formattedString)) { + Map matchMap = PROJECT_FOOBAR.match(formattedString); + return ofProjectFoobarBuilder(matchMap.get("project"), matchMap.get("foobar")); + } else if (PROJECT_VARIANT_FOOBAR.matches(formattedString)) { + Map matchMap = PROJECT_VARIANT_FOOBAR.match(formattedString); + return ofProjectVariantFoobarBuilder( + matchMap.get("project"), matchMap.get("variant"), matchMap.get("foobar")); + } else if (FOOBAR.matches(formattedString)) { + Map matchMap = FOOBAR.match(formattedString); + return ofFoobarBuilder(matchMap.get("foobar")); + } + throw new ValidationException("FoobarName.parse: formattedString not in valid format"); + } + + public static List parseList(List formattedStrings) { + List list = new ArrayList<>(formattedStrings.size()); + for (String formattedString : formattedStrings) { + list.add(parse(formattedString)); + } + return list; + } + + public static List toStringList(List values) { + List list = new ArrayList<>(values.size()); + for (FoobarName value : values) { + if (Objects.equals(value, null)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_FOOBAR + .matches(formattedString) + .todoOr(PROJECT_VARIANT_FOOBAR.matches(formattedString)) + .todoOr(FOOBAR.matches(formattedString)); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.equals(fieldValuesMap, null)) { + synchronized (this) { + if (Objects.equals(fieldValuesMap, null)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (Objects.notTodoEquals(project, null)) { + fieldMapBuilder.put("project", project); + } + if (Objects.notTodoEquals(foobar, null)) { + fieldMapBuilder.put("foobar", foobar); + } + if (Objects.notTodoEquals(variant, null)) { + fieldMapBuilder.put("variant", variant); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return Objects.equals(fixedValue, null) + ? pathTemplate.instantiate(getFieldValuesMap()) + : fixedValue; + } + + /** Builder for projects/{project}/foobars/{foobar}. */ + public static class Builder { + private String project; + private String foobar; + + private Builder() {} + + public String getProject() { + return project; + } + + public String getFoobar() { + return foobar; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setFoobar(String foobar) { + this.foobar = foobar; + return this; + } + + private Builder(FoobarName foobarName) { + Preconditions.checkArgument( + Objects.equals(foobarName.pathTemplate, PROJECT_FOOBAR), + "toBuilder is only supported when FoobarName has the pattern of projects/{project}/foobars/{foobar}"); + project = foobarName.project; + foobar = foobarName.foobar; + } + + public FoobarName build() { + return new FoobarName(this); + } + } + + /** Builder for projects/{project}/chocolate/variants/{variant}/foobars/{foobar}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class ProjectVariantFoobarBuilder { + private String project; + private String variant; + private String foobar; + + private ProjectVariantFoobarBuilder() {} + + public String getProject() { + return project; + } + + public String getVariant() { + return variant; + } + + public String getFoobar() { + return foobar; + } + + public ProjectVariantFoobarBuilder setProject(String project) { + this.project = project; + return this; + } + + public ProjectVariantFoobarBuilder setVariant(String variant) { + this.variant = variant; + return this; + } + + public ProjectVariantFoobarBuilder setFoobar(String foobar) { + this.foobar = foobar; + return this; + } + + public FoobarName build() { + return new FoobarName(this); + } + } + + /** Builder for foobars/{foobar}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class FoobarBuilder { + private String foobar; + + private FoobarBuilder() {} + + public String getFoobar() { + return foobar; + } + + public FoobarBuilder setFoobar(String foobar) { + this.foobar = foobar; + return this; + } + + public FoobarName build() { + return new FoobarName(this); + } + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestOnePattern.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestOnePattern.golden new file mode 100644 index 0000000000..0e3a9266f5 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestOnePattern.golden @@ -0,0 +1,127 @@ +package com.google.showcase.v1beta1; + +import com.google.api.pathtemplate.PathTemplate; +import com.google.api.resourcenames.ResourceName; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +@Generated("by gapic-generator-java") +public class SessionName implements ResourceName { + private static final PathTemplate SESSION = + PathTemplate.createWithoutUrlEncoding("sessions/{session}"); + private volatile Map fieldValuesMap; + private final String session; + + private SessionName(Builder builder) { + session = Preconditions.checkNotNull(builder.getSession()); + } + + public String getSession() { + return session; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static SessionName of(String session) { + return newBuilder().setSession(session).build(); + } + + public static String format(String session) { + return newBuilder().setSession(session).build().toString(); + } + + public static SessionName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + SESSION.validatedMatch( + formattedString, "SessionName.parse: formattedString not in valid format"); + return of(matchMap.get("session")); + } + + public static List parseList(List formattedStrings) { + List list = new ArrayList<>(formattedStrings.size()); + for (String formattedString : formattedStrings) { + list.add(parse(formattedString)); + } + return list; + } + + public static List toStringList(List values) { + List list = new ArrayList<>(values.size()); + for (SessionName value : values) { + if (Objects.equals(value, null)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return SESSION.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.equals(fieldValuesMap, null)) { + synchronized (this) { + if (Objects.equals(fieldValuesMap, null)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (Objects.notTodoEquals(session, null)) { + fieldMapBuilder.put("session", session); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return SESSION.instantiate("session", session); + } + + /** Builder for sessions/{session}. */ + public static class Builder { + private String session; + + private Builder() {} + + public String getSession() { + return session; + } + + public Builder setSession(String session) { + this.session = session; + return this; + } + + private Builder(SessionName sessionName) { + session = sessionName.session; + } + + public SessionName build() { + return new SessionName(this); + } + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden new file mode 100644 index 0000000000..c4ff6fd19c --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden @@ -0,0 +1,191 @@ +package com.google.showcase.v1beta1; + +import com.google.api.core.BetaApi; +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.longrunning.OperationFuture; +import com.google.api.gax.rpc.BidiStreamingCallable; +import com.google.api.gax.rpc.ClientStreamingCallable; +import com.google.api.gax.rpc.OperationCallable; +import com.google.api.gax.rpc.ServerStreamingCallable; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.api.resourcenames.ResourceName; +import com.google.common.base.Strings; +import com.google.longrunning.Operation; +import com.google.longrunning.OperationsClient; +import com.google.rpc.Status; +import com.google.showcase.v1beta1.stub.EchoStub; +import com.google.showcase.v1beta1.stub.EchoStubSettings; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +@BetaApi +@Generated("by gapic-generator") +public class EchoClient implements BackgroundResource { + private final EchoSettings settings; + private final EchoStub stub; + private final OperationsClient operationsClient; + + public static final EchoClient create() throws IOException { + return create(EchoSettings.newBuilder().build()); + } + + public static final EchoClient create(EchoSettings settings) throws IOException { + return new EchoClient(settings); + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public static final EchoClient create(EchoStub stub) { + return new EchoClient(stub); + } + + protected EchoClient(EchoSettings settings) throws IOException { + this.settings = settings; + this.stub = ((EchoStubSettings) settings.getStubSettings()).createStub(); + this.operationsClient = OperationsClient.create(this.stub.getOperationsStub()); + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + protected EchoClient(EchoStub stub) { + this.settings = null; + this.stub = stub; + this.operationsClient = OperationsClient.create(this.stub.getOperationsStub()); + } + + public final EchoSettings getSettings() { + return settings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public EchoStub getStub() { + return stub; + } + + public final OperationsClient getOperationsClient() { + return operationsClient; + } + + public final EchoResponse echo(String content) { + EchoRequest request = EchoRequest.newBuilder().setContent(content).build(); + return echo(request); + } + + public final EchoResponse echo(Status error) { + EchoRequest request = EchoRequest.newBuilder().setError(error).build(); + return echo(request); + } + + public final EchoResponse echo(String content, Severity severity) { + EchoRequest request = + EchoRequest.newBuilder().setContent(content).setSeverity(severity).build(); + return echo(request); + } + + public final EchoResponse echo(String name) { + EchoRequest request = EchoRequest.newBuilder().setName(name).build(); + return echo(request); + } + + public final EchoResponse echo(FoobarName name) { + EchoRequest request = + EchoRequest.newBuilder() + .setName(Strings.isNullOrEmpty(name) ? null : name.toString()) + .build(); + return echo(request); + } + + public final EchoResponse echo(String parent) { + EchoRequest request = EchoRequest.newBuilder().setParent(parent).build(); + return echo(request); + } + + public final EchoResponse echo(ResourceName parent) { + EchoRequest request = + EchoRequest.newBuilder() + .setParent(Strings.isNullOrEmpty(parent) ? null : parent.toString()) + .build(); + return echo(request); + } + + public final EchoResponse echo(EchoRequest request) { + return echoCallable().call(request); + } + + public final UnaryCallable echoCallable() { + return stub.echoCallable(); + } + + public final ServerStreamingCallable expandCallable() { + return stub.expandCallable(); + } + + public final ClientStreamingCallable collectCallable() { + return stub.collectCallable(); + } + + public final BidiStreamingCallable chatCallable() { + return stub.chatCallable(); + } + + public final BidiStreamingCallable chatAgainCallable() { + return stub.chatAgainCallable(); + } + + public final PagedExpandResponse pagedExpand(PagedExpandRequest request) { + return pagedExpandCallable().call(request); + } + + public final UnaryCallable pagedExpandCallable() { + return stub.pagedExpandCallable(); + } + + public final OperationFuture waitAsync(WaitRequest request) { + return waitOperationCallable().futureCall(request); + } + + public final OperationCallable waitOperationCallabke() { + return stub.waitOperationCallabke(); + } + + public final UnaryCallable waitCallable() { + return stub.waitCallable(); + } + + public final BlockResponse block(BlockRequest request) { + return blockCallable().call(request); + } + + public final UnaryCallable blockCallable() { + return stub.blockCallable(); + } + + @Override + public final void close() { + stub.close(); + } + + @Override + public void shutdown() { + stub.shutdown(); + } + + @Override + public boolean isShutdown() { + return stub.isShutdown(); + } + + @Override + public boolean isTerminated() { + return stub.isTerminated(); + } + + @Override + public void shutdownNow() { + stub.shutdownNow(); + } + + @Override + public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { + return stub.awaitTermination(duration, unit); + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden new file mode 100644 index 0000000000..8f63eac49d --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden @@ -0,0 +1,53 @@ +package com.google.showcase.v1beta1; + +import com.google.api.gax.core.NoCredentialsProvider; +import com.google.api.gax.grpc.testing.LocalChannelProvider; +import com.google.api.gax.grpc.testing.MockGrpcService; +import com.google.api.gax.grpc.testing.MockServiceHelper; +import java.io.IOException; +import java.util.Arrays; +import java.util.UUID; +import javax.annotation.Generated; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; + +@Generated("by gapic-generator-java") +public class EchoClientTest { + public static MockServiceHelper mockServiceHelper; + public static MockEcho mockEcho; + public EchoClient client; + public LocalChannelProvider channelProvider; + + @BeforeClass + public static void startStaticServer() { + mockEcho = new MockEcho(); + mockServiceHelper = + new MockServiceHelper( + UUID.randomUUID().toString(), Arrays.asList(mockEcho)); + mockServiceHelper.start(); + } + + @AfterClass + public static void stopServer() { + mockServiceHelper.stop(); + } + + @Before + public void setUp() throws IOException { + mockServiceHelper.reset(); + channelProvider = mockServiceHelper.createChannelProvider(); + settings = + EchoSettings.newBuilder() + .setTransportChannelProvider(channelProvider) + .setCredentialsProvider(NoCredentialsProvider.create()) + .build(); + client = EchoClient.create(settings); + } + + @After + public static void tearDown() throws Exception { + client.close(); + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceSettingsClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceSettingsClassComposerTest.golden new file mode 100644 index 0000000000..221b3725d2 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceSettingsClassComposerTest.golden @@ -0,0 +1,242 @@ +package com.google.showcase.v1beta1; + +import static com.google.showcase.v1beta1.EchoClient.PagedExpandPagedResponse; + +import com.google.api.core.ApiFunction; +import com.google.api.core.BetaApi; +import com.google.api.gax.core.GoogleCredentialsProvider; +import com.google.api.gax.core.InstantiatingExecutorProvider; +import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; +import com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.ClientContext; +import com.google.api.gax.rpc.ClientSettings; +import com.google.api.gax.rpc.OperationCallSettings; +import com.google.api.gax.rpc.PagedCallSettings; +import com.google.api.gax.rpc.ServerStreamingCallSettings; +import com.google.api.gax.rpc.StreamingCallSettings; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.longrunning.Operation; +import com.google.showcase.v1beta1.stub.EchoStubSettings; +import java.io.IOException; +import java.util.List; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link EchoClient}. + * + *

The default instance has everything set to sensible defaults: + * + *

    + *
  • The default service address (localhost) and default port (7469) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
+ * + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. + * + *

For example, to set the total timeout of echo to 30 seconds: + */ +@Generated("by gapic-generator-java") +public class EchoSettings extends ClientSettings { + + /** Returns the object with the settings used for calls to echo. */ + public UnaryCallSettings echoSettings() { + return ((EchoStubSettings) getStubSettings()).echoSettings(); + } + + /** Returns the object with the settings used for calls to expand. */ + public ServerStreamingCallSettings expandSettings() { + return ((EchoStubSettings) getStubSettings()).expandSettings(); + } + + /** Returns the object with the settings used for calls to collect. */ + public StreamingCallSettings collectSettings() { + return ((EchoStubSettings) getStubSettings()).collectSettings(); + } + + /** Returns the object with the settings used for calls to chat. */ + public StreamingCallSettings chatSettings() { + return ((EchoStubSettings) getStubSettings()).chatSettings(); + } + + /** Returns the object with the settings used for calls to chatAgain. */ + public StreamingCallSettings chatAgainSettings() { + return ((EchoStubSettings) getStubSettings()).chatAgainSettings(); + } + + /** Returns the object with the settings used for calls to pagedExpand. */ + public PagedCallSettings + pagedExpandSettings() { + return ((EchoStubSettings) getStubSettings()).pagedExpandSettings(); + } + + /** Returns the object with the settings used for calls to wait. */ + public UnaryCallSettings waitSettings() { + return ((EchoStubSettings) getStubSettings()).waitSettings(); + } + + /** Returns the object with the settings used for calls to wait. */ + public OperationCallSettings waitOperationSettings() { + return ((EchoStubSettings) getStubSettings()).waitOperationSettings(); + } + + /** Returns the object with the settings used for calls to block. */ + public UnaryCallSettings blockSettings() { + return ((EchoStubSettings) getStubSettings()).blockSettings(); + } + + public static final EchoSettings create(EchoStubSettings stub) throws IOException { + return new EchoStubSettings.Builder(stub.toBuilder()).build(); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return EchoStubSettings.defaultExecutorProviderBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return EchoStubSettings.getDefaultEndpoint(); + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return EchoStubSettings.getDefaultServiceScopes(); + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return EchoStubSettings.defaultCredentialsProviderBuilder(); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return EchoStubSettings.defaultGrpcTransportProviderBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return EchoStubSettings.defaultTransportChannelProvider(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return EchoStubSettings.defaultApiClientHeaderProviderBuilder(); + } + + /** Returns a new builder for this class. */ + public static Builder newBuilder() { + return Builder.createDefault(); + } + + /** Returns a new builder for this class. */ + public static Builder newBuilder(ClientContext clientContext) { + return new Builder(clientContext); + } + + /** Returns a builder containing all the values of this settings class. */ + public Builder toBuilder() { + return new Builder(this); + } + + protected EchoSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + } + + /** Builder for EchoSettings. */ + public static class Builder extends ClientSettings.Builder { + + protected Builder() throws IOException { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(EchoStubSettings.newBuilder(clientContext)); + } + + protected Builder(EchoSettings settings) { + super(settings.getStubSettings().toBuilder()); + } + + protected Builder(EchoStubSettings.Builder stubSettings) { + super(stubSettings); + } + + private static Builder createDefault() { + return new Builder(EchoStubSettings.newBuilder()); + } + + public EchoStubSettings.Builder getStubSettingsBuilder() { + return ((EchoStubSettings.Builder) getStubSettings()); + } + + // NEXT_MAJOR_VER: remove 'throws Exception'. + /** + * Applies the given settings updater function to all of the unary API methods in this service. + * + *

Note: This method does not support applying settings to streaming methods. + */ + public Builder applyToAllUnaryMethods( + ApiFunction, Void> settingsUpdater) throws Exception { + super.applyToAllUnaryMethods( + getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater); + return this; + } + + /** Returns the builder for the settings used for calls to echo. */ + public UnaryCallSettings.Builder echoSettings() { + return getStubSettingsBuilder().echoSettings(); + } + + /** Returns the builder for the settings used for calls to expand. */ + public ServerStreamingCallSettings.Builder expandSettings() { + return getStubSettingsBuilder().expandSettings(); + } + + /** Returns the builder for the settings used for calls to collect. */ + public StreamingCallSettings.Builder collectSettings() { + return getStubSettingsBuilder().collectSettings(); + } + + /** Returns the builder for the settings used for calls to chat. */ + public StreamingCallSettings.Builder chatSettings() { + return getStubSettingsBuilder().chatSettings(); + } + + /** Returns the builder for the settings used for calls to chatAgain. */ + public StreamingCallSettings.Builder chatAgainSettings() { + return getStubSettingsBuilder().chatAgainSettings(); + } + + /** Returns the builder for the settings used for calls to pagedExpand. */ + public PagedCallSettings.Builder< + PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse> + pagedExpandSettings() { + return getStubSettingsBuilder().pagedExpandSettings(); + } + + /** Returns the builder for the settings used for calls to wait. */ + public UnaryCallSettings.Builder waitSettings() { + return getStubSettingsBuilder().waitSettings(); + } + + /** Returns the builder for the settings used for calls to wait. */ + public OperationCallSettings.Builder + waitOperationSettings() { + return getStubSettingsBuilder().waitOperationSettings(); + } + + /** Returns the builder for the settings used for calls to block. */ + public UnaryCallSettings.Builder blockSettings() { + return getStubSettingsBuilder().blockSettings(); + } + + @Override + public EchoSettings build() throws IOException { + return new EchoSettings(this); + } + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubClassComposerTest.golden new file mode 100644 index 0000000000..83bca288c2 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubClassComposerTest.golden @@ -0,0 +1,73 @@ +package com.google.showcase.v1beta1.stub; + +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.rpc.BidiStreamingCallable; +import com.google.api.gax.rpc.ClientStreamingCallable; +import com.google.api.gax.rpc.OperationCallable; +import com.google.api.gax.rpc.ServerStreamingCallable; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.longrunning.stub.OperationsStub; +import com.google.showcase.v1beta1.BlockRequest; +import com.google.showcase.v1beta1.BlockResponse; +import com.google.showcase.v1beta1.EchoRequest; +import com.google.showcase.v1beta1.EchoResponse; +import com.google.showcase.v1beta1.ExpandRequest; +import com.google.showcase.v1beta1.PagedExpandRequest; +import com.google.showcase.v1beta1.PagedExpandResponse; +import com.google.showcase.v1beta1.WaitMetadata; +import com.google.showcase.v1beta1.WaitRequest; +import com.google.showcase.v1beta1.WaitResponse; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Base stub class for the Echo service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator") +public abstract class EchoStub implements BackgroundResource { + + public OperationsStub getOperationsStub() { + throw new UnsupportedOperationException("Not implemented: getOperationsStub()"); + } + + public UnaryCallable echoCallable() { + throw new UnsupportedOperationException("Not implemented: echoCallable()"); + } + + public ServerStreamingCallable expandCallable() { + throw new UnsupportedOperationException("Not implemented: expandCallable()"); + } + + public ClientStreamingCallable collectCallable() { + throw new UnsupportedOperationException("Not implemented: collectCallable()"); + } + + public BidiStreamingCallable chatCallable() { + throw new UnsupportedOperationException("Not implemented: chatCallable()"); + } + + public BidiStreamingCallable chatAgainCallable() { + throw new UnsupportedOperationException("Not implemented: chatAgainCallable()"); + } + + public UnaryCallable pagedExpandCallable() { + throw new UnsupportedOperationException("Not implemented: pagedExpandCallable()"); + } + + public OperationCallable waitOperationCallable() { + throw new UnsupportedOperationException("Not implemented: waitOperationCallable()"); + } + + public UnaryCallable waitCallable() { + throw new UnsupportedOperationException("Not implemented: waitCallable()"); + } + + public UnaryCallable blockCallable() { + throw new UnsupportedOperationException("Not implemented: blockCallable()"); + } + + @Override + public abstract void close(); +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestEcho.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestEcho.golden new file mode 100644 index 0000000000..745634aa8c --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestEcho.golden @@ -0,0 +1,486 @@ +package com.google.showcase.v1beta1.stub; + +import static com.google.showcase.v1beta1.EchoClient.PagedExpandPagedResponse; + +import com.google.api.core.ApiFunction; +import com.google.api.core.ApiFuture; +import com.google.api.core.BetaApi; +import com.google.api.gax.core.GaxProperties; +import com.google.api.gax.core.GoogleCredentialsProvider; +import com.google.api.gax.core.InstantiatingExecutorProvider; +import com.google.api.gax.grpc.GaxGrpcProperties; +import com.google.api.gax.grpc.GrpcTransportChannel; +import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; +import com.google.api.gax.grpc.ProtoOperationTransformers; +import com.google.api.gax.longrunning.OperationSnapshot; +import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiCallContext; +import com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.ClientContext; +import com.google.api.gax.rpc.OperationCallSettings; +import com.google.api.gax.rpc.PageContext; +import com.google.api.gax.rpc.PagedCallSettings; +import com.google.api.gax.rpc.PagedListDescriptor; +import com.google.api.gax.rpc.PagedListResponseFactory; +import com.google.api.gax.rpc.ServerStreamingCallSettings; +import com.google.api.gax.rpc.StatusCode; +import com.google.api.gax.rpc.StreamingCallSettings; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.longrunning.Operation; +import com.google.showcase.v1beta1.BlockRequest; +import com.google.showcase.v1beta1.BlockResponse; +import com.google.showcase.v1beta1.EchoRequest; +import com.google.showcase.v1beta1.EchoResponse; +import com.google.showcase.v1beta1.ExpandRequest; +import com.google.showcase.v1beta1.PagedExpandRequest; +import com.google.showcase.v1beta1.PagedExpandResponse; +import com.google.showcase.v1beta1.WaitMetadata; +import com.google.showcase.v1beta1.WaitRequest; +import com.google.showcase.v1beta1.WaitResponse; +import java.io.IOException; +import java.util.List; +import java.util.Objects; +import javax.annotation.Generated; +import org.threeten.bp.Duration; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link EchoStub}. + * + *

The default instance has everything set to sensible defaults: + * + *

    + *
  • The default service address (localhost) and default port (7469) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
+ * + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. + * + *

For example, to set the total timeout of echo to 30 seconds: + */ +@BetaApi +@Generated("by gapic-generator-java") +public class EchoStubSettings extends StubSettings { + /** The default scopes of the service. */ + private static final ImmutableList DEFAULT_SERVICE_SCOPES = + ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build(); + + private final UnaryCallSettings echoSettings; + private final ServerStreamingCallSettings expandSettings; + private final StreamingCallSettings collectSettings; + private final StreamingCallSettings chatSettings; + private final StreamingCallSettings chatAgainSettings; + private final PagedCallSettings + pagedExpandSettings; + private final UnaryCallSettings waitSettings; + private final OperationCallSettings + waitOperationSettings; + private final UnaryCallSettings blockSettings; + private static final PagedListDescriptor + PAGED_EXPAND_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public PagedExpandRequest injectToken(PagedExpandRequest payload, String token) { + return PagedExpandRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public PagedExpandRequest injectPageSize(PagedExpandRequest payload, int pageSize) { + return PagedExpandRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(PagedExpandRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(PagedExpandResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(PagedExpandResponse payload) { + return Objects.equals(payload.getResponsesList(), null) + ? ImmutableList.of() + : payload.getResponsesList(); + } + }; + private static final PagedListResponseFactory< + PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse> + PAGED_EXPAND_PAGE_STR_FACT = + new PagedListResponseFactory< + PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + PagedExpandRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, PAGED_EXPAND_PAGE_STR_DESC, request, context); + return PagedExpandPagedResponse.createAsync(pageContext, futureResponse); + } + }; + + /** Returns the object with the settings used for calls to echo. */ + public UnaryCallSettings echoSettings() { + return echoSettings; + } + + /** Returns the object with the settings used for calls to expand. */ + public ServerStreamingCallSettings expandSettings() { + return expandSettings; + } + + /** Returns the object with the settings used for calls to collect. */ + public StreamingCallSettings collectSettings() { + return collectSettings; + } + + /** Returns the object with the settings used for calls to chat. */ + public StreamingCallSettings chatSettings() { + return chatSettings; + } + + /** Returns the object with the settings used for calls to chatAgain. */ + public StreamingCallSettings chatAgainSettings() { + return chatAgainSettings; + } + + /** Returns the object with the settings used for calls to pagedExpand. */ + public PagedCallSettings + pagedExpandSettings() { + return pagedExpandSettings; + } + + /** Returns the object with the settings used for calls to wait. */ + public UnaryCallSettings waitSettings() { + return waitSettings; + } + + /** Returns the object with the settings used for calls to wait. */ + public OperationCallSettings waitOperationSettings() { + return waitOperationSettings; + } + + /** Returns the object with the settings used for calls to block. */ + public UnaryCallSettings blockSettings() { + return blockSettings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public EchoStub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(GrpcTransportChannel.getGrpcTransportName())) { + return GrpcEchoStub.create(this); + } + throw new UnsupportedOperationException( + String.format( + "Transport not supported: %s", getTransportChannelProvider().getTransportName())); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return InstantiatingExecutorProvider.newBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return "localhost:7469"; + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return DEFAULT_SERVICE_SCOPES; + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return InstantiatingGrpcChannelProvider.newBuilder() + .setMaxInboundMessageSize(Integer.MAX_VALUE); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return defaultGrpcTransportProviderBuilder().build(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return ApiClientHeaderProvider.newBuilder() + .setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(EchoStubSettings.class)) + .setTransportToken( + GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); + } + + /** Returns a new builder for this class. */ + public static Builder newBuilder() { + return Builder.createDefault(); + } + + /** Returns a new builder for this class. */ + public static Builder newBuilder(ClientContext clientContext) { + return new Builder(clientContext); + } + + /** Returns a builder containing all the values of this settings class. */ + public Builder toBuilder() { + return new Builder(this); + } + + protected EchoStubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + echoSettings = settingsBuilder.echoSettings().build(); + expandSettings = settingsBuilder.expandSettings().build(); + collectSettings = settingsBuilder.collectSettings().build(); + chatSettings = settingsBuilder.chatSettings().build(); + chatAgainSettings = settingsBuilder.chatAgainSettings().build(); + pagedExpandSettings = settingsBuilder.pagedExpandSettings().build(); + waitSettings = settingsBuilder.waitSettings().build(); + waitOperationSettings = settingsBuilder.waitOperationSettings().build(); + blockSettings = settingsBuilder.blockSettings().build(); + } + + /** Builder for EchoStubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final UnaryCallSettings.Builder echoSettings; + private final ServerStreamingCallSettings.Builder expandSettings; + private final StreamingCallSettings.Builder collectSettings; + private final StreamingCallSettings.Builder chatSettings; + private final StreamingCallSettings.Builder chatAgainSettings; + private final PagedCallSettings.Builder< + PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse> + pagedExpandSettings; + private final UnaryCallSettings.Builder waitSettings; + private final OperationCallSettings.Builder + waitOperationSettings; + private final UnaryCallSettings.Builder blockSettings; + private static final ImmutableMap> + RETRYABLE_CODE_DEFINITIONS; + + static { + ImmutableMap.Builder> definitions = + ImmutableMap.builder(); + definitions.put( + "retry_policy_1_codes", + ImmutableSet.copyOf( + Lists.newArrayList( + StatusCode.Code.UNAVAILABLE, StatusCode.Code.UNKNOWN))); + definitions.put( + "no_retry_0_codes", ImmutableSet.copyOf(Lists.newArrayList())); + RETRYABLE_CODE_DEFINITIONS = definitions.build(); + } + + private static final ImmutableMap RETRY_PARAM_DEFINITIONS; + + static { + ImmutableMap.Builder definitions = ImmutableMap.builder(); + RetrySettings settings = null; + settings = + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(100L)) + .setRetryDelayMultiplier(2.0) + .setMaxRetryDelay(Duration.ofMillis(3000L)) + .setInitialRpcTimeout(Duration.ofMillis(10000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(10000L)) + .setTotalTimeout(Duration.ofMillis(10000L)) + .build(); + definitions.put("retry_policy_1_params", settings); + settings = + RetrySettings.newBuilder() + .setInitialRpcTimeout(Duration.ofMillis(5000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(5000L)) + .setTotalTimeout(Duration.ofMillis(5000L)) + .build(); + definitions.put("no_retry_0_params", settings); + RETRY_PARAM_DEFINITIONS = definitions.build(); + } + + protected Builder() { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(clientContext); + echoSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + expandSettings = ServerStreamingCallSettings.newBuilder(); + collectSettings = StreamingCallSettings.newBuilder(); + chatSettings = StreamingCallSettings.newBuilder(); + chatAgainSettings = StreamingCallSettings.newBuilder(); + pagedExpandSettings = PagedCallSettings.newBuilder(PAGED_EXPAND_PAGE_STR_FACT); + waitSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + waitOperationSettings = OperationCallSettings.newBuilder(); + blockSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + unaryMethodSettingsBuilders = + ImmutableList.>of( + echoSettings, pagedExpandSettings, waitSettings, blockSettings); + initDefaults(this); + } + + protected Builder(EchoStubSettings settings) { + super(settings); + echoSettings = settings.echoSettings.toBuilder(); + expandSettings = settings.expandSettings.toBuilder(); + collectSettings = settings.collectSettings.toBuilder(); + chatSettings = settings.chatSettings.toBuilder(); + chatAgainSettings = settings.chatAgainSettings.toBuilder(); + pagedExpandSettings = settings.pagedExpandSettings.toBuilder(); + waitSettings = settings.waitSettings.toBuilder(); + waitOperationSettings = settings.waitOperationSettings.toBuilder(); + blockSettings = settings.blockSettings.toBuilder(); + unaryMethodSettingsBuilders = + ImmutableList.>of( + echoSettings, pagedExpandSettings, waitSettings, blockSettings); + } + + private static Builder createDefault() { + Builder builder = new Builder(((ClientContext) null)); + builder.setTransportChannelProvider(defaultTransportChannelProvider()); + builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); + builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); + builder.setEndpoint(getDefaultEndpoint()); + return initDefaults(builder); + } + + private static Builder initDefaults(Builder builder) { + builder + .echoSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + builder + .expandSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + builder + .pagedExpandSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + builder + .waitSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); + builder + .blockSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); + builder + .waitOperationSettings() + .setInitialCallSettings( + UnaryCallSettings.newUnaryCallSettingsBuilder() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")) + .build()) + .setResponseTransformer( + ProtoOperationTransformers.ResponseTransformer.create(WaitResponse.class)) + .setMetadataTransformer( + ProtoOperationTransformers.MetadataTransformer.create(WaitMetadata.class)) + .setPollingAlgorithm( + OperationTimedPollAlgorithm.create( + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(500L)) + .setRetryDelayMultiplier(1.5) + .setMaxRetryDelay(Duration.ofMillis(5000L)) + .setInitialRpcTimeout(Duration.ZERO) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ZERO) + .setTotalTimeout(Duration.ofMillis(300000L)) + .build())); + return builder; + } + + // NEXT_MAJOR_VER: remove 'throws Exception'. + /** + * Applies the given settings updater function to all of the unary API methods in this service. + * + *

Note: This method does not support applying settings to streaming methods. + */ + public Builder applyToAllUnaryMethods( + ApiFunction, Void> settingsUpdater) throws Exception { + super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); + return this; + } + + public ImmutableList> unaryMethodSettingsBuilders() { + return unaryMethodSettingsBuilders; + } + + /** Returns the builder for the settings used for calls to echo. */ + public UnaryCallSettings.Builder echoSettings() { + return echoSettings; + } + + /** Returns the builder for the settings used for calls to expand. */ + public ServerStreamingCallSettings.Builder expandSettings() { + return expandSettings; + } + + /** Returns the builder for the settings used for calls to collect. */ + public StreamingCallSettings.Builder collectSettings() { + return collectSettings; + } + + /** Returns the builder for the settings used for calls to chat. */ + public StreamingCallSettings.Builder chatSettings() { + return chatSettings; + } + + /** Returns the builder for the settings used for calls to chatAgain. */ + public StreamingCallSettings.Builder chatAgainSettings() { + return chatAgainSettings; + } + + /** Returns the builder for the settings used for calls to pagedExpand. */ + public PagedCallSettings.Builder< + PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse> + pagedExpandSettings() { + return pagedExpandSettings; + } + + /** Returns the builder for the settings used for calls to wait. */ + public UnaryCallSettings.Builder waitSettings() { + return waitSettings; + } + + /** Returns the builder for the settings used for calls to wait. */ + @BetaApi( + "The surface for use by generated code is not stable yet and may change in the future.") + public OperationCallSettings.Builder + waitOperationSettings() { + return waitOperationSettings; + } + + /** Returns the builder for the settings used for calls to block. */ + public UnaryCallSettings.Builder blockSettings() { + return blockSettings; + } + + @Override + public EchoStubSettings build() throws IOException { + return new EchoStubSettings(this); + } + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestLogging.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestLogging.golden new file mode 100644 index 0000000000..770d6f49be --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestLogging.golden @@ -0,0 +1,649 @@ +package com.google.logging.v2.stub; + +import static com.google.logging.v2.LoggingServiceV2Client.ListLogEntriesPagedResponse; +import static com.google.logging.v2.LoggingServiceV2Client.ListLogsPagedResponse; +import static com.google.logging.v2.LoggingServiceV2Client.ListMonitoredResourceDescriptorsPagedResponse; + +import com.google.api.MonitoredResourceDescriptor; +import com.google.api.core.ApiFunction; +import com.google.api.core.ApiFuture; +import com.google.api.core.BetaApi; +import com.google.api.gax.batching.BatchingSettings; +import com.google.api.gax.batching.FlowControlSettings; +import com.google.api.gax.batching.FlowController; +import com.google.api.gax.batching.PartitionKey; +import com.google.api.gax.batching.RequestBuilder; +import com.google.api.gax.core.GaxProperties; +import com.google.api.gax.core.GoogleCredentialsProvider; +import com.google.api.gax.core.InstantiatingExecutorProvider; +import com.google.api.gax.grpc.GaxGrpcProperties; +import com.google.api.gax.grpc.GrpcTransportChannel; +import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiCallContext; +import com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.BatchedRequestIssuer; +import com.google.api.gax.rpc.BatchingCallSettings; +import com.google.api.gax.rpc.BatchingDescriptor; +import com.google.api.gax.rpc.ClientContext; +import com.google.api.gax.rpc.PageContext; +import com.google.api.gax.rpc.PagedCallSettings; +import com.google.api.gax.rpc.PagedListDescriptor; +import com.google.api.gax.rpc.PagedListResponseFactory; +import com.google.api.gax.rpc.StatusCode; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.logging.v2.DeleteLogRequest; +import com.google.logging.v2.ListLogEntriesRequest; +import com.google.logging.v2.ListLogEntriesResponse; +import com.google.logging.v2.ListLogsRequest; +import com.google.logging.v2.ListLogsResponse; +import com.google.logging.v2.ListMonitoredResourceDescriptorsRequest; +import com.google.logging.v2.ListMonitoredResourceDescriptorsResponse; +import com.google.logging.v2.LogEntry; +import com.google.logging.v2.WriteLogEntriesRequest; +import com.google.logging.v2.WriteLogEntriesResponse; +import com.google.protobuf.Empty; +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import javax.annotation.Generated; +import org.threeten.bp.Duration; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link LoggingServiceV2Stub}. + * + *

The default instance has everything set to sensible defaults: + * + *

    + *
  • The default service address (logging.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
+ * + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. + * + *

For example, to set the total timeout of deleteLog to 30 seconds: + */ +@BetaApi +@Generated("by gapic-generator-java") +public class LoggingServiceV2StubSettings extends StubSettings { + /** The default scopes of the service. */ + private static final ImmutableList DEFAULT_SERVICE_SCOPES = + ImmutableList.builder() + .add("https://www.googleapis.com/auth/cloud-platform") + .add("https://www.googleapis.com/auth/cloud-platform.read-only") + .add("https://www.googleapis.com/auth/logging.admin") + .add("https://www.googleapis.com/auth/logging.read") + .add("https://www.googleapis.com/auth/logging.write") + .build(); + + private final UnaryCallSettings deleteLogSettings; + private final BatchingCallSettings + writeLogEntriesSettings; + private final PagedCallSettings< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> + listLogEntriesSettings; + private final PagedCallSettings< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse> + listMonitoredResourceDescriptorsSettings; + private final PagedCallSettings + listLogsSettings; + private static final PagedListDescriptor + LIST_LOG_ENTRIES_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListLogEntriesRequest injectToken(ListLogEntriesRequest payload, String token) { + return ListLogEntriesRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListLogEntriesRequest injectPageSize( + ListLogEntriesRequest payload, int pageSize) { + return ListLogEntriesRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListLogEntriesRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListLogEntriesResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListLogEntriesResponse payload) { + return Objects.equals(payload.getResponsesList(), null) + ? ImmutableList.of() + : payload.getResponsesList(); + } + }; + private static final PagedListDescriptor< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor> + LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC = + new PagedListDescriptor< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor>() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListMonitoredResourceDescriptorsRequest injectToken( + ListMonitoredResourceDescriptorsRequest payload, String token) { + return ListMonitoredResourceDescriptorsRequest.newBuilder(payload) + .setPageToken(token) + .build(); + } + + @Override + public ListMonitoredResourceDescriptorsRequest injectPageSize( + ListMonitoredResourceDescriptorsRequest payload, int pageSize) { + return ListMonitoredResourceDescriptorsRequest.newBuilder(payload) + .setPageSize(pageSize) + .build(); + } + + @Override + public Integer extractPageSize(ListMonitoredResourceDescriptorsRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListMonitoredResourceDescriptorsResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources( + ListMonitoredResourceDescriptorsResponse payload) { + return Objects.equals(payload.getResponsesList(), null) + ? ImmutableList.of() + : payload.getResponsesList(); + } + }; + private static final PagedListDescriptor + LIST_LOGS_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListLogsRequest injectToken(ListLogsRequest payload, String token) { + return ListLogsRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListLogsRequest injectPageSize(ListLogsRequest payload, int pageSize) { + return ListLogsRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListLogsRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListLogsResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListLogsResponse payload) { + return Objects.equals(payload.getResponsesList(), null) + ? ImmutableList.of() + : payload.getResponsesList(); + } + }; + private static final PagedListResponseFactory< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> + LIST_LOG_ENTRIES_PAGE_STR_FACT = + new PagedListResponseFactory< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListLogEntriesRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, LIST_LOG_ENTRIES_PAGE_STR_DESC, request, context); + return ListLogEntriesPagedResponse.createAsync(pageContext, futureResponse); + } + }; + private static final PagedListResponseFactory< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse> + LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse> + callable, + ListMonitoredResourceDescriptorsRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor> + pageContext = + PageContext.create( + callable, + LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC, + request, + context); + return ListMonitoredResourceDescriptorsPagedResponse.createAsync( + pageContext, futureResponse); + } + }; + private static final PagedListResponseFactory< + ListLogsRequest, ListLogsResponse, ListLogsPagedResponse> + LIST_LOGS_PAGE_STR_FACT = + new PagedListResponseFactory() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListLogsRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, LIST_LOGS_PAGE_STR_DESC, request, context); + return ListLogsPagedResponse.createAsync(pageContext, futureResponse); + } + }; + private static final BatchingDescriptor + WRITE_LOG_ENTRIES_BATCHING_DESC = + new BatchingDescriptor() { + @Override + public PartitionKey getBatchPartitionKey(WriteLogEntriesRequest request) { + return new PartitionKey( + request.getLogName(), request.getResource(), request.getLabels()); + } + + @Override + public RequestBuilder getRequestBuilder() { + return new RequestBuilder() { + private RequestBuilder builder; + + @Override + public void appendRequest(WriteLogEntriesRequest request) { + if (Objects.isNull(builder)) { + builder = request.toBuilder(); + } else { + builder.addAllEntries(request.getEntriesList()); + } + } + + @Override + public WriteLogEntriesRequest build() { + return builder.build(); + } + }; + } + + @Override + public void splitResponse( + WriteLogEntriesResponse batchResponse, + Collection> batch) { + for (BatchedRequestIssuer responder : batch) { + WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); + responder.setResponse(response); + } + } + + @Override + public void splitException( + Throwable throwable, + Collection> batch) { + for (BatchedRequestIssuer responder : batch) { + responder.setException(throwable); + } + } + + @Override + public long countElements(WriteLogEntriesRequest request) { + return request.getEntriesCount(); + } + + @Override + public long countBytes(WriteLogEntriesRequest request) { + return request.getSerializedSize(); + } + }; + + /** Returns the object with the settings used for calls to deleteLog. */ + public UnaryCallSettings deleteLogSettings() { + return deleteLogSettings; + } + + /** Returns the object with the settings used for calls to writeLogEntries. */ + public BatchingCallSettings + writeLogEntriesSettings() { + return writeLogEntriesSettings; + } + + /** Returns the object with the settings used for calls to listLogEntries. */ + public PagedCallSettings< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> + listLogEntriesSettings() { + return listLogEntriesSettings; + } + + /** Returns the object with the settings used for calls to listMonitoredResourceDescriptors. */ + public PagedCallSettings< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse> + listMonitoredResourceDescriptorsSettings() { + return listMonitoredResourceDescriptorsSettings; + } + + /** Returns the object with the settings used for calls to listLogs. */ + public PagedCallSettings + listLogsSettings() { + return listLogsSettings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public LoggingServiceV2Stub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(GrpcTransportChannel.getGrpcTransportName())) { + return GrpcLoggingServiceV2Stub.create(this); + } + throw new UnsupportedOperationException( + String.format( + "Transport not supported: %s", getTransportChannelProvider().getTransportName())); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return InstantiatingExecutorProvider.newBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return "logging.googleapis.com:443"; + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return DEFAULT_SERVICE_SCOPES; + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return InstantiatingGrpcChannelProvider.newBuilder() + .setMaxInboundMessageSize(Integer.MAX_VALUE); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return defaultGrpcTransportProviderBuilder().build(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return ApiClientHeaderProvider.newBuilder() + .setGeneratedLibToken( + "gapic", GaxProperties.getLibraryVersion(LoggingServiceV2StubSettings.class)) + .setTransportToken( + GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); + } + + /** Returns a new builder for this class. */ + public static Builder newBuilder() { + return Builder.createDefault(); + } + + /** Returns a new builder for this class. */ + public static Builder newBuilder(ClientContext clientContext) { + return new Builder(clientContext); + } + + /** Returns a builder containing all the values of this settings class. */ + public Builder toBuilder() { + return new Builder(this); + } + + protected LoggingServiceV2StubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + deleteLogSettings = settingsBuilder.deleteLogSettings().build(); + writeLogEntriesSettings = settingsBuilder.writeLogEntriesSettings().build(); + listLogEntriesSettings = settingsBuilder.listLogEntriesSettings().build(); + listMonitoredResourceDescriptorsSettings = + settingsBuilder.listMonitoredResourceDescriptorsSettings().build(); + listLogsSettings = settingsBuilder.listLogsSettings().build(); + } + + /** Builder for LoggingServiceV2StubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final UnaryCallSettings.Builder deleteLogSettings; + private final BatchingCallSettings.Builder + writeLogEntriesSettings; + private final PagedCallSettings.Builder< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> + listLogEntriesSettings; + private final PagedCallSettings.Builder< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse> + listMonitoredResourceDescriptorsSettings; + private final PagedCallSettings.Builder< + ListLogsRequest, ListLogsResponse, ListLogsPagedResponse> + listLogsSettings; + private static final ImmutableMap> + RETRYABLE_CODE_DEFINITIONS; + + static { + ImmutableMap.Builder> definitions = + ImmutableMap.builder(); + definitions.put( + "retry_policy_1_codes", + ImmutableSet.copyOf( + Lists.newArrayList( + StatusCode.Code.DEADLINE_EXCEEDED, + StatusCode.Code.INTERNAL, + StatusCode.Code.UNAVAILABLE))); + RETRYABLE_CODE_DEFINITIONS = definitions.build(); + } + + private static final ImmutableMap RETRY_PARAM_DEFINITIONS; + + static { + ImmutableMap.Builder definitions = ImmutableMap.builder(); + RetrySettings settings = null; + settings = + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(100L)) + .setRetryDelayMultiplier(1.3) + .setMaxRetryDelay(Duration.ofMillis(60000L)) + .setInitialRpcTimeout(Duration.ofMillis(60000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(60000L)) + .setTotalTimeout(Duration.ofMillis(60000L)) + .build(); + definitions.put("retry_policy_1_params", settings); + RETRY_PARAM_DEFINITIONS = definitions.build(); + } + + protected Builder() { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(clientContext); + deleteLogSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + writeLogEntriesSettings = + BatchingCallSettings.newBuilder(WRITE_LOG_ENTRIES_BATCHING_DESC) + .setBatchingSettings(BatchingSettings.newBuilder().build()); + listLogEntriesSettings = PagedCallSettings.newBuilder(LIST_LOG_ENTRIES_PAGE_STR_FACT); + listMonitoredResourceDescriptorsSettings = + PagedCallSettings.newBuilder(LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_FACT); + listLogsSettings = PagedCallSettings.newBuilder(LIST_LOGS_PAGE_STR_FACT); + unaryMethodSettingsBuilders = + ImmutableList.>of( + deleteLogSettings, + writeLogEntriesSettings, + listLogEntriesSettings, + listMonitoredResourceDescriptorsSettings, + listLogsSettings); + initDefaults(this); + } + + protected Builder(LoggingServiceV2StubSettings settings) { + super(settings); + deleteLogSettings = settings.deleteLogSettings.toBuilder(); + writeLogEntriesSettings = settings.writeLogEntriesSettings.toBuilder(); + listLogEntriesSettings = settings.listLogEntriesSettings.toBuilder(); + listMonitoredResourceDescriptorsSettings = + settings.listMonitoredResourceDescriptorsSettings.toBuilder(); + listLogsSettings = settings.listLogsSettings.toBuilder(); + unaryMethodSettingsBuilders = + ImmutableList.>of( + deleteLogSettings, + writeLogEntriesSettings, + listLogEntriesSettings, + listMonitoredResourceDescriptorsSettings, + listLogsSettings); + } + + private static Builder createDefault() { + Builder builder = new Builder(((ClientContext) null)); + builder.setTransportChannelProvider(defaultTransportChannelProvider()); + builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); + builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); + builder.setEndpoint(getDefaultEndpoint()); + return initDefaults(builder); + } + + private static Builder initDefaults(Builder builder) { + builder + .deleteLogSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + builder + .writeLogEntriesSettings() + .setBatchingSettings( + BatchingSettings.newBuilder() + .setElementCountThreshold(1000L) + .setRequestByteThreshold(1048576L) + .setDelayThreshold(Duration.ofMillis(50L)) + .setFlowControlSettings( + FlowControlSettings.newBuilder() + .setMaxOutstandingElementCount(100000L) + .setMaxOutstandingRequestBytes(10485760L) + .setLimitExceededBehavior( + FlowController.LimitExceededBehavior.ThrowException) + .build()) + .build()); + builder + .writeLogEntriesSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + builder + .listLogEntriesSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + builder + .listMonitoredResourceDescriptorsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + builder + .listLogsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + return builder; + } + + // NEXT_MAJOR_VER: remove 'throws Exception'. + /** + * Applies the given settings updater function to all of the unary API methods in this service. + * + *

Note: This method does not support applying settings to streaming methods. + */ + public Builder applyToAllUnaryMethods( + ApiFunction, Void> settingsUpdater) throws Exception { + super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); + return this; + } + + public ImmutableList> unaryMethodSettingsBuilders() { + return unaryMethodSettingsBuilders; + } + + /** Returns the builder for the settings used for calls to deleteLog. */ + public UnaryCallSettings.Builder deleteLogSettings() { + return deleteLogSettings; + } + + /** Returns the builder for the settings used for calls to writeLogEntries. */ + public BatchingCallSettings.Builder + writeLogEntriesSettings() { + return writeLogEntriesSettings; + } + + /** Returns the builder for the settings used for calls to listLogEntries. */ + public PagedCallSettings.Builder< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> + listLogEntriesSettings() { + return listLogEntriesSettings; + } + + /** Returns the builder for the settings used for calls to listMonitoredResourceDescriptors. */ + public PagedCallSettings.Builder< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse> + listMonitoredResourceDescriptorsSettings() { + return listMonitoredResourceDescriptorsSettings; + } + + /** Returns the builder for the settings used for calls to listLogs. */ + public PagedCallSettings.Builder + listLogsSettings() { + return listLogsSettings; + } + + @Override + public LoggingServiceV2StubSettings build() throws IOException { + return new LoggingServiceV2StubSettings(this); + } + } +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestPublisher.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestPublisher.golden new file mode 100644 index 0000000000..7bc74092f4 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestPublisher.golden @@ -0,0 +1,758 @@ +package com.google.pubsub.v1.stub; + +import static com.google.pubsub.v1.PublisherClient.ListTopicSnapshotsPagedResponse; +import static com.google.pubsub.v1.PublisherClient.ListTopicSubscriptionsPagedResponse; +import static com.google.pubsub.v1.PublisherClient.ListTopicsPagedResponse; + +import com.google.api.core.ApiFunction; +import com.google.api.core.ApiFuture; +import com.google.api.core.BetaApi; +import com.google.api.gax.batching.BatchingSettings; +import com.google.api.gax.batching.FlowControlSettings; +import com.google.api.gax.batching.FlowController; +import com.google.api.gax.batching.PartitionKey; +import com.google.api.gax.batching.RequestBuilder; +import com.google.api.gax.core.GaxProperties; +import com.google.api.gax.core.GoogleCredentialsProvider; +import com.google.api.gax.core.InstantiatingExecutorProvider; +import com.google.api.gax.grpc.GaxGrpcProperties; +import com.google.api.gax.grpc.GrpcTransportChannel; +import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiCallContext; +import com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.BatchedRequestIssuer; +import com.google.api.gax.rpc.BatchingCallSettings; +import com.google.api.gax.rpc.BatchingDescriptor; +import com.google.api.gax.rpc.ClientContext; +import com.google.api.gax.rpc.PageContext; +import com.google.api.gax.rpc.PagedCallSettings; +import com.google.api.gax.rpc.PagedListDescriptor; +import com.google.api.gax.rpc.PagedListResponseFactory; +import com.google.api.gax.rpc.StatusCode; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.DeleteTopicRequest; +import com.google.pubsub.v1.DetachSubscriptionRequest; +import com.google.pubsub.v1.DetachSubscriptionResponse; +import com.google.pubsub.v1.GetTopicRequest; +import com.google.pubsub.v1.ListTopicSnapshotsRequest; +import com.google.pubsub.v1.ListTopicSnapshotsResponse; +import com.google.pubsub.v1.ListTopicSubscriptionsRequest; +import com.google.pubsub.v1.ListTopicSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ListTopicsResponse; +import com.google.pubsub.v1.PublishRequest; +import com.google.pubsub.v1.PublishResponse; +import com.google.pubsub.v1.Topic; +import com.google.pubsub.v1.UpdateTopicRequest; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import javax.annotation.Generated; +import org.threeten.bp.Duration; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link PublisherStub}. + * + *

The default instance has everything set to sensible defaults: + * + *

    + *
  • The default service address (pubsub.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
+ * + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. + * + *

For example, to set the total timeout of createTopic to 30 seconds: + */ +@BetaApi +@Generated("by gapic-generator-java") +public class PublisherStubSettings extends StubSettings { + /** The default scopes of the service. */ + private static final ImmutableList DEFAULT_SERVICE_SCOPES = + ImmutableList.builder() + .add("https://www.googleapis.com/auth/cloud-platform") + .add("https://www.googleapis.com/auth/pubsub") + .build(); + + private final UnaryCallSettings createTopicSettings; + private final UnaryCallSettings updateTopicSettings; + private final BatchingCallSettings publishSettings; + private final UnaryCallSettings getTopicSettings; + private final PagedCallSettings + listTopicsSettings; + private final PagedCallSettings< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> + listTopicSubscriptionsSettings; + private final PagedCallSettings< + ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, ListTopicSnapshotsPagedResponse> + listTopicSnapshotsSettings; + private final UnaryCallSettings deleteTopicSettings; + private final UnaryCallSettings + detachSubscriptionSettings; + private static final PagedListDescriptor + LIST_TOPICS_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListTopicsRequest injectToken(ListTopicsRequest payload, String token) { + return ListTopicsRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListTopicsRequest injectPageSize(ListTopicsRequest payload, int pageSize) { + return ListTopicsRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListTopicsRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListTopicsResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListTopicsResponse payload) { + return Objects.equals(payload.getResponsesList(), null) + ? ImmutableList.of() + : payload.getResponsesList(); + } + }; + private static final PagedListDescriptor< + ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String> + LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_DESC = + new PagedListDescriptor< + ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String>() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListTopicSubscriptionsRequest injectToken( + ListTopicSubscriptionsRequest payload, String token) { + return ListTopicSubscriptionsRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListTopicSubscriptionsRequest injectPageSize( + ListTopicSubscriptionsRequest payload, int pageSize) { + return ListTopicSubscriptionsRequest.newBuilder(payload) + .setPageSize(pageSize) + .build(); + } + + @Override + public Integer extractPageSize(ListTopicSubscriptionsRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListTopicSubscriptionsResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListTopicSubscriptionsResponse payload) { + return Objects.equals(payload.getResponsesList(), null) + ? ImmutableList.of() + : payload.getResponsesList(); + } + }; + private static final PagedListDescriptor< + ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, String> + LIST_TOPIC_SNAPSHOTS_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListTopicSnapshotsRequest injectToken( + ListTopicSnapshotsRequest payload, String token) { + return ListTopicSnapshotsRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListTopicSnapshotsRequest injectPageSize( + ListTopicSnapshotsRequest payload, int pageSize) { + return ListTopicSnapshotsRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListTopicSnapshotsRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListTopicSnapshotsResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListTopicSnapshotsResponse payload) { + return Objects.equals(payload.getResponsesList(), null) + ? ImmutableList.of() + : payload.getResponsesList(); + } + }; + private static final PagedListResponseFactory< + ListTopicsRequest, ListTopicsResponse, ListTopicsPagedResponse> + LIST_TOPICS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListTopicsRequest, ListTopicsResponse, ListTopicsPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListTopicsRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, LIST_TOPICS_PAGE_STR_DESC, request, context); + return ListTopicsPagedResponse.createAsync(pageContext, futureResponse); + } + }; + private static final PagedListResponseFactory< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> + LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable + callable, + ListTopicSubscriptionsRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext + pageContext = + PageContext.create( + callable, LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_DESC, request, context); + return ListTopicSubscriptionsPagedResponse.createAsync(pageContext, futureResponse); + } + }; + private static final PagedListResponseFactory< + ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, ListTopicSnapshotsPagedResponse> + LIST_TOPIC_SNAPSHOTS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListTopicSnapshotsRequest, + ListTopicSnapshotsResponse, + ListTopicSnapshotsPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListTopicSnapshotsRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext + pageContext = + PageContext.create( + callable, LIST_TOPIC_SNAPSHOTS_PAGE_STR_DESC, request, context); + return ListTopicSnapshotsPagedResponse.createAsync(pageContext, futureResponse); + } + }; + private static final BatchingDescriptor PUBLISH_BATCHING_DESC = + new BatchingDescriptor() { + @Override + public PartitionKey getBatchPartitionKey(PublishRequest request) { + return new PartitionKey(request.getTopic()); + } + + @Override + public RequestBuilder getRequestBuilder() { + return new RequestBuilder() { + private RequestBuilder builder; + + @Override + public void appendRequest(PublishRequest request) { + if (Objects.isNull(builder)) { + builder = request.toBuilder(); + } else { + builder.addAllMessages(request.getMessagesList()); + } + } + + @Override + public PublishRequest build() { + return builder.build(); + } + }; + } + + @Override + public void splitResponse( + PublishResponse batchResponse, + Collection> batch) { + int batchMessageIndex = 0; + for (BatchedRequestIssuer responder : batch) { + List subresponseElements = new ArrayList<>(); + long subresponseCount = responder.getMessageCount(); + for (int i = 0; i < subresponseCount; i++) { + subresponseElements.add(batchResponse.getMessageIds(batchMessageIndex)); + } + PublishResponse response = + PublishResponse.newBuilder().addAllMessageIds(subresponseElements).build(); + responder.setResponse(response); + } + } + + @Override + public void splitException( + Throwable throwable, + Collection> batch) { + for (BatchedRequestIssuer responder : batch) { + responder.setException(throwable); + } + } + + @Override + public long countElements(PublishRequest request) { + return request.getMessagesCount(); + } + + @Override + public long countBytes(PublishRequest request) { + return request.getSerializedSize(); + } + }; + + /** Returns the object with the settings used for calls to createTopic. */ + public UnaryCallSettings createTopicSettings() { + return createTopicSettings; + } + + /** Returns the object with the settings used for calls to updateTopic. */ + public UnaryCallSettings updateTopicSettings() { + return updateTopicSettings; + } + + /** Returns the object with the settings used for calls to publish. */ + public BatchingCallSettings publishSettings() { + return publishSettings; + } + + /** Returns the object with the settings used for calls to getTopic. */ + public UnaryCallSettings getTopicSettings() { + return getTopicSettings; + } + + /** Returns the object with the settings used for calls to listTopics. */ + public PagedCallSettings + listTopicsSettings() { + return listTopicsSettings; + } + + /** Returns the object with the settings used for calls to listTopicSubscriptions. */ + public PagedCallSettings< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> + listTopicSubscriptionsSettings() { + return listTopicSubscriptionsSettings; + } + + /** Returns the object with the settings used for calls to listTopicSnapshots. */ + public PagedCallSettings< + ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, ListTopicSnapshotsPagedResponse> + listTopicSnapshotsSettings() { + return listTopicSnapshotsSettings; + } + + /** Returns the object with the settings used for calls to deleteTopic. */ + public UnaryCallSettings deleteTopicSettings() { + return deleteTopicSettings; + } + + /** Returns the object with the settings used for calls to detachSubscription. */ + public UnaryCallSettings + detachSubscriptionSettings() { + return detachSubscriptionSettings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public PublisherStub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(GrpcTransportChannel.getGrpcTransportName())) { + return GrpcPublisherStub.create(this); + } + throw new UnsupportedOperationException( + String.format( + "Transport not supported: %s", getTransportChannelProvider().getTransportName())); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return InstantiatingExecutorProvider.newBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return "pubsub.googleapis.com:443"; + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return DEFAULT_SERVICE_SCOPES; + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return InstantiatingGrpcChannelProvider.newBuilder() + .setMaxInboundMessageSize(Integer.MAX_VALUE); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return defaultGrpcTransportProviderBuilder().build(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return ApiClientHeaderProvider.newBuilder() + .setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(PublisherStubSettings.class)) + .setTransportToken( + GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); + } + + /** Returns a new builder for this class. */ + public static Builder newBuilder() { + return Builder.createDefault(); + } + + /** Returns a new builder for this class. */ + public static Builder newBuilder(ClientContext clientContext) { + return new Builder(clientContext); + } + + /** Returns a builder containing all the values of this settings class. */ + public Builder toBuilder() { + return new Builder(this); + } + + protected PublisherStubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + createTopicSettings = settingsBuilder.createTopicSettings().build(); + updateTopicSettings = settingsBuilder.updateTopicSettings().build(); + publishSettings = settingsBuilder.publishSettings().build(); + getTopicSettings = settingsBuilder.getTopicSettings().build(); + listTopicsSettings = settingsBuilder.listTopicsSettings().build(); + listTopicSubscriptionsSettings = settingsBuilder.listTopicSubscriptionsSettings().build(); + listTopicSnapshotsSettings = settingsBuilder.listTopicSnapshotsSettings().build(); + deleteTopicSettings = settingsBuilder.deleteTopicSettings().build(); + detachSubscriptionSettings = settingsBuilder.detachSubscriptionSettings().build(); + } + + /** Builder for PublisherStubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final UnaryCallSettings.Builder createTopicSettings; + private final UnaryCallSettings.Builder updateTopicSettings; + private final BatchingCallSettings.Builder publishSettings; + private final UnaryCallSettings.Builder getTopicSettings; + private final PagedCallSettings.Builder< + ListTopicsRequest, ListTopicsResponse, ListTopicsPagedResponse> + listTopicsSettings; + private final PagedCallSettings.Builder< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> + listTopicSubscriptionsSettings; + private final PagedCallSettings.Builder< + ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, ListTopicSnapshotsPagedResponse> + listTopicSnapshotsSettings; + private final UnaryCallSettings.Builder deleteTopicSettings; + private final UnaryCallSettings.Builder + detachSubscriptionSettings; + private static final ImmutableMap> + RETRYABLE_CODE_DEFINITIONS; + + static { + ImmutableMap.Builder> definitions = + ImmutableMap.builder(); + definitions.put( + "retry_policy_0_codes", + ImmutableSet.copyOf(Lists.newArrayList(StatusCode.Code.UNAVAILABLE))); + definitions.put( + "retry_policy_1_codes", + ImmutableSet.copyOf( + Lists.newArrayList( + StatusCode.Code.ABORTED, + StatusCode.Code.CANCELLED, + StatusCode.Code.INTERNAL, + StatusCode.Code.RESOURCE_EXHAUSTED, + StatusCode.Code.UNKNOWN, + StatusCode.Code.UNAVAILABLE, + StatusCode.Code.DEADLINE_EXCEEDED))); + definitions.put( + "retry_policy_2_codes", + ImmutableSet.copyOf( + Lists.newArrayList( + StatusCode.Code.UNKNOWN, StatusCode.Code.ABORTED, StatusCode.Code.UNAVAILABLE))); + RETRYABLE_CODE_DEFINITIONS = definitions.build(); + } + + private static final ImmutableMap RETRY_PARAM_DEFINITIONS; + + static { + ImmutableMap.Builder definitions = ImmutableMap.builder(); + RetrySettings settings = null; + settings = + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(100L)) + .setRetryDelayMultiplier(1.3) + .setMaxRetryDelay(Duration.ofMillis(60000L)) + .setInitialRpcTimeout(Duration.ofMillis(60000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(60000L)) + .setTotalTimeout(Duration.ofMillis(60000L)) + .build(); + definitions.put("retry_policy_0_params", settings); + settings = + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(100L)) + .setRetryDelayMultiplier(1.3) + .setMaxRetryDelay(Duration.ofMillis(60000L)) + .setInitialRpcTimeout(Duration.ofMillis(60000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(60000L)) + .setTotalTimeout(Duration.ofMillis(60000L)) + .build(); + definitions.put("retry_policy_1_params", settings); + settings = + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(100L)) + .setRetryDelayMultiplier(1.3) + .setMaxRetryDelay(Duration.ofMillis(60000L)) + .setInitialRpcTimeout(Duration.ofMillis(60000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(60000L)) + .setTotalTimeout(Duration.ofMillis(60000L)) + .build(); + definitions.put("retry_policy_2_params", settings); + RETRY_PARAM_DEFINITIONS = definitions.build(); + } + + protected Builder() { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(clientContext); + createTopicSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + updateTopicSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + publishSettings = + BatchingCallSettings.newBuilder(PUBLISH_BATCHING_DESC) + .setBatchingSettings(BatchingSettings.newBuilder().build()); + getTopicSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + listTopicsSettings = PagedCallSettings.newBuilder(LIST_TOPICS_PAGE_STR_FACT); + listTopicSubscriptionsSettings = + PagedCallSettings.newBuilder(LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_FACT); + listTopicSnapshotsSettings = PagedCallSettings.newBuilder(LIST_TOPIC_SNAPSHOTS_PAGE_STR_FACT); + deleteTopicSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + detachSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + unaryMethodSettingsBuilders = + ImmutableList.>of( + createTopicSettings, + updateTopicSettings, + publishSettings, + getTopicSettings, + listTopicsSettings, + listTopicSubscriptionsSettings, + listTopicSnapshotsSettings, + deleteTopicSettings, + detachSubscriptionSettings); + initDefaults(this); + } + + protected Builder(PublisherStubSettings settings) { + super(settings); + createTopicSettings = settings.createTopicSettings.toBuilder(); + updateTopicSettings = settings.updateTopicSettings.toBuilder(); + publishSettings = settings.publishSettings.toBuilder(); + getTopicSettings = settings.getTopicSettings.toBuilder(); + listTopicsSettings = settings.listTopicsSettings.toBuilder(); + listTopicSubscriptionsSettings = settings.listTopicSubscriptionsSettings.toBuilder(); + listTopicSnapshotsSettings = settings.listTopicSnapshotsSettings.toBuilder(); + deleteTopicSettings = settings.deleteTopicSettings.toBuilder(); + detachSubscriptionSettings = settings.detachSubscriptionSettings.toBuilder(); + unaryMethodSettingsBuilders = + ImmutableList.>of( + createTopicSettings, + updateTopicSettings, + publishSettings, + getTopicSettings, + listTopicsSettings, + listTopicSubscriptionsSettings, + listTopicSnapshotsSettings, + deleteTopicSettings, + detachSubscriptionSettings); + } + + private static Builder createDefault() { + Builder builder = new Builder(((ClientContext) null)); + builder.setTransportChannelProvider(defaultTransportChannelProvider()); + builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); + builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); + builder.setEndpoint(getDefaultEndpoint()); + return initDefaults(builder); + } + + private static Builder initDefaults(Builder builder) { + builder + .createTopicSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); + builder + .updateTopicSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); + builder + .publishSettings() + .setBatchingSettings( + BatchingSettings.newBuilder() + .setElementCountThreshold(100L) + .setRequestByteThreshold(1048576L) + .setDelayThreshold(Duration.ofMillis(10L)) + .setFlowControlSettings( + FlowControlSettings.newBuilder() + .setLimitExceededBehavior(FlowController.LimitExceededBehavior.Ignore) + .build()) + .build()); + builder + .publishSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + builder + .getTopicSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_2_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_2_params")); + builder + .listTopicsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_2_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_2_params")); + builder + .listTopicSubscriptionsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_2_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_2_params")); + builder + .listTopicSnapshotsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_2_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_2_params")); + builder + .deleteTopicSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); + builder + .detachSubscriptionSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); + return builder; + } + + // NEXT_MAJOR_VER: remove 'throws Exception'. + /** + * Applies the given settings updater function to all of the unary API methods in this service. + * + *

Note: This method does not support applying settings to streaming methods. + */ + public Builder applyToAllUnaryMethods( + ApiFunction, Void> settingsUpdater) throws Exception { + super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); + return this; + } + + public ImmutableList> unaryMethodSettingsBuilders() { + return unaryMethodSettingsBuilders; + } + + /** Returns the builder for the settings used for calls to createTopic. */ + public UnaryCallSettings.Builder createTopicSettings() { + return createTopicSettings; + } + + /** Returns the builder for the settings used for calls to updateTopic. */ + public UnaryCallSettings.Builder updateTopicSettings() { + return updateTopicSettings; + } + + /** Returns the builder for the settings used for calls to publish. */ + public BatchingCallSettings.Builder publishSettings() { + return publishSettings; + } + + /** Returns the builder for the settings used for calls to getTopic. */ + public UnaryCallSettings.Builder getTopicSettings() { + return getTopicSettings; + } + + /** Returns the builder for the settings used for calls to listTopics. */ + public PagedCallSettings.Builder + listTopicsSettings() { + return listTopicsSettings; + } + + /** Returns the builder for the settings used for calls to listTopicSubscriptions. */ + public PagedCallSettings.Builder< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> + listTopicSubscriptionsSettings() { + return listTopicSubscriptionsSettings; + } + + /** Returns the builder for the settings used for calls to listTopicSnapshots. */ + public PagedCallSettings.Builder< + ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, ListTopicSnapshotsPagedResponse> + listTopicSnapshotsSettings() { + return listTopicSnapshotsSettings; + } + + /** Returns the builder for the settings used for calls to deleteTopic. */ + public UnaryCallSettings.Builder deleteTopicSettings() { + return deleteTopicSettings; + } + + /** Returns the builder for the settings used for calls to detachSubscription. */ + public UnaryCallSettings.Builder + detachSubscriptionSettings() { + return detachSubscriptionSettings; + } + + @Override + public PublisherStubSettings build() throws IOException { + return new PublisherStubSettings(this); + } + } +} From 424a2bf3d90a452a712efed97876a25453ef89bd Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Tue, 8 Sep 2020 14:58:36 -0700 Subject: [PATCH 04/16] format --- .../java/com/google/api/generator/gapic/composer/BUILD.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel index 943026628e..249b507e57 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel @@ -46,9 +46,9 @@ java_proto_library( name = test_name, srcs = ["{0}.java".format(test_name)], data = [ + "//src/test/java/com/google/api/generator/gapic/composer/goldens:goldens_files", "//src/test/java/com/google/api/generator/gapic/testdata:gapic_config_files", "//src/test/java/com/google/api/generator/gapic/testdata:service_config_files", - "//src/test/java/com/google/api/generator/gapic/composer/goldens:goldens_files", ], test_class = "com.google.api.generator.gapic.composer.{0}".format(test_name), deps = [ From c2b3e6d03ae43ea0034f2c77fae2b3260df228b6 Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Wed, 23 Sep 2020 22:47:27 +0000 Subject: [PATCH 05/16] update goldens --- .../api/generator/gapic/composer/BUILD.bazel | 1 + .../BatchingDescriptorComposerTest.java | 141 +-------- .../gapic/composer/ComposerTest.java | 13 +- ...rviceCallableFactoryClassComposerTest.java | 13 +- .../GrpcServiceStubClassComposerTest.java | 12 +- .../MockServiceClassComposerTest.java | 12 +- .../MockServiceImplClassComposerTest.java | 14 +- .../ResourceNameHelperClassComposerTest.java | 24 +- .../ServiceClientClassComposerTest.java | 11 +- .../ServiceClientTestClassComposerTest.java | 12 +- .../ServiceSettingsClassComposerTest.java | 13 +- .../ServiceStubClassComposerTest.java | 12 +- .../ServiceStubSettingsClassComposerTest.java | 26 +- ...DescriptorComposerTestNoSubresponse.golden | 53 ++++ ...ngDescriptorComposerTestSubresponse.golden | 59 ++++ .../GrpcServiceStubClassComposerTest.golden | 2 +- .../MockServiceImplClassComposerTest.golden | 5 - ...HelperClassComposerTestMultiPattern.golden | 100 ++++++- ...meHelperClassComposerTestOnePattern.golden | 8 +- .../ServiceClientClassComposerTest.golden | 282 ++++++++++++++++-- .../ServiceClientTestClassComposerTest.golden | 4 +- .../ServiceSettingsClassComposerTest.golden | 2 +- .../ServiceStubClassComposerTest.golden | 9 +- ...ceStubSettingsClassComposerTestEcho.golden | 4 +- ...tubSettingsClassComposerTestLogging.golden | 16 +- ...bSettingsClassComposerTestPublisher.golden | 18 +- 26 files changed, 580 insertions(+), 286 deletions(-) create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestNoSubresponse.golden create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel index 431accefed..193a9a21f6 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel @@ -50,6 +50,7 @@ java_proto_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/composer", + "//src/test/java/com/google/api/generator/test/framework", "//src/main/java/com/google/api/generator/gapic/model", "//src/main/java/com/google/api/generator/gapic/protoparser", "//src/test/java/com/google/api/generator/gapic/testdata:showcase_java_proto", diff --git a/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java index ffb494d802..ec1078122d 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java @@ -28,6 +28,7 @@ import com.google.api.generator.gapic.protoparser.BatchingSettingsConfigParser; import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.gapic.protoparser.ServiceConfigParser; +import com.google.api.generator.test.framework.Assert; import com.google.logging.v2.LogEntryProto; import com.google.logging.v2.LoggingConfigProto; import com.google.logging.v2.LoggingMetricsProto; @@ -51,6 +52,12 @@ public class BatchingDescriptorComposerTest { private static final String TESTFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/testdata/"; + private static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_NO_SUBRESPONSE = + "BatchingDescriptorComposerTestNoSubresponse.golden"; + private static final String GOLDENFILES_SUBRESPONSE = + "BatchingDescriptorComposerTestSubresponse.golden"; private JavaWriterVisitor writerVisitor; @@ -101,74 +108,8 @@ public void batchingDescriptor_hasSubresponseField() { method, batchingSetting, messageTypes); batchingDescriptorExpr.accept(writerVisitor); - String expected = - createLines( - "private static final BatchingDescriptor" - + " PUBLISH_BATCHING_DESC = new BatchingDescriptor() {\n", - "@Override\n", - "public PartitionKey getBatchPartitionKey(PublishRequest request) {\n", - "return new PartitionKey(request.getTopic());\n", - "}\n", - "\n", - "@Override\n", - "public RequestBuilder getRequestBuilder() {\n", - "return new RequestBuilder() {\n", - "private PublishRequest.Builder builder;\n", - "@Override\n", - "public void appendRequest(PublishRequest request) {\n", - "if (Objects.isNull(builder)) {\n", - "builder = request.toBuilder();\n", - "} else {\n", - "builder.addAllMessages(request.getMessagesList());\n", - "}\n", - "}\n", - "\n", - "@Override\n", - "public PublishRequest build() {\n", - "return builder.build();\n", - "}\n", - "\n", - "};\n", - "}\n", - "\n", - "@Override\n", - "public void splitResponse(PublishResponse batchResponse, Collection> batch) {\n", - "int batchMessageIndex = 0;\n", - "for (BatchedRequestIssuer responder : batch) {\n", - "List subresponseElements = new ArrayList<>();\n", - "long subresponseCount = responder.getMessageCount();\n", - "for (int i = 0; i < subresponseCount; i++) {\n", - "subresponseElements.add(batchResponse.getMessageIds(batchMessageIndex++));\n", - "}\n", - "PublishResponse response =" - + " PublishResponse.newBuilder().addAllMessageIds(subresponseElements).build();\n", - "responder.setResponse(response);\n", - "}\n", - "}\n", - "\n", - "@Override\n", - "public void splitException(Throwable throwable, Collection> batch) {\n", - "for (BatchedRequestIssuer responder : batch) {\n", - "responder.setException(throwable);\n", - "}\n", - "}\n", - "\n", - "@Override\n", - "public long countElements(PublishRequest request) {\n", - "return request.getMessagesCount();\n", - "}\n", - "\n", - "@Override\n", - "public long countBytes(PublishRequest request) {\n", - "return request.getSerializedSize();\n", - "}\n", - "\n", - "}"); - - assertEquals(expected, writerVisitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_SUBRESPONSE); + Assert.assertCodeEquals(goldenFilePath, writerVisitor.write()); } @Test @@ -220,68 +161,8 @@ public void batchingDescriptor_noSubresponseField() { method, batchingSetting, messageTypes); batchingDescriptorExpr.accept(writerVisitor); - String expected = - createLines( - "private static final BatchingDescriptor WRITE_LOG_ENTRIES_BATCHING_DESC = new" - + " BatchingDescriptor() {\n", - "@Override\n", - "public PartitionKey getBatchPartitionKey(WriteLogEntriesRequest request) {\n", - "return new PartitionKey(request.getLogName(), request.getResource()," - + " request.getLabels());\n", - "}\n", - "\n", - "@Override\n", - "public RequestBuilder getRequestBuilder() {\n", - "return new RequestBuilder() {\n", - "private WriteLogEntriesRequest.Builder builder;\n", - "@Override\n", - "public void appendRequest(WriteLogEntriesRequest request) {\n", - "if (Objects.isNull(builder)) {\n", - "builder = request.toBuilder();\n", - "} else {\n", - "builder.addAllEntries(request.getEntriesList());\n", - "}\n", - "}\n", - "\n", - "@Override\n", - "public WriteLogEntriesRequest build() {\n", - "return builder.build();\n", - "}\n", - "\n", - "};\n", - "}\n", - "\n", - "@Override\n", - "public void splitResponse(WriteLogEntriesResponse batchResponse, Collection> batch) {\n", - "for (BatchedRequestIssuer responder : batch) {\n", - "WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build();\n", - "responder.setResponse(response);\n", - "}\n", - "}\n", - "\n", - "@Override\n", - "public void splitException(Throwable throwable, Collection> batch) {\n", - "for (BatchedRequestIssuer responder : batch) {\n", - "responder.setException(throwable);\n", - "}\n", - "}\n", - "\n", - "@Override\n", - "public long countElements(WriteLogEntriesRequest request) {\n", - "return request.getEntriesCount();\n", - "}\n", - "\n", - "@Override\n", - "public long countBytes(WriteLogEntriesRequest request) {\n", - "return request.getSerializedSize();\n", - "}\n", - "\n", - "}"); - - assertEquals(expected, writerVisitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NO_SUBRESPONSE); + Assert.assertCodeEquals(goldenFilePath, writerVisitor.write()); } private static Method findMethod(Service service, String methodName) { diff --git a/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java index 59f46da982..60ea52fdb9 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java @@ -14,15 +14,12 @@ package com.google.api.generator.gapic.composer; -import static junit.framework.Assert.assertEquals; - import com.google.api.generator.engine.ast.ClassDefinition; import com.google.api.generator.engine.ast.ScopeNode; import com.google.api.generator.engine.writer.JavaWriterVisitor; import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; -import java.io.IOException; -import java.nio.file.Files; +import com.google.api.generator.test.framework.Assert; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; @@ -32,9 +29,10 @@ public class ComposerTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_NAME = "ComposerTest.golden"; @Test - public void gapicClass_addApacheLicense() throws IOException { + public void gapicClass_addApacheLicense() { ClassDefinition classDef = ClassDefinition.builder() .setPackageString("com.google.showcase.v1beta1.stub") @@ -45,8 +43,7 @@ public void gapicClass_addApacheLicense() throws IOException { Composer.addApacheLicense(Arrays.asList(GapicClass.create(Kind.TEST, classDef))); JavaWriterVisitor visitor = new JavaWriterVisitor(); gapicClassWithHeaderList.get(0).classDefinition().accept(visitor); - Path goldeFilePath = Paths.get(GOLDENFILES_DIRECTORY, "ComposerTest.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(visitor.write(), expectedClassString); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java index fd6ee29780..67bbc2c37a 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java @@ -22,11 +22,10 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; +import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; @@ -41,6 +40,8 @@ public class GrpcServiceCallableFactoryClassComposerTest { private FileDescriptor echoFileDescriptor; private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_NAME = + "GrpcServiceCallableFactoryClassComposerTest.golden"; @Before public void setUp() { @@ -50,7 +51,7 @@ public void setUp() { } @Test - public void generateServiceClasses() throws IOException { + public void generateServiceClasses() { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -63,9 +64,7 @@ public void generateServiceClasses() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = - Paths.get(GOLDENFILES_DIRECTORY, "GrpcServiceCallableFactoryClassComposerTest.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java index 26e5515864..056e777bee 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java @@ -22,11 +22,10 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; +import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; @@ -39,6 +38,7 @@ public class GrpcServiceStubClassComposerTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_NAME = "GrpcServiceStubClassComposerTest.golden"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -50,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() throws IOException { + public void generateServiceClasses() { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -62,9 +62,7 @@ public void generateServiceClasses() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = - Paths.get(GOLDENFILES_DIRECTORY, "GrpcServiceStubClassComposerTest.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java index 21921ce5a1..5a9ab45a35 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java @@ -22,11 +22,10 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; +import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; @@ -39,6 +38,8 @@ public class MockServiceClassComposerTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_NAME = "MockServiceClassComposerTest.golden"; + private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -50,7 +51,7 @@ public void setUp() { } @Test - public void generateServiceClasses() throws IOException { + public void generateServiceClasses() { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -62,8 +63,7 @@ public void generateServiceClasses() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = Paths.get(GOLDENFILES_DIRECTORY, "MockServiceClassComposerTest.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java index 827436b3c2..db57fc4004 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java @@ -22,11 +22,10 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; +import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; @@ -39,6 +38,8 @@ public class MockServiceImplClassComposerTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_NAME = "MockServiceImplClassComposerTest.golden"; + private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -50,7 +51,7 @@ public void setUp() { } @Test - public void generateServiceClasses() throws IOException { + public void generateServiceClasses() { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -63,10 +64,7 @@ public void generateServiceClasses() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = - Paths.get(GOLDENFILES_DIRECTORY, "MockServiceImplClassComposerTest.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - System.out.println(visitor.write()); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java index d9c6fbc0e5..20fbe7b28d 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java @@ -23,12 +23,11 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; +import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; import com.google.showcase.v1beta1.TestingOuterClass; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; @@ -44,6 +43,11 @@ public class ResourceNameHelperClassComposerTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_MULTI_PATTERN = + "ResourceNameHelperClassComposerTestMultiPattern.golden"; + private static final String GOLDENFILES_SINGLE_PATTERN = + "ResourceNameHelperClassComposerTestOnePattern.golden"; + private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -167,7 +171,7 @@ public void concatToUpperCamelCaseName_basic() { } @Test - public void generateResourceNameClass_echoFoobarMultiplePatterns() throws IOException { + public void generateResourceNameClass_echoFoobarMultiplePatterns() { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -182,14 +186,12 @@ public void generateResourceNameClass_echoFoobarMultiplePatterns() throws IOExce JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = - Paths.get(GOLDENFILES_DIRECTORY, "ResourceNameHelperClassComposerTestMultiPattern.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_MULTI_PATTERN); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } @Test - public void generateResourceNameClass_testingSessionOnePattern() throws IOException { + public void generateResourceNameClass_testingSessionOnePattern() { FileDescriptor testingFileDescriptor = TestingOuterClass.getDescriptor(); ServiceDescriptor testingService = testingFileDescriptor.getServices().get(0); assertEquals(testingService.getName(), "Testing"); @@ -209,10 +211,8 @@ public void generateResourceNameClass_testingSessionOnePattern() throws IOExcept JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = - Paths.get(GOLDENFILES_DIRECTORY, "ResourceNameHelperClassComposerTestOnePattern.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_SINGLE_PATTERN); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } // TODO(miraleung): Add more tests for a single pattern. } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java index 498d6d0db3..fb431f39e8 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java @@ -22,11 +22,10 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; +import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; @@ -39,6 +38,7 @@ public class ServiceClientClassComposerTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_NAME = "ServiceClientClassComposerTest.golden"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -50,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() throws IOException { + public void generateServiceClasses() { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -63,8 +63,7 @@ public void generateServiceClasses() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = Paths.get(GOLDENFILES_DIRECTORY, "ServiceClientClassComposerTest.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java index 1b48c9246f..8d790fa6c4 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java @@ -22,11 +22,10 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; +import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; @@ -39,6 +38,7 @@ public class ServiceClientTestClassComposerTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_NAME = "ServiceClientTestClassComposerTest.golden"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -50,7 +50,7 @@ public void setUp() { } @Test - public void generateServiceClasses() throws IOException { + public void generateServiceClasses() { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -63,9 +63,7 @@ public void generateServiceClasses() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = - Paths.get(GOLDENFILES_DIRECTORY, "ServiceClientTestClassComposerTest.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java index 7d19d5d7ff..ceda5a848c 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java @@ -22,11 +22,10 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; +import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; @@ -39,6 +38,8 @@ public class ServiceSettingsClassComposerTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_NAME = "ServiceSettingsClassComposerTest.golden"; + private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -50,7 +51,7 @@ public void setUp() { } @Test - public void generateServiceClasses() throws IOException { + public void generateServiceClasses() { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -63,9 +64,7 @@ public void generateServiceClasses() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = - Paths.get(GOLDENFILES_DIRECTORY, "ServiceSettingsClassComposerTest.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java index b9672c43c5..7845e2ef20 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java @@ -22,11 +22,10 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; +import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; @@ -39,6 +38,8 @@ public class ServiceStubClassComposerTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + private static final String GOLDENFILES_NAME = "ServiceStubClassComposerTest.golden"; + private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -50,7 +51,7 @@ public void setUp() { } @Test - public void generateServiceClasses() throws IOException { + public void generateServiceClasses() { Map messageTypes = Parser.parseMessages(echoFileDescriptor); Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); @@ -62,8 +63,7 @@ public void generateServiceClasses() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = Paths.get(GOLDENFILES_DIRECTORY, "ServiceStubClassComposerTest.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java index 3995cde711..8748d67872 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java @@ -27,6 +27,7 @@ import com.google.api.generator.gapic.protoparser.BatchingSettingsConfigParser; import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.gapic.protoparser.ServiceConfigParser; +import com.google.api.generator.test.framework.Assert; import com.google.logging.v2.LogEntryProto; import com.google.logging.v2.LoggingConfigProto; import com.google.logging.v2.LoggingMetricsProto; @@ -37,7 +38,6 @@ import com.google.showcase.v1beta1.EchoOuterClass; import google.cloud.CommonResources; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; @@ -54,6 +54,12 @@ public class ServiceStubSettingsClassComposerTest { "src/test/java/com/google/api/generator/gapic/composer/goldens/"; private static final String TESTFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/testdata/"; + private static final String GOLDENFILES_NAME_LOGGING = + "ServiceStubSettingsClassComposerTestLogging.golden"; + private static final String GOLDENFILES_NAME_ECHO = + "ServiceStubSettingsClassComposerTestEcho.golden"; + private static final String GOLDENFILES_NAME_PUBLISHER = + "ServiceStubSettingsClassComposerTestPublisher.golden"; @Test public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() throws IOException { @@ -97,10 +103,8 @@ public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() thro JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = - Paths.get(GOLDENFILES_DIRECTORY, "ServiceStubSettingsClassComposerTestLogging.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME_LOGGING); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } @Test @@ -140,10 +144,8 @@ public void generateServiceStubSettingsClasses_batchingWithNonemptyResponses() JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = - Paths.get(GOLDENFILES_DIRECTORY, "ServiceStubSettingsClassComposerTestPublisher.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME_PUBLISHER); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } @Test @@ -171,10 +173,8 @@ public void generateServiceStubSettingsClasses_basic() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldeFilePath = - Paths.get(GOLDENFILES_DIRECTORY, "ServiceStubSettingsClassComposerTestEcho.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(expectedClassString, visitor.write()); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME_ECHO); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); } private static List parseServices( diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestNoSubresponse.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestNoSubresponse.golden new file mode 100644 index 0000000000..b9c9eba122 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestNoSubresponse.golden @@ -0,0 +1,53 @@ +private static final BatchingDescriptor WRITE_LOG_ENTRIES_BATCHING_DESC = new BatchingDescriptor() { +@Override +public PartitionKey getBatchPartitionKey(WriteLogEntriesRequest request) { +return new PartitionKey(request.getLogName(), request.getResource(), request.getLabels()); +} + +@Override +public RequestBuilder getRequestBuilder() { +return new RequestBuilder() { +private WriteLogEntriesRequest.Builder builder; +@Override +public void appendRequest(WriteLogEntriesRequest request) { +if (Objects.isNull(builder)) { +builder = request.toBuilder(); +} else { +builder.addAllEntries(request.getEntriesList()); +} +} + +@Override +public WriteLogEntriesRequest build() { +return builder.build(); +} + +}; +} + +@Override +public void splitResponse(WriteLogEntriesResponse batchResponse, Collection> batch) { +for (BatchedRequestIssuer responder : batch) { +WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); +responder.setResponse(response); +} +} + +@Override +public void splitException(Throwable throwable, Collection> batch) { +for (BatchedRequestIssuer responder : batch) { +responder.setException(throwable); +} +} + +@Override +public long countElements(WriteLogEntriesRequest request) { +return request.getEntriesCount(); +} + +@Override +public long countBytes(WriteLogEntriesRequest request) { +return request.getSerializedSize(); +} + +} \ No newline at end of file diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden new file mode 100644 index 0000000000..1ebfca8696 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden @@ -0,0 +1,59 @@ +private static final BatchingDescriptor PUBLISH_BATCHING_DESC = new BatchingDescriptor() { +@Override +public PartitionKey getBatchPartitionKey(PublishRequest request) { +return new PartitionKey(request.getTopic()); +} + +@Override +public RequestBuilder getRequestBuilder() { +return new RequestBuilder() { +private PublishRequest.Builder builder; +@Override +public void appendRequest(PublishRequest request) { +if (Objects.isNull(builder)) { +builder = request.toBuilder(); +} else { +builder.addAllMessages(request.getMessagesList()); +} +} + +@Override +public PublishRequest build() { +return builder.build(); +} + +}; +} + +@Override +public void splitResponse(PublishResponse batchResponse, Collection> batch) { +int batchMessageIndex = 0; +for (BatchedRequestIssuer responder : batch) { +List subresponseElements = new ArrayList<>(); +long subresponseCount = responder.getMessageCount(); +for (int i = 0; i < subresponseCount; i++) { +subresponseElements.add(batchResponse.getMessageIds(batchMessageIndex++)); +} +PublishResponse response = PublishResponse.newBuilder().addAllMessageIds(subresponseElements).build(); +responder.setResponse(response); +} +} + +@Override +public void splitException(Throwable throwable, Collection> batch) { +for (BatchedRequestIssuer responder : batch) { +responder.setException(throwable); +} +} + +@Override +public long countElements(PublishRequest request) { +return request.getMessagesCount(); +} + +@Override +public long countBytes(PublishRequest request) { +return request.getSerializedSize(); +} + +} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceStubClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceStubClassComposerTest.golden index 9068e90730..fdc6daf449 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceStubClassComposerTest.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceStubClassComposerTest.golden @@ -187,7 +187,7 @@ public class GrpcEchoStub extends EchoStub { callableFactory.createUnaryCallable( pagedExpandTransportSettings, settings.pagedExpandSettings(), clientContext); this.pagedExpandPagedCallable = - callableFactory.createUnaryCallable( + callableFactory.createPagedCallable( pagedExpandTransportSettings, settings.pagedExpandSettings(), clientContext); this.waitCallable = callableFactory.createUnaryCallable( diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceImplClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceImplClassComposerTest.golden index 05641e4794..e3652b66d8 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceImplClassComposerTest.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceImplClassComposerTest.golden @@ -22,27 +22,22 @@ public class MockEchoImpl extends EchoImplBase { responses = new LinkedList<>(); } - @Override public List getRequests() { return requests; } - @Override public void addResponse(AbstractMessage response) { responses.add(response); } - @Override public void setResponses(List responses) { this.responses = new LinkedList(responses); } - @Override public void addException(Exception exception) { responses.add(exception); } - @Override public void reset() { requests = new ArrayList<>(); responses = new LinkedList<>(); diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestMultiPattern.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestMultiPattern.golden index 0b6beb27cb..7676c60e08 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestMultiPattern.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestMultiPattern.golden @@ -22,19 +22,21 @@ public class FoobarName implements ResourceName { "projects/{project}/chocolate/variants/{variant}/foobars/{foobar}"); private static final PathTemplate FOOBAR = PathTemplate.createWithoutUrlEncoding("foobars/{foobar}"); + private static final PathTemplate BAR_FOO_FOOBAR = + PathTemplate.createWithoutUrlEncoding("bar_foos/{bar_foo}/foobars/{foobar}"); private volatile Map fieldValuesMap; private PathTemplate pathTemplate; private String fixedValue; private final String project; private final String foobar; private final String variant; - - @Deprecated - protected FoobarName() {} + private final String barFoo; private FoobarName(Builder builder) { project = Preconditions.checkNotNull(builder.getProject()); foobar = Preconditions.checkNotNull(builder.getFoobar()); + variant = null; + barFoo = null; pathTemplate = PROJECT_FOOBAR; } @@ -42,14 +44,26 @@ public class FoobarName implements ResourceName { project = Preconditions.checkNotNull(builder.getProject()); variant = Preconditions.checkNotNull(builder.getVariant()); foobar = Preconditions.checkNotNull(builder.getFoobar()); + barFoo = null; pathTemplate = PROJECT_VARIANT_FOOBAR; } private FoobarName(FoobarBuilder builder) { foobar = Preconditions.checkNotNull(builder.getFoobar()); + project = null; + variant = null; + barFoo = null; pathTemplate = FOOBAR; } + private FoobarName(BarFooFoobarBuilder builder) { + barFoo = Preconditions.checkNotNull(builder.getBarFoo()); + foobar = Preconditions.checkNotNull(builder.getFoobar()); + project = null; + variant = null; + pathTemplate = BAR_FOO_FOOBAR; + } + public String getProject() { return project; } @@ -62,6 +76,10 @@ public class FoobarName implements ResourceName { return variant; } + public String getBarFoo() { + return barFoo; + } + public static Builder newBuilder() { return new Builder(); } @@ -81,6 +99,11 @@ public class FoobarName implements ResourceName { return new FoobarBuilder(); } + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static BarFooFoobarBuilder newBarFooFoobarBuilder() { + return new BarFooFoobarBuilder(); + } + public Builder toBuilder() { return new Builder(this); } @@ -109,6 +132,11 @@ public class FoobarName implements ResourceName { return newFoobarBuilder().setFoobar(foobar).build(); } + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static FoobarName ofBarFooFoobarBuilder(String barFoo, String foobar) { + return newBarFooFoobarBuilder().setBarFoo(barFoo).setFoobar(foobar).build(); + } + public static String format(String project, String foobar) { return newBuilder().setProject(project).setFoobar(foobar).build().toString(); } @@ -134,6 +162,11 @@ public class FoobarName implements ResourceName { return newFoobarBuilder().setFoobar(foobar).build().toString(); } + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatBarFooFoobarBuilder(String barFoo, String foobar) { + return newBarFooFoobarBuilder().setBarFoo(barFoo).setFoobar(foobar).build().toString(); + } + public static FoobarName parse(String formattedString) { if (formattedString.isEmpty()) { return null; @@ -148,6 +181,9 @@ public class FoobarName implements ResourceName { } else if (FOOBAR.matches(formattedString)) { Map matchMap = FOOBAR.match(formattedString); return ofFoobarBuilder(matchMap.get("foobar")); + } else if (BAR_FOO_FOOBAR.matches(formattedString)) { + Map matchMap = BAR_FOO_FOOBAR.match(formattedString); + return ofBarFooFoobarBuilder(matchMap.get("bar_foo"), matchMap.get("foobar")); } throw new ValidationException("FoobarName.parse: formattedString not in valid format"); } @@ -163,7 +199,7 @@ public class FoobarName implements ResourceName { public static List toStringList(List values) { List list = new ArrayList<>(values.size()); for (FoobarName value : values) { - if (Objects.equals(value, null)) { + if (Objects.isNull(value)) { list.add(""); } else { list.add(value.toString()); @@ -173,27 +209,30 @@ public class FoobarName implements ResourceName { } public static boolean isParsableFrom(String formattedString) { - return PROJECT_FOOBAR - .matches(formattedString) - .todoOr(PROJECT_VARIANT_FOOBAR.matches(formattedString)) - .todoOr(FOOBAR.matches(formattedString)); + return PROJECT_FOOBAR.matches(formattedString) + || PROJECT_VARIANT_FOOBAR.matches(formattedString) + || FOOBAR.matches(formattedString) + || BAR_FOO_FOOBAR.matches(formattedString); } @Override public Map getFieldValuesMap() { - if (Objects.equals(fieldValuesMap, null)) { + if (Objects.isNull(fieldValuesMap)) { synchronized (this) { - if (Objects.equals(fieldValuesMap, null)) { + if (Objects.isNull(fieldValuesMap)) { ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); - if (Objects.notTodoEquals(project, null)) { + if (!Objects.isNull(project)) { fieldMapBuilder.put("project", project); } - if (Objects.notTodoEquals(foobar, null)) { + if (!Objects.isNull(foobar)) { fieldMapBuilder.put("foobar", foobar); } - if (Objects.notTodoEquals(variant, null)) { + if (!Objects.isNull(variant)) { fieldMapBuilder.put("variant", variant); } + if (!Objects.isNull(barFoo)) { + fieldMapBuilder.put("bar_foo", barFoo); + } fieldValuesMap = fieldMapBuilder.build(); } } @@ -207,9 +246,7 @@ public class FoobarName implements ResourceName { @Override public String toString() { - return Objects.equals(fixedValue, null) - ? pathTemplate.instantiate(getFieldValuesMap()) - : fixedValue; + return !Objects.isNull(fixedValue) ? fixedValue : pathTemplate.instantiate(getFieldValuesMap()); } /** Builder for projects/{project}/foobars/{foobar}. */ @@ -311,4 +348,35 @@ public class FoobarName implements ResourceName { return new FoobarName(this); } } + + /** Builder for bar_foos/{bar_foo}/foobars/{foobar}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class BarFooFoobarBuilder { + private String barFoo; + private String foobar; + + private BarFooFoobarBuilder() {} + + public String getBarFoo() { + return barFoo; + } + + public String getFoobar() { + return foobar; + } + + public BarFooFoobarBuilder setBarFoo(String barFoo) { + this.barFoo = barFoo; + return this; + } + + public BarFooFoobarBuilder setFoobar(String foobar) { + this.foobar = foobar; + return this; + } + + public FoobarName build() { + return new FoobarName(this); + } + } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestOnePattern.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestOnePattern.golden index 0e3a9266f5..4dbe76e88e 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestOnePattern.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestOnePattern.golden @@ -63,7 +63,7 @@ public class SessionName implements ResourceName { public static List toStringList(List values) { List list = new ArrayList<>(values.size()); for (SessionName value : values) { - if (Objects.equals(value, null)) { + if (Objects.isNull(value)) { list.add(""); } else { list.add(value.toString()); @@ -78,11 +78,11 @@ public class SessionName implements ResourceName { @Override public Map getFieldValuesMap() { - if (Objects.equals(fieldValuesMap, null)) { + if (Objects.isNull(fieldValuesMap)) { synchronized (this) { - if (Objects.equals(fieldValuesMap, null)) { + if (Objects.isNull(fieldValuesMap)) { ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); - if (Objects.notTodoEquals(session, null)) { + if (!Objects.isNull(session)) { fieldMapBuilder.put("session", session); } fieldValuesMap = fieldMapBuilder.build(); diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden index c4ff6fd19c..58d6ddf08e 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden @@ -1,24 +1,68 @@ package com.google.showcase.v1beta1; +import com.google.api.core.ApiFunction; +import com.google.api.core.ApiFuture; +import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.longrunning.OperationFuture; +import com.google.api.gax.paging.AbstractFixedSizeCollection; +import com.google.api.gax.paging.AbstractPage; +import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.BidiStreamingCallable; import com.google.api.gax.rpc.ClientStreamingCallable; import com.google.api.gax.rpc.OperationCallable; +import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.ServerStreamingCallable; import com.google.api.gax.rpc.UnaryCallable; import com.google.api.resourcenames.ResourceName; -import com.google.common.base.Strings; +import com.google.common.util.concurrent.MoreExecutors; import com.google.longrunning.Operation; import com.google.longrunning.OperationsClient; import com.google.rpc.Status; import com.google.showcase.v1beta1.stub.EchoStub; import com.google.showcase.v1beta1.stub.EchoStubSettings; import java.io.IOException; +import java.util.List; +import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * This class provides the ability to make remote calls to the backing service through method calls + * that map to API methods. Sample code to get started: + * + *

Note: close() needs to be called on the echoClient object to clean up resources such as + * threads. In the example above, try-with-resources is used, which automatically calls close(). + * + *

The surface of this class includes several types of Java methods for each of the API's + * methods: + * + *

    + *
  1. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  2. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  3. A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. + *
+ * + *

See the individual methods for example code. + * + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. + * + *

This class can be customized by passing in a custom instance of EchoSettings to create(). For + * example: + * + *

To customize credentials: + * + *

To customize the endpoint: + */ @BetaApi @Generated("by gapic-generator") public class EchoClient implements BackgroundResource { @@ -26,19 +70,32 @@ public class EchoClient implements BackgroundResource { private final EchoStub stub; private final OperationsClient operationsClient; + /** Constructs an instance of EchoClient with default settings. */ public static final EchoClient create() throws IOException { return create(EchoSettings.newBuilder().build()); } + /** + * Constructs an instance of EchoClient, using the given settings. The channels are created based + * on the settings passed in, or defaults for any settings that are not set. + */ public static final EchoClient create(EchoSettings settings) throws IOException { return new EchoClient(settings); } + /** + * Constructs an instance of EchoClient, using the given stub for making calls. This is for + * advanced usage - prefer using create(EchoSettings). + */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final EchoClient create(EchoStub stub) { return new EchoClient(stub); } + /** + * Constructs an instance of EchoClient, using the given settings. This is protected so that it is + * easy to make a subclass, but otherwise, the static factory methods should be preferred. + */ protected EchoClient(EchoSettings settings) throws IOException { this.settings = settings; this.stub = ((EchoStubSettings) settings.getStubSettings()).createStub(); @@ -61,100 +118,205 @@ public class EchoClient implements BackgroundResource { return stub; } + /** + * Returns the OperationsClient that can be used to query the status of a long-running operation + * returned by another API method call. + */ public final OperationsClient getOperationsClient() { return operationsClient; } - public final EchoResponse echo(String content) { - EchoRequest request = EchoRequest.newBuilder().setContent(content).build(); + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param parent + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final EchoResponse echo(ResourceName parent) { + EchoRequest request = + EchoRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); return echo(request); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param error + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ public final EchoResponse echo(Status error) { EchoRequest request = EchoRequest.newBuilder().setError(error).build(); return echo(request); } - public final EchoResponse echo(String content, Severity severity) { + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param name + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final EchoResponse echo(FoobarName name) { EchoRequest request = - EchoRequest.newBuilder().setContent(content).setSeverity(severity).build(); + EchoRequest.newBuilder().setName(Objects.isNull(name) ? null : name.toString()).build(); return echo(request); } - public final EchoResponse echo(String name) { - EchoRequest request = EchoRequest.newBuilder().setName(name).build(); + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param content + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final EchoResponse echo(String content) { + EchoRequest request = EchoRequest.newBuilder().setContent(content).build(); return echo(request); } - public final EchoResponse echo(FoobarName name) { - EchoRequest request = - EchoRequest.newBuilder() - .setName(Strings.isNullOrEmpty(name) ? null : name.toString()) - .build(); + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param name + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final EchoResponse echo(String name) { + EchoRequest request = EchoRequest.newBuilder().setName(name).build(); return echo(request); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param parent + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ public final EchoResponse echo(String parent) { EchoRequest request = EchoRequest.newBuilder().setParent(parent).build(); return echo(request); } - public final EchoResponse echo(ResourceName parent) { + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param content + * @param severity + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final EchoResponse echo(String content, Severity severity) { EchoRequest request = - EchoRequest.newBuilder() - .setParent(Strings.isNullOrEmpty(parent) ? null : parent.toString()) - .build(); + EchoRequest.newBuilder().setContent(content).setSeverity(severity).build(); return echo(request); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param request The request object containing all of the parameters for the API call. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ public final EchoResponse echo(EchoRequest request) { return echoCallable().call(request); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** Sample code: */ public final UnaryCallable echoCallable() { return stub.echoCallable(); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** Sample code: */ public final ServerStreamingCallable expandCallable() { return stub.expandCallable(); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** Sample code: */ public final ClientStreamingCallable collectCallable() { return stub.collectCallable(); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** Sample code: */ public final BidiStreamingCallable chatCallable() { return stub.chatCallable(); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** Sample code: */ public final BidiStreamingCallable chatAgainCallable() { return stub.chatAgainCallable(); } - public final PagedExpandResponse pagedExpand(PagedExpandRequest request) { - return pagedExpandCallable().call(request); + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param request The request object containing all of the parameters for the API call. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final PagedExpandPagedResponse pagedExpand(PagedExpandRequest request) { + return pagedExpandPagedCallable().call(request); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** Sample code: */ + public final UnaryCallable + pagedExpandPagedCallable() { + return stub.pagedExpandPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** Sample code: */ public final UnaryCallable pagedExpandCallable() { return stub.pagedExpandCallable(); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param request The request object containing all of the parameters for the API call. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ public final OperationFuture waitAsync(WaitRequest request) { return waitOperationCallable().futureCall(request); } - public final OperationCallable waitOperationCallabke() { - return stub.waitOperationCallabke(); + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** Sample code: */ + public final OperationCallable waitOperationCallable() { + return stub.waitOperationCallable(); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** Sample code: */ public final UnaryCallable waitCallable() { return stub.waitCallable(); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sample code: + * + * @param request The request object containing all of the parameters for the API call. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ public final BlockResponse block(BlockRequest request) { return blockCallable().call(request); } + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** Sample code: */ public final UnaryCallable blockCallable() { return stub.blockCallable(); } @@ -188,4 +350,84 @@ public class EchoClient implements BackgroundResource { public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } + + public static class PagedExpandPagedResponse + extends AbstractPagedListResponse< + PagedExpandRequest, + PagedExpandResponse, + EchoResponse, + PagedExpandPage, + PagedExpandFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + PagedExpandPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public PagedExpandPagedResponse apply(PagedExpandPage input) { + return new PagedExpandPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private PagedExpandPagedResponse(PagedExpandPage page) { + super(page, PagedExpandFixedSizeCollection.createEmptyCollection()); + } + } + + public static class PagedExpandPage + extends AbstractPage { + + private PagedExpandPage( + PageContext context, + PagedExpandResponse response) { + super(context, response); + } + + private static PagedExpandPage createEmptyPage() { + return new PagedExpandPage(null, null); + } + + @Override + protected PagedExpandPage createPage( + PageContext context, + PagedExpandResponse response) { + return new PagedExpandPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class PagedExpandFixedSizeCollection + extends AbstractFixedSizeCollection< + PagedExpandRequest, + PagedExpandResponse, + EchoResponse, + PagedExpandPage, + PagedExpandFixedSizeCollection> { + + private PagedExpandFixedSizeCollection(List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static PagedExpandFixedSizeCollection createEmptyCollection() { + return new PagedExpandFixedSizeCollection(null, 0); + } + + @Override + protected PagedExpandFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new PagedExpandFixedSizeCollection(pages, collectionSize); + } + } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden index 8f63eac49d..474236814b 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden @@ -38,7 +38,7 @@ public class EchoClientTest { public void setUp() throws IOException { mockServiceHelper.reset(); channelProvider = mockServiceHelper.createChannelProvider(); - settings = + EchoSettings settings = EchoSettings.newBuilder() .setTransportChannelProvider(channelProvider) .setCredentialsProvider(NoCredentialsProvider.create()) @@ -47,7 +47,7 @@ public class EchoClientTest { } @After - public static void tearDown() throws Exception { + public void tearDown() throws Exception { client.close(); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceSettingsClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceSettingsClassComposerTest.golden index 221b3725d2..076e0d772b 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceSettingsClassComposerTest.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceSettingsClassComposerTest.golden @@ -90,7 +90,7 @@ public class EchoSettings extends ClientSettings { } public static final EchoSettings create(EchoStubSettings stub) throws IOException { - return new EchoStubSettings.Builder(stub.toBuilder()).build(); + return new EchoSettings.Builder(stub.toBuilder()).build(); } /** Returns a builder for the default ExecutorProvider for this service. */ diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubClassComposerTest.golden index 83bca288c2..2b6ddd9a7e 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubClassComposerTest.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubClassComposerTest.golden @@ -1,11 +1,14 @@ package com.google.showcase.v1beta1.stub; +import static com.google.showcase.v1beta1.EchoClient.PagedExpandPagedResponse; + import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.rpc.BidiStreamingCallable; import com.google.api.gax.rpc.ClientStreamingCallable; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.ServerStreamingCallable; import com.google.api.gax.rpc.UnaryCallable; +import com.google.longrunning.Operation; import com.google.longrunning.stub.OperationsStub; import com.google.showcase.v1beta1.BlockRequest; import com.google.showcase.v1beta1.BlockResponse; @@ -52,6 +55,10 @@ public abstract class EchoStub implements BackgroundResource { throw new UnsupportedOperationException("Not implemented: chatAgainCallable()"); } + public UnaryCallable pagedExpandPagedCallable() { + throw new UnsupportedOperationException("Not implemented: pagedExpandPagedCallable()"); + } + public UnaryCallable pagedExpandCallable() { throw new UnsupportedOperationException("Not implemented: pagedExpandCallable()"); } @@ -60,7 +67,7 @@ public abstract class EchoStub implements BackgroundResource { throw new UnsupportedOperationException("Not implemented: waitOperationCallable()"); } - public UnaryCallable waitCallable() { + public UnaryCallable waitCallable() { throw new UnsupportedOperationException("Not implemented: waitCallable()"); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestEcho.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestEcho.golden index 745634aa8c..d55d7a9f3f 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestEcho.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestEcho.golden @@ -116,7 +116,7 @@ public class EchoStubSettings extends StubSettings { @Override public Iterable extractResources(PagedExpandResponse payload) { - return Objects.equals(payload.getResponsesList(), null) + return Objects.isNull(payload.getResponsesList()) ? ImmutableList.of() : payload.getResponsesList(); } @@ -263,7 +263,7 @@ public class EchoStubSettings extends StubSettings { } /** Builder for EchoStubSettings. */ - public static class Builder extends StubSettings.Builder { + public static class Builder extends StubSettings.Builder { private final ImmutableList> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder echoSettings; private final ServerStreamingCallSettings.Builder expandSettings; diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestLogging.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestLogging.golden index 770d6f49be..9b34b02c44 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestLogging.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestLogging.golden @@ -131,9 +131,9 @@ public class LoggingServiceV2StubSettings extends StubSettings extractResources(ListLogEntriesResponse payload) { - return Objects.equals(payload.getResponsesList(), null) + return Objects.isNull(payload.getEntriesList()) ? ImmutableList.of() - : payload.getResponsesList(); + : payload.getEntriesList(); } }; private static final PagedListDescriptor< @@ -179,9 +179,9 @@ public class LoggingServiceV2StubSettings extends StubSettings extractResources( ListMonitoredResourceDescriptorsResponse payload) { - return Objects.equals(payload.getResponsesList(), null) + return Objects.isNull(payload.getResourceDescriptorsList()) ? ImmutableList.of() - : payload.getResponsesList(); + : payload.getResourceDescriptorsList(); } }; private static final PagedListDescriptor @@ -214,9 +214,9 @@ public class LoggingServiceV2StubSettings extends StubSettings extractResources(ListLogsResponse payload) { - return Objects.equals(payload.getResponsesList(), null) + return Objects.isNull(payload.getLogNamesList()) ? ImmutableList.of() - : payload.getResponsesList(); + : payload.getLogNamesList(); } }; private static final PagedListResponseFactory< @@ -294,7 +294,7 @@ public class LoggingServiceV2StubSettings extends StubSettings getRequestBuilder() { return new RequestBuilder() { - private RequestBuilder builder; + private WriteLogEntriesRequest.Builder builder; @Override public void appendRequest(WriteLogEntriesRequest request) { @@ -452,7 +452,7 @@ public class LoggingServiceV2StubSettings extends StubSettings { + public static class Builder extends StubSettings.Builder { private final ImmutableList> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder deleteLogSettings; private final BatchingCallSettings.Builder diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestPublisher.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestPublisher.golden index 7bc74092f4..67404721a9 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestPublisher.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestPublisher.golden @@ -135,9 +135,9 @@ public class PublisherStubSettings extends StubSettings { @Override public Iterable extractResources(ListTopicsResponse payload) { - return Objects.equals(payload.getResponsesList(), null) + return Objects.isNull(payload.getTopicsList()) ? ImmutableList.of() - : payload.getResponsesList(); + : payload.getTopicsList(); } }; private static final PagedListDescriptor< @@ -176,9 +176,9 @@ public class PublisherStubSettings extends StubSettings { @Override public Iterable extractResources(ListTopicSubscriptionsResponse payload) { - return Objects.equals(payload.getResponsesList(), null) + return Objects.isNull(payload.getSubscriptionsList()) ? ImmutableList.of() - : payload.getResponsesList(); + : payload.getSubscriptionsList(); } }; private static final PagedListDescriptor< @@ -214,9 +214,9 @@ public class PublisherStubSettings extends StubSettings { @Override public Iterable extractResources(ListTopicSnapshotsResponse payload) { - return Objects.equals(payload.getResponsesList(), null) + return Objects.isNull(payload.getSnapshotsList()) ? ImmutableList.of() - : payload.getResponsesList(); + : payload.getSnapshotsList(); } }; private static final PagedListResponseFactory< @@ -288,7 +288,7 @@ public class PublisherStubSettings extends StubSettings { @Override public RequestBuilder getRequestBuilder() { return new RequestBuilder() { - private RequestBuilder builder; + private PublishRequest.Builder builder; @Override public void appendRequest(PublishRequest request) { @@ -315,7 +315,7 @@ public class PublisherStubSettings extends StubSettings { List subresponseElements = new ArrayList<>(); long subresponseCount = responder.getMessageCount(); for (int i = 0; i < subresponseCount; i++) { - subresponseElements.add(batchResponse.getMessageIds(batchMessageIndex)); + subresponseElements.add(batchResponse.getMessageIds(batchMessageIndex++)); } PublishResponse response = PublishResponse.newBuilder().addAllMessageIds(subresponseElements).build(); @@ -475,7 +475,7 @@ public class PublisherStubSettings extends StubSettings { } /** Builder for PublisherStubSettings. */ - public static class Builder extends StubSettings.Builder { + public static class Builder extends StubSettings.Builder { private final ImmutableList> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder createTopicSettings; private final UnaryCallSettings.Builder updateTopicSettings; From 22482a0d6a544b0d621034608d47b71d1084e673 Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Wed, 23 Sep 2020 22:51:28 +0000 Subject: [PATCH 06/16] update ast integration test --- .../java/com/google/api/generator/engine/BUILD.bazel | 1 + .../api/generator/engine/JavaCodeGeneratorTest.java | 12 +++++------- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/test/java/com/google/api/generator/engine/BUILD.bazel b/src/test/java/com/google/api/generator/engine/BUILD.bazel index 76d309f069..54b08dfd36 100644 --- a/src/test/java/com/google/api/generator/engine/BUILD.bazel +++ b/src/test/java/com/google/api/generator/engine/BUILD.bazel @@ -21,6 +21,7 @@ TESTS = [ deps = [ "//src/main/java/com/google/api/generator/engine/ast", "//src/main/java/com/google/api/generator/engine/writer", + "//src/test/java/com/google/api/generator/test/framework", "@junit_junit//jar", ], ) for test_name in TESTS] diff --git a/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java b/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java index 4887d677c6..f262bb9e60 100644 --- a/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java +++ b/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java @@ -14,8 +14,6 @@ package com.google.api.generator.engine; -import static junit.framework.Assert.assertEquals; - import com.google.api.generator.engine.ast.AnnotationNode; import com.google.api.generator.engine.ast.AnonymousClassExpr; import com.google.api.generator.engine.ast.AssignmentExpr; @@ -51,9 +49,9 @@ import com.google.api.generator.engine.ast.VariableExpr; import com.google.api.generator.engine.ast.WhileStatement; import com.google.api.generator.engine.writer.JavaWriterVisitor; +import com.google.api.generator.test.framework.Assert; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -66,6 +64,7 @@ public class JavaCodeGeneratorTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/engine/goldens/"; + private static final String GOLDENFILES_NAME = "JavaCodeGeneratorTest.golden"; // Create shared VaporReferences. private static final VaporReference stubRef = createVaporReference("com.google.gax.grpc", "Stub"); private static final VaporReference bookKindRef = @@ -101,7 +100,7 @@ public class JavaCodeGeneratorTest { private static final Variable bookKindVar = createVarFromVaporRef(bookKindRef, "bookKind"); @Test - public void validJavaClass() throws IOException { + public void validJavaClass() { // Create outer class variableDecls. // [code] private static final String serviceName = "LibraryServiceStub"; VariableExpr serviceName = createServiceNameVarExpr(); @@ -174,9 +173,8 @@ public void validJavaClass() throws IOException { .build(); JavaWriterVisitor javaWriterVisitor = new JavaWriterVisitor(); libraryServiceStubClass.accept(javaWriterVisitor); - Path goldeFilePath = Paths.get(GOLDENFILES_DIRECTORY, "JavaCodeGeneratorTest.golden"); - String expectedClassString = new String(Files.readAllBytes(goldeFilePath)); - assertEquals(javaWriterVisitor.write(), expectedClassString); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Assert.assertCodeEquals(goldenFilePath, javaWriterVisitor.write()); } // Private helpers. From 24f788db7d6b68092b88ba7b10f35f5a8b1c4ff9 Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Thu, 24 Sep 2020 01:02:49 +0000 Subject: [PATCH 07/16] keep service client test --- .../ServiceClientClassComposerTest.java | 482 +++++++++++++++++- .../ServiceClientTestClassComposerTest.java | 65 ++- .../ServiceClientClassComposerTest.golden | 433 ---------------- .../ServiceClientTestClassComposerTest.golden | 53 -- 4 files changed, 531 insertions(+), 502 deletions(-) delete mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden delete mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java index fb431f39e8..371b184823 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientClassComposerTest.java @@ -22,12 +22,9 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; -import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -36,9 +33,6 @@ import org.junit.Test; public class ServiceClientClassComposerTest { - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_NAME = "ServiceClientClassComposerTest.golden"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -63,7 +57,479 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); - Assert.assertCodeEquals(goldenFilePath, visitor.write()); + assertEquals(EXPECTED_CLASS_STRING, visitor.write()); } + + // TODO(miraleung): Update this when a file-diffing test mechanism is in place. + private static final String EXPECTED_CLASS_STRING = + "package com.google.showcase.v1beta1;\n" + + "\n" + + "import com.google.api.core.ApiFunction;\n" + + "import com.google.api.core.ApiFuture;\n" + + "import com.google.api.core.ApiFutures;\n" + + "import com.google.api.core.BetaApi;\n" + + "import com.google.api.gax.core.BackgroundResource;\n" + + "import com.google.api.gax.longrunning.OperationFuture;\n" + + "import com.google.api.gax.paging.AbstractFixedSizeCollection;\n" + + "import com.google.api.gax.paging.AbstractPage;\n" + + "import com.google.api.gax.paging.AbstractPagedListResponse;\n" + + "import com.google.api.gax.rpc.BidiStreamingCallable;\n" + + "import com.google.api.gax.rpc.ClientStreamingCallable;\n" + + "import com.google.api.gax.rpc.OperationCallable;\n" + + "import com.google.api.gax.rpc.PageContext;\n" + + "import com.google.api.gax.rpc.ServerStreamingCallable;\n" + + "import com.google.api.gax.rpc.UnaryCallable;\n" + + "import com.google.api.resourcenames.ResourceName;\n" + + "import com.google.common.util.concurrent.MoreExecutors;\n" + + "import com.google.longrunning.Operation;\n" + + "import com.google.longrunning.OperationsClient;\n" + + "import com.google.rpc.Status;\n" + + "import com.google.showcase.v1beta1.stub.EchoStub;\n" + + "import com.google.showcase.v1beta1.stub.EchoStubSettings;\n" + + "import java.io.IOException;\n" + + "import java.util.List;\n" + + "import java.util.Objects;\n" + + "import java.util.concurrent.TimeUnit;\n" + + "import javax.annotation.Generated;\n" + + "\n" + + "// AUTO-GENERATED DOCUMENTATION AND CLASS.\n" + + "/**\n" + + " * This class provides the ability to make remote calls to the backing service" + + " through method calls\n" + + " * that map to API methods. Sample code to get started:\n" + + " *\n" + + " *

Note: close() needs to be called on the echoClient object to clean up resources" + + " such as\n" + + " * threads. In the example above, try-with-resources is used, which automatically" + + " calls close().\n" + + " *\n" + + " *

The surface of this class includes several types of Java methods for each of" + + " the API's\n" + + " * methods:\n" + + " *\n" + + " *

    \n" + + " *
  1. A \"flattened\" method. With this type of method, the fields of the request" + + " type have been\n" + + " * converted into function parameters. It may be the case that not all fields" + + " are available as\n" + + " * parameters, and not every API method will have a flattened method entry" + + " point.\n" + + " *
  2. A \"request object\" method. This type of method only takes one parameter, a" + + " request object,\n" + + " * which must be constructed before the call. Not every API method will have a" + + " request object\n" + + " * method.\n" + + " *
  3. A \"callable\" method. This type of method takes no parameters and returns" + + " an immutable API\n" + + " * callable object, which can be used to initiate calls to the service.\n" + + " *
\n" + + " *\n" + + " *

See the individual methods for example code.\n" + + " *\n" + + " *

Many parameters require resource names to be formatted in a particular way. To" + + " assist with\n" + + " * these names, this class includes a format method for each type of name, and" + + " additionally a parse\n" + + " * method to extract the individual identifiers contained within names that are" + + " returned.\n" + + " *\n" + + " *

This class can be customized by passing in a custom instance of EchoSettings to" + + " create(). For\n" + + " * example:\n" + + " *\n" + + " *

To customize credentials:\n" + + " *\n" + + " *

To customize the endpoint:\n" + + " */\n" + + "@BetaApi\n" + + "@Generated(\"by gapic-generator\")\n" + + "public class EchoClient implements BackgroundResource {\n" + + " private final EchoSettings settings;\n" + + " private final EchoStub stub;\n" + + " private final OperationsClient operationsClient;\n" + + "\n" + + " /** Constructs an instance of EchoClient with default settings. */\n" + + " public static final EchoClient create() throws IOException {\n" + + " return create(EchoSettings.newBuilder().build());\n" + + " }\n" + + "\n" + + " /**\n" + + " * Constructs an instance of EchoClient, using the given settings. The channels are" + + " created based\n" + + " * on the settings passed in, or defaults for any settings that are not set.\n" + + " */\n" + + " public static final EchoClient create(EchoSettings settings) throws IOException {\n" + + " return new EchoClient(settings);\n" + + " }\n" + + "\n" + + " /**\n" + + " * Constructs an instance of EchoClient, using the given stub for making calls." + + " This is for\n" + + " * advanced usage - prefer using create(EchoSettings).\n" + + " */\n" + + " @BetaApi(\"A restructuring of stub classes is planned, so this may break in the" + + " future\")\n" + + " public static final EchoClient create(EchoStub stub) {\n" + + " return new EchoClient(stub);\n" + + " }\n" + + "\n" + + " /**\n" + + " * Constructs an instance of EchoClient, using the given settings. This is" + + " protected so that it is\n" + + " * easy to make a subclass, but otherwise, the static factory methods should be" + + " preferred.\n" + + " */\n" + + " protected EchoClient(EchoSettings settings) throws IOException {\n" + + " this.settings = settings;\n" + + " this.stub = ((EchoStubSettings) settings.getStubSettings()).createStub();\n" + + " this.operationsClient = OperationsClient.create(this.stub.getOperationsStub());\n" + + " }\n" + + "\n" + + " @BetaApi(\"A restructuring of stub classes is planned, so this may break in the" + + " future\")\n" + + " protected EchoClient(EchoStub stub) {\n" + + " this.settings = null;\n" + + " this.stub = stub;\n" + + " this.operationsClient = OperationsClient.create(this.stub.getOperationsStub());\n" + + " }\n" + + "\n" + + " public final EchoSettings getSettings() {\n" + + " return settings;\n" + + " }\n" + + "\n" + + " @BetaApi(\"A restructuring of stub classes is planned, so this may break in the" + + " future\")\n" + + " public EchoStub getStub() {\n" + + " return stub;\n" + + " }\n" + + "\n" + + " /**\n" + + " * Returns the OperationsClient that can be used to query the status of a" + + " long-running operation\n" + + " * returned by another API method call.\n" + + " */\n" + + " public final OperationsClient getOperationsClient() {\n" + + " return operationsClient;\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param parent\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final EchoResponse echo(ResourceName parent) {\n" + + " EchoRequest request =\n" + + " EchoRequest.newBuilder()\n" + + " .setParent(Objects.isNull(parent) ? null : parent.toString())\n" + + " .build();\n" + + " return echo(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param error\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final EchoResponse echo(Status error) {\n" + + " EchoRequest request = EchoRequest.newBuilder().setError(error).build();\n" + + " return echo(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param name\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final EchoResponse echo(FoobarName name) {\n" + + " EchoRequest request =\n" + + " EchoRequest.newBuilder().setName(Objects.isNull(name) ? null :" + + " name.toString()).build();\n" + + " return echo(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param content\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final EchoResponse echo(String content) {\n" + + " EchoRequest request = EchoRequest.newBuilder().setContent(content).build();\n" + + " return echo(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param name\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final EchoResponse echo(String name) {\n" + + " EchoRequest request = EchoRequest.newBuilder().setName(name).build();\n" + + " return echo(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param parent\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final EchoResponse echo(String parent) {\n" + + " EchoRequest request = EchoRequest.newBuilder().setParent(parent).build();\n" + + " return echo(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param content\n" + + " * @param severity\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final EchoResponse echo(String content, Severity severity) {\n" + + " EchoRequest request =\n" + + " EchoRequest.newBuilder().setContent(content).setSeverity(severity).build();\n" + + " return echo(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param request The request object containing all of the parameters for the API" + + " call.\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final EchoResponse echo(EchoRequest request) {\n" + + " return echoCallable().call(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /** Sample code: */\n" + + " public final UnaryCallable echoCallable() {\n" + + " return stub.echoCallable();\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /** Sample code: */\n" + + " public final ServerStreamingCallable expandCallable()" + + " {\n" + + " return stub.expandCallable();\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /** Sample code: */\n" + + " public final ClientStreamingCallable collectCallable()" + + " {\n" + + " return stub.collectCallable();\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /** Sample code: */\n" + + " public final BidiStreamingCallable chatCallable() {\n" + + " return stub.chatCallable();\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /** Sample code: */\n" + + " public final BidiStreamingCallable chatAgainCallable()" + + " {\n" + + " return stub.chatAgainCallable();\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param request The request object containing all of the parameters for the API" + + " call.\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final PagedExpandPagedResponse pagedExpand(PagedExpandRequest request) {\n" + + " return pagedExpandPagedCallable().call(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /** Sample code: */\n" + + " public final UnaryCallable\n" + + " pagedExpandPagedCallable() {\n" + + " return stub.pagedExpandPagedCallable();\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /** Sample code: */\n" + + " public final UnaryCallable" + + " pagedExpandCallable() {\n" + + " return stub.pagedExpandCallable();\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param request The request object containing all of the parameters for the API" + + " call.\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final OperationFuture waitAsync(WaitRequest" + + " request) {\n" + + " return waitOperationCallable().futureCall(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /** Sample code: */\n" + + " public final OperationCallable" + + " waitOperationCallable() {\n" + + " return stub.waitOperationCallable();\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /** Sample code: */\n" + + " public final UnaryCallable waitCallable() {\n" + + " return stub.waitCallable();\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /**\n" + + " * Sample code:\n" + + " *\n" + + " * @param request The request object containing all of the parameters for the API" + + " call.\n" + + " * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n" + + " */\n" + + " public final BlockResponse block(BlockRequest request) {\n" + + " return blockCallable().call(request);\n" + + " }\n" + + "\n" + + " // AUTO-GENERATED DOCUMENTATION AND METHOD.\n" + + " /** Sample code: */\n" + + " public final UnaryCallable blockCallable() {\n" + + " return stub.blockCallable();\n" + + " }\n" + + "\n" + + " @Override\n" + + " public final void close() {\n" + + " stub.close();\n" + + " }\n" + + "\n" + + " @Override\n" + + " public void shutdown() {\n" + + " stub.shutdown();\n" + + " }\n" + + "\n" + + " @Override\n" + + " public boolean isShutdown() {\n" + + " return stub.isShutdown();\n" + + " }\n" + + "\n" + + " @Override\n" + + " public boolean isTerminated() {\n" + + " return stub.isTerminated();\n" + + " }\n" + + "\n" + + " @Override\n" + + " public void shutdownNow() {\n" + + " stub.shutdownNow();\n" + + " }\n" + + "\n" + + " @Override\n" + + " public boolean awaitTermination(long duration, TimeUnit unit) throws" + + " InterruptedException {\n" + + " return stub.awaitTermination(duration, unit);\n" + + " }\n" + + "\n" + + " public static class PagedExpandPagedResponse\n" + + " extends AbstractPagedListResponse<\n" + + " PagedExpandRequest,\n" + + " PagedExpandResponse,\n" + + " EchoResponse,\n" + + " PagedExpandPage,\n" + + " PagedExpandFixedSizeCollection> {\n" + + "\n" + + " public static ApiFuture createAsync(\n" + + " PageContext context,\n" + + " ApiFuture futureResponse) {\n" + + " ApiFuture futurePage =\n" + + " PagedExpandPage.createEmptyPage().createPageAsync(context," + + " futureResponse);\n" + + " return ApiFutures.transform(\n" + + " futurePage,\n" + + " new ApiFunction() {\n" + + " @Override\n" + + " public PagedExpandPagedResponse apply(PagedExpandPage input) {\n" + + " return new PagedExpandPagedResponse(input);\n" + + " }\n" + + " },\n" + + " MoreExecutors.directExecutor());\n" + + " }\n" + + "\n" + + " private PagedExpandPagedResponse(PagedExpandPage page) {\n" + + " super(page, PagedExpandFixedSizeCollection.createEmptyCollection());\n" + + " }\n" + + " }\n" + + "\n" + + " public static class PagedExpandPage\n" + + " extends AbstractPage {\n" + + "\n" + + " private PagedExpandPage(\n" + + " PageContext context,\n" + + " PagedExpandResponse response) {\n" + + " super(context, response);\n" + + " }\n" + + "\n" + + " private static PagedExpandPage createEmptyPage() {\n" + + " return new PagedExpandPage(null, null);\n" + + " }\n" + + "\n" + + " @Override\n" + + " protected PagedExpandPage createPage(\n" + + " PageContext context,\n" + + " PagedExpandResponse response) {\n" + + " return new PagedExpandPage(context, response);\n" + + " }\n" + + "\n" + + " @Override\n" + + " public ApiFuture createPageAsync(\n" + + " PageContext context,\n" + + " ApiFuture futureResponse) {\n" + + " return super.createPageAsync(context, futureResponse);\n" + + " }\n" + + " }\n" + + "\n" + + " public static class PagedExpandFixedSizeCollection\n" + + " extends AbstractFixedSizeCollection<\n" + + " PagedExpandRequest,\n" + + " PagedExpandResponse,\n" + + " EchoResponse,\n" + + " PagedExpandPage,\n" + + " PagedExpandFixedSizeCollection> {\n" + + "\n" + + " private PagedExpandFixedSizeCollection(List pages, int" + + " collectionSize) {\n" + + " super(pages, collectionSize);\n" + + " }\n" + + "\n" + + " private static PagedExpandFixedSizeCollection createEmptyCollection() {\n" + + " return new PagedExpandFixedSizeCollection(null, 0);\n" + + " }\n" + + "\n" + + " @Override\n" + + " protected PagedExpandFixedSizeCollection createCollection(\n" + + " List pages, int collectionSize) {\n" + + " return new PagedExpandFixedSizeCollection(pages, collectionSize);\n" + + " }\n" + + " }\n" + + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java index 8d790fa6c4..e916663570 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposerTest.java @@ -22,12 +22,9 @@ import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; -import com.google.api.generator.test.framework.Assert; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -36,9 +33,6 @@ import org.junit.Test; public class ServiceClientTestClassComposerTest { - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_NAME = "ServiceClientTestClassComposerTest.golden"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -63,7 +57,62 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); - Assert.assertCodeEquals(goldenFilePath, visitor.write()); + assertEquals(EXPECTED_CLASS_STRING, visitor.write()); } + + // TODO(miraleung): Update this when a file-diffing test mechanism is in place. + private static final String EXPECTED_CLASS_STRING = + "package com.google.showcase.v1beta1;\n" + + "\n" + + "import com.google.api.gax.core.NoCredentialsProvider;\n" + + "import com.google.api.gax.grpc.testing.LocalChannelProvider;\n" + + "import com.google.api.gax.grpc.testing.MockGrpcService;\n" + + "import com.google.api.gax.grpc.testing.MockServiceHelper;\n" + + "import java.io.IOException;\n" + + "import java.util.Arrays;\n" + + "import java.util.UUID;\n" + + "import javax.annotation.Generated;\n" + + "import org.junit.After;\n" + + "import org.junit.AfterClass;\n" + + "import org.junit.Before;\n" + + "import org.junit.BeforeClass;\n" + + "\n" + + "@Generated(\"by gapic-generator-java\")\n" + + "public class EchoClientTest {\n" + + " public static MockServiceHelper mockServiceHelper;\n" + + " public static MockEcho mockEcho;\n" + + " public EchoClient client;\n" + + " public LocalChannelProvider channelProvider;\n" + + "\n" + + " @BeforeClass\n" + + " public static void startStaticServer() {\n" + + " mockEcho = new MockEcho();\n" + + " mockServiceHelper =\n" + + " new MockServiceHelper(\n" + + " UUID.randomUUID().toString(), Arrays.asList(mockEcho));\n" + + " mockServiceHelper.start();\n" + + " }\n" + + "\n" + + " @AfterClass\n" + + " public static void stopServer() {\n" + + " mockServiceHelper.stop();\n" + + " }\n" + + "\n" + + " @Before\n" + + " public void setUp() throws IOException {\n" + + " mockServiceHelper.reset();\n" + + " channelProvider = mockServiceHelper.createChannelProvider();\n" + + " EchoSettings settings =\n" + + " EchoSettings.newBuilder()\n" + + " .setTransportChannelProvider(channelProvider)\n" + + " .setCredentialsProvider(NoCredentialsProvider.create())\n" + + " .build();\n" + + " client = EchoClient.create(settings);\n" + + " }\n" + + "\n" + + " @After\n" + + " public void tearDown() throws Exception {\n" + + " client.close();\n" + + " }\n" + + "}\n"; } diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden deleted file mode 100644 index 58d6ddf08e..0000000000 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientClassComposerTest.golden +++ /dev/null @@ -1,433 +0,0 @@ -package com.google.showcase.v1beta1; - -import com.google.api.core.ApiFunction; -import com.google.api.core.ApiFuture; -import com.google.api.core.ApiFutures; -import com.google.api.core.BetaApi; -import com.google.api.gax.core.BackgroundResource; -import com.google.api.gax.longrunning.OperationFuture; -import com.google.api.gax.paging.AbstractFixedSizeCollection; -import com.google.api.gax.paging.AbstractPage; -import com.google.api.gax.paging.AbstractPagedListResponse; -import com.google.api.gax.rpc.BidiStreamingCallable; -import com.google.api.gax.rpc.ClientStreamingCallable; -import com.google.api.gax.rpc.OperationCallable; -import com.google.api.gax.rpc.PageContext; -import com.google.api.gax.rpc.ServerStreamingCallable; -import com.google.api.gax.rpc.UnaryCallable; -import com.google.api.resourcenames.ResourceName; -import com.google.common.util.concurrent.MoreExecutors; -import com.google.longrunning.Operation; -import com.google.longrunning.OperationsClient; -import com.google.rpc.Status; -import com.google.showcase.v1beta1.stub.EchoStub; -import com.google.showcase.v1beta1.stub.EchoStubSettings; -import java.io.IOException; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.TimeUnit; -import javax.annotation.Generated; - -// AUTO-GENERATED DOCUMENTATION AND CLASS. -/** - * This class provides the ability to make remote calls to the backing service through method calls - * that map to API methods. Sample code to get started: - * - *

Note: close() needs to be called on the echoClient object to clean up resources such as - * threads. In the example above, try-with-resources is used, which automatically calls close(). - * - *

The surface of this class includes several types of Java methods for each of the API's - * methods: - * - *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available as - * parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request object, - * which must be constructed before the call. Not every API method will have a request object - * method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable API - * callable object, which can be used to initiate calls to the service. - *
- * - *

See the individual methods for example code. - * - *

Many parameters require resource names to be formatted in a particular way. To assist with - * these names, this class includes a format method for each type of name, and additionally a parse - * method to extract the individual identifiers contained within names that are returned. - * - *

This class can be customized by passing in a custom instance of EchoSettings to create(). For - * example: - * - *

To customize credentials: - * - *

To customize the endpoint: - */ -@BetaApi -@Generated("by gapic-generator") -public class EchoClient implements BackgroundResource { - private final EchoSettings settings; - private final EchoStub stub; - private final OperationsClient operationsClient; - - /** Constructs an instance of EchoClient with default settings. */ - public static final EchoClient create() throws IOException { - return create(EchoSettings.newBuilder().build()); - } - - /** - * Constructs an instance of EchoClient, using the given settings. The channels are created based - * on the settings passed in, or defaults for any settings that are not set. - */ - public static final EchoClient create(EchoSettings settings) throws IOException { - return new EchoClient(settings); - } - - /** - * Constructs an instance of EchoClient, using the given stub for making calls. This is for - * advanced usage - prefer using create(EchoSettings). - */ - @BetaApi("A restructuring of stub classes is planned, so this may break in the future") - public static final EchoClient create(EchoStub stub) { - return new EchoClient(stub); - } - - /** - * Constructs an instance of EchoClient, using the given settings. This is protected so that it is - * easy to make a subclass, but otherwise, the static factory methods should be preferred. - */ - protected EchoClient(EchoSettings settings) throws IOException { - this.settings = settings; - this.stub = ((EchoStubSettings) settings.getStubSettings()).createStub(); - this.operationsClient = OperationsClient.create(this.stub.getOperationsStub()); - } - - @BetaApi("A restructuring of stub classes is planned, so this may break in the future") - protected EchoClient(EchoStub stub) { - this.settings = null; - this.stub = stub; - this.operationsClient = OperationsClient.create(this.stub.getOperationsStub()); - } - - public final EchoSettings getSettings() { - return settings; - } - - @BetaApi("A restructuring of stub classes is planned, so this may break in the future") - public EchoStub getStub() { - return stub; - } - - /** - * Returns the OperationsClient that can be used to query the status of a long-running operation - * returned by another API method call. - */ - public final OperationsClient getOperationsClient() { - return operationsClient; - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param parent - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final EchoResponse echo(ResourceName parent) { - EchoRequest request = - EchoRequest.newBuilder() - .setParent(Objects.isNull(parent) ? null : parent.toString()) - .build(); - return echo(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param error - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final EchoResponse echo(Status error) { - EchoRequest request = EchoRequest.newBuilder().setError(error).build(); - return echo(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param name - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final EchoResponse echo(FoobarName name) { - EchoRequest request = - EchoRequest.newBuilder().setName(Objects.isNull(name) ? null : name.toString()).build(); - return echo(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param content - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final EchoResponse echo(String content) { - EchoRequest request = EchoRequest.newBuilder().setContent(content).build(); - return echo(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param name - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final EchoResponse echo(String name) { - EchoRequest request = EchoRequest.newBuilder().setName(name).build(); - return echo(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param parent - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final EchoResponse echo(String parent) { - EchoRequest request = EchoRequest.newBuilder().setParent(parent).build(); - return echo(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param content - * @param severity - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final EchoResponse echo(String content, Severity severity) { - EchoRequest request = - EchoRequest.newBuilder().setContent(content).setSeverity(severity).build(); - return echo(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param request The request object containing all of the parameters for the API call. - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final EchoResponse echo(EchoRequest request) { - return echoCallable().call(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** Sample code: */ - public final UnaryCallable echoCallable() { - return stub.echoCallable(); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** Sample code: */ - public final ServerStreamingCallable expandCallable() { - return stub.expandCallable(); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** Sample code: */ - public final ClientStreamingCallable collectCallable() { - return stub.collectCallable(); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** Sample code: */ - public final BidiStreamingCallable chatCallable() { - return stub.chatCallable(); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** Sample code: */ - public final BidiStreamingCallable chatAgainCallable() { - return stub.chatAgainCallable(); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param request The request object containing all of the parameters for the API call. - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final PagedExpandPagedResponse pagedExpand(PagedExpandRequest request) { - return pagedExpandPagedCallable().call(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** Sample code: */ - public final UnaryCallable - pagedExpandPagedCallable() { - return stub.pagedExpandPagedCallable(); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** Sample code: */ - public final UnaryCallable pagedExpandCallable() { - return stub.pagedExpandCallable(); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param request The request object containing all of the parameters for the API call. - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final OperationFuture waitAsync(WaitRequest request) { - return waitOperationCallable().futureCall(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** Sample code: */ - public final OperationCallable waitOperationCallable() { - return stub.waitOperationCallable(); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** Sample code: */ - public final UnaryCallable waitCallable() { - return stub.waitCallable(); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** - * Sample code: - * - * @param request The request object containing all of the parameters for the API call. - * @throws com.google.api.gax.rpc.ApiException if the remote call fails - */ - public final BlockResponse block(BlockRequest request) { - return blockCallable().call(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD. - /** Sample code: */ - public final UnaryCallable blockCallable() { - return stub.blockCallable(); - } - - @Override - public final void close() { - stub.close(); - } - - @Override - public void shutdown() { - stub.shutdown(); - } - - @Override - public boolean isShutdown() { - return stub.isShutdown(); - } - - @Override - public boolean isTerminated() { - return stub.isTerminated(); - } - - @Override - public void shutdownNow() { - stub.shutdownNow(); - } - - @Override - public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { - return stub.awaitTermination(duration, unit); - } - - public static class PagedExpandPagedResponse - extends AbstractPagedListResponse< - PagedExpandRequest, - PagedExpandResponse, - EchoResponse, - PagedExpandPage, - PagedExpandFixedSizeCollection> { - - public static ApiFuture createAsync( - PageContext context, - ApiFuture futureResponse) { - ApiFuture futurePage = - PagedExpandPage.createEmptyPage().createPageAsync(context, futureResponse); - return ApiFutures.transform( - futurePage, - new ApiFunction() { - @Override - public PagedExpandPagedResponse apply(PagedExpandPage input) { - return new PagedExpandPagedResponse(input); - } - }, - MoreExecutors.directExecutor()); - } - - private PagedExpandPagedResponse(PagedExpandPage page) { - super(page, PagedExpandFixedSizeCollection.createEmptyCollection()); - } - } - - public static class PagedExpandPage - extends AbstractPage { - - private PagedExpandPage( - PageContext context, - PagedExpandResponse response) { - super(context, response); - } - - private static PagedExpandPage createEmptyPage() { - return new PagedExpandPage(null, null); - } - - @Override - protected PagedExpandPage createPage( - PageContext context, - PagedExpandResponse response) { - return new PagedExpandPage(context, response); - } - - @Override - public ApiFuture createPageAsync( - PageContext context, - ApiFuture futureResponse) { - return super.createPageAsync(context, futureResponse); - } - } - - public static class PagedExpandFixedSizeCollection - extends AbstractFixedSizeCollection< - PagedExpandRequest, - PagedExpandResponse, - EchoResponse, - PagedExpandPage, - PagedExpandFixedSizeCollection> { - - private PagedExpandFixedSizeCollection(List pages, int collectionSize) { - super(pages, collectionSize); - } - - private static PagedExpandFixedSizeCollection createEmptyCollection() { - return new PagedExpandFixedSizeCollection(null, 0); - } - - @Override - protected PagedExpandFixedSizeCollection createCollection( - List pages, int collectionSize) { - return new PagedExpandFixedSizeCollection(pages, collectionSize); - } - } -} diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden deleted file mode 100644 index 474236814b..0000000000 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceClientTestClassComposerTest.golden +++ /dev/null @@ -1,53 +0,0 @@ -package com.google.showcase.v1beta1; - -import com.google.api.gax.core.NoCredentialsProvider; -import com.google.api.gax.grpc.testing.LocalChannelProvider; -import com.google.api.gax.grpc.testing.MockGrpcService; -import com.google.api.gax.grpc.testing.MockServiceHelper; -import java.io.IOException; -import java.util.Arrays; -import java.util.UUID; -import javax.annotation.Generated; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; - -@Generated("by gapic-generator-java") -public class EchoClientTest { - public static MockServiceHelper mockServiceHelper; - public static MockEcho mockEcho; - public EchoClient client; - public LocalChannelProvider channelProvider; - - @BeforeClass - public static void startStaticServer() { - mockEcho = new MockEcho(); - mockServiceHelper = - new MockServiceHelper( - UUID.randomUUID().toString(), Arrays.asList(mockEcho)); - mockServiceHelper.start(); - } - - @AfterClass - public static void stopServer() { - mockServiceHelper.stop(); - } - - @Before - public void setUp() throws IOException { - mockServiceHelper.reset(); - channelProvider = mockServiceHelper.createChannelProvider(); - EchoSettings settings = - EchoSettings.newBuilder() - .setTransportChannelProvider(channelProvider) - .setCredentialsProvider(NoCredentialsProvider.create()) - .build(); - client = EchoClient.create(settings); - } - - @After - public void tearDown() throws Exception { - client.close(); - } -} From 0625e08f0c8a0c5ec1a980bda07a02f9f3cbb859 Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Thu, 24 Sep 2020 05:49:33 +0000 Subject: [PATCH 08/16] constant helper --- .../api/generator/gapic/composer/BUILD.bazel | 2 +- .../BatchingDescriptorComposerTest.java | 27 ++++++++--------- .../gapic/composer/ComposerConstants.java | 21 ++++++++++++++ .../gapic/composer/ComposerTest.java | 6 +--- ...rviceCallableFactoryClassComposerTest.java | 7 ++--- .../GrpcServiceStubClassComposerTest.java | 5 +--- .../MockServiceClassComposerTest.java | 5 +--- .../MockServiceImplClassComposerTest.java | 6 +--- .../ResourceNameHelperClassComposerTest.java | 11 ++----- .../composer/RetrySettingsComposerTest.java | 22 +++++++------- .../ServiceSettingsClassComposerTest.java | 6 +--- .../ServiceStubClassComposerTest.java | 6 +--- .../ServiceStubSettingsClassComposerTest.java | 29 +++++++------------ ...omposerTest.golden => EchoSettings.golden} | 0 ...assComposerTest.golden => EchoStub.golden} | 0 ...estEcho.golden => EchoStubSettings.golden} | 0 ...tMultiPattern.golden => FoobarName.golden} | 0 ....golden => GrpcEchoCallableFactory.golden} | 0 ...omposerTest.golden => GrpcEchoStub.golden} | 0 ...en => LoggingServiceV2StubSettings.golden} | 0 ...assComposerTest.golden => MockEcho.golden} | 0 ...omposerTest.golden => MockEchoImpl.golden} | 0 ...er.golden => PublisherStubSettings.golden} | 0 ...stOnePattern.golden => SessionName.golden} | 0 24 files changed, 65 insertions(+), 88 deletions(-) create mode 100644 src/test/java/com/google/api/generator/gapic/composer/ComposerConstants.java rename src/test/java/com/google/api/generator/gapic/composer/goldens/{ServiceSettingsClassComposerTest.golden => EchoSettings.golden} (100%) rename src/test/java/com/google/api/generator/gapic/composer/goldens/{ServiceStubClassComposerTest.golden => EchoStub.golden} (100%) rename src/test/java/com/google/api/generator/gapic/composer/goldens/{ServiceStubSettingsClassComposerTestEcho.golden => EchoStubSettings.golden} (100%) rename src/test/java/com/google/api/generator/gapic/composer/goldens/{ResourceNameHelperClassComposerTestMultiPattern.golden => FoobarName.golden} (100%) rename src/test/java/com/google/api/generator/gapic/composer/goldens/{GrpcServiceCallableFactoryClassComposerTest.golden => GrpcEchoCallableFactory.golden} (100%) rename src/test/java/com/google/api/generator/gapic/composer/goldens/{GrpcServiceStubClassComposerTest.golden => GrpcEchoStub.golden} (100%) rename src/test/java/com/google/api/generator/gapic/composer/goldens/{ServiceStubSettingsClassComposerTestLogging.golden => LoggingServiceV2StubSettings.golden} (100%) rename src/test/java/com/google/api/generator/gapic/composer/goldens/{MockServiceClassComposerTest.golden => MockEcho.golden} (100%) rename src/test/java/com/google/api/generator/gapic/composer/goldens/{MockServiceImplClassComposerTest.golden => MockEchoImpl.golden} (100%) rename src/test/java/com/google/api/generator/gapic/composer/goldens/{ServiceStubSettingsClassComposerTestPublisher.golden => PublisherStubSettings.golden} (100%) rename src/test/java/com/google/api/generator/gapic/composer/goldens/{ResourceNameHelperClassComposerTestOnePattern.golden => SessionName.golden} (100%) diff --git a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel index 193a9a21f6..9712f5f86d 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel @@ -37,7 +37,7 @@ java_proto_library( [java_test( name = test_name, - srcs = ["{0}.java".format(test_name)], + srcs = glob(["*.java"]), data = [ "//src/test/java/com/google/api/generator/gapic/composer/goldens:goldens_files", "//src/test/java/com/google/api/generator/gapic/testdata:gapic_config_files", diff --git a/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java index ec1078122d..a556b191f0 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java @@ -50,15 +50,6 @@ import org.junit.Test; public class BatchingDescriptorComposerTest { - private static final String TESTFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/testdata/"; - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_NO_SUBRESPONSE = - "BatchingDescriptorComposerTestNoSubresponse.golden"; - private static final String GOLDENFILES_SUBRESPONSE = - "BatchingDescriptorComposerTestSubresponse.golden"; - private JavaWriterVisitor writerVisitor; @Before @@ -85,13 +76,13 @@ public void batchingDescriptor_hasSubresponseField() { serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); String filename = "pubsub_gapic.yaml"; - Path path = Paths.get(TESTFILES_DIRECTORY, filename); + Path path = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, filename); Optional> batchingSettingsOpt = BatchingSettingsConfigParser.parse(Optional.of(path.toString())); assertTrue(batchingSettingsOpt.isPresent()); String jsonFilename = "pubsub_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional configOpt = ServiceConfigParser.parse(jsonPath.toString(), batchingSettingsOpt); assertTrue(configOpt.isPresent()); @@ -108,7 +99,10 @@ public void batchingDescriptor_hasSubresponseField() { method, batchingSetting, messageTypes); batchingDescriptorExpr.accept(writerVisitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_SUBRESPONSE); + Path goldenFilePath = + Paths.get( + ComposerConstants.GOLDENFILES_DIRECTORY, + "BatchingDescriptorComposerTestSubresponse.golden"); Assert.assertCodeEquals(goldenFilePath, writerVisitor.write()); } @@ -138,13 +132,13 @@ public void batchingDescriptor_noSubresponseField() { serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); String filename = "logging_gapic.yaml"; - Path path = Paths.get(TESTFILES_DIRECTORY, filename); + Path path = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, filename); Optional> batchingSettingsOpt = BatchingSettingsConfigParser.parse(Optional.of(path.toString())); assertTrue(batchingSettingsOpt.isPresent()); String jsonFilename = "logging_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional configOpt = ServiceConfigParser.parse(jsonPath.toString(), batchingSettingsOpt); assertTrue(configOpt.isPresent()); @@ -161,7 +155,10 @@ public void batchingDescriptor_noSubresponseField() { method, batchingSetting, messageTypes); batchingDescriptorExpr.accept(writerVisitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NO_SUBRESPONSE); + Path goldenFilePath = + Paths.get( + ComposerConstants.GOLDENFILES_DIRECTORY, + "BatchingDescriptorComposerTestNoSubresponse.golden"); Assert.assertCodeEquals(goldenFilePath, writerVisitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ComposerConstants.java b/src/test/java/com/google/api/generator/gapic/composer/ComposerConstants.java new file mode 100644 index 0000000000..2aa3704cb2 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/ComposerConstants.java @@ -0,0 +1,21 @@ +// 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; + +public class ComposerConstants { + public static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + public static final String TESTFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/testdata/"; +} \ No newline at end of file diff --git a/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java index 60ea52fdb9..3f2980bede 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java @@ -27,10 +27,6 @@ import org.junit.Test; public class ComposerTest { - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_NAME = "ComposerTest.golden"; - @Test public void gapicClass_addApacheLicense() { ClassDefinition classDef = @@ -43,7 +39,7 @@ public void gapicClass_addApacheLicense() { Composer.addApacheLicense(Arrays.asList(GapicClass.create(Kind.TEST, classDef))); JavaWriterVisitor visitor = new JavaWriterVisitor(); gapicClassWithHeaderList.get(0).classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "ComposerTest.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java index 67bbc2c37a..32414a301b 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java @@ -38,10 +38,6 @@ public class GrpcServiceCallableFactoryClassComposerTest { private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_NAME = - "GrpcServiceCallableFactoryClassComposerTest.golden"; @Before public void setUp() { @@ -64,7 +60,8 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Path goldenFilePath = + Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "GrpcEchoCallableFactory.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java index 056e777bee..53ea2c413e 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java @@ -36,9 +36,6 @@ import org.junit.Test; public class GrpcServiceStubClassComposerTest { - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_NAME = "GrpcServiceStubClassComposerTest.golden"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -62,7 +59,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "GrpcEchoStub.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java index 5a9ab45a35..87dbce90ea 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java @@ -36,9 +36,6 @@ import org.junit.Test; public class MockServiceClassComposerTest { - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_NAME = "MockServiceClassComposerTest.golden"; private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -63,7 +60,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "MockEcho.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java index db57fc4004..cd2fb25b2e 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java @@ -36,10 +36,6 @@ import org.junit.Test; public class MockServiceImplClassComposerTest { - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_NAME = "MockServiceImplClassComposerTest.golden"; - private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -64,7 +60,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "MockEchoImpl.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java index 20fbe7b28d..9570ed428f 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java @@ -41,13 +41,6 @@ import org.junit.Test; public class ResourceNameHelperClassComposerTest { - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_MULTI_PATTERN = - "ResourceNameHelperClassComposerTestMultiPattern.golden"; - private static final String GOLDENFILES_SINGLE_PATTERN = - "ResourceNameHelperClassComposerTestOnePattern.golden"; - private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -186,7 +179,7 @@ public void generateResourceNameClass_echoFoobarMultiplePatterns() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_MULTI_PATTERN); + Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "FoobarName.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } @@ -211,7 +204,7 @@ public void generateResourceNameClass_testingSessionOnePattern() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_SINGLE_PATTERN); + Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "SessionName.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } // TODO(miraleung): Add more tests for a single pattern. diff --git a/src/test/java/com/google/api/generator/gapic/composer/RetrySettingsComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/RetrySettingsComposerTest.java index 27eedd2d68..be764f7073 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/RetrySettingsComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/RetrySettingsComposerTest.java @@ -61,8 +61,6 @@ import org.junit.Test; public class RetrySettingsComposerTest { - private static final String TESTFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/testdata/"; private static final VariableExpr RETRY_PARAM_DEFINITIONS_VAR_EXPR = createRetryParamDefinitionsVarExpr(); private static final VariableExpr RETRY_CODES_DEFINITIONS_VAR_EXPR = @@ -89,7 +87,7 @@ public void paramDefinitionsBlock_noConfigsFound() { Service service = services.get(0); String jsonFilename = "retrying_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional serviceConfigOpt = ServiceConfigParser.parse(jsonPath.toString(), Optional.empty()); assertTrue(serviceConfigOpt.isPresent()); @@ -126,7 +124,7 @@ public void paramDefinitionsBlock_basic() { Service service = services.get(0); String jsonFilename = "showcase_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional serviceConfigOpt = ServiceConfigParser.parse(jsonPath.toString(), Optional.empty()); assertTrue(serviceConfigOpt.isPresent()); @@ -167,7 +165,7 @@ public void codesDefinitionsBlock_noConfigsFound() { Service service = services.get(0); String jsonFilename = "retrying_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional serviceConfigOpt = ServiceConfigParser.parse(jsonPath.toString(), Optional.empty()); assertTrue(serviceConfigOpt.isPresent()); @@ -204,7 +202,7 @@ public void codesDefinitionsBlock_basic() { Service service = services.get(0); String jsonFilename = "showcase_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional serviceConfigOpt = ServiceConfigParser.parse(jsonPath.toString(), Optional.empty()); assertTrue(serviceConfigOpt.isPresent()); @@ -244,7 +242,7 @@ public void simpleBuilderExpr_basic() { Service service = services.get(0); String jsonFilename = "showcase_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional serviceConfigOpt = ServiceConfigParser.parse(jsonPath.toString(), Optional.empty()); assertTrue(serviceConfigOpt.isPresent()); @@ -326,7 +324,7 @@ public void lroBuilderExpr() { Service service = services.get(0); String jsonFilename = "showcase_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional serviceConfigOpt = ServiceConfigParser.parse(jsonPath.toString(), Optional.empty()); assertTrue(serviceConfigOpt.isPresent()); @@ -384,13 +382,13 @@ public void batchingSettings_minimalFlowControlSettings() { serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); String filename = "pubsub_gapic.yaml"; - Path path = Paths.get(TESTFILES_DIRECTORY, filename); + Path path = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, filename); Optional> batchingSettingsOpt = BatchingSettingsConfigParser.parse(Optional.of(path.toString())); assertTrue(batchingSettingsOpt.isPresent()); String jsonFilename = "pubsub_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional configOpt = ServiceConfigParser.parse(jsonPath.toString(), batchingSettingsOpt); assertTrue(configOpt.isPresent()); @@ -461,13 +459,13 @@ public void batchingSettings_fullFlowControlSettings() { serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); String filename = "logging_gapic.yaml"; - Path path = Paths.get(TESTFILES_DIRECTORY, filename); + Path path = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, filename); Optional> batchingSettingsOpt = BatchingSettingsConfigParser.parse(Optional.of(path.toString())); assertTrue(batchingSettingsOpt.isPresent()); String jsonFilename = "logging_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional configOpt = ServiceConfigParser.parse(jsonPath.toString(), batchingSettingsOpt); assertTrue(configOpt.isPresent()); diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java index ceda5a848c..0ba1c09956 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java @@ -36,10 +36,6 @@ import org.junit.Test; public class ServiceSettingsClassComposerTest { - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_NAME = "ServiceSettingsClassComposerTest.golden"; - private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -64,7 +60,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "EchoSettings.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java index 7845e2ef20..e282bec281 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java @@ -36,10 +36,6 @@ import org.junit.Test; public class ServiceStubClassComposerTest { - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String GOLDENFILES_NAME = "ServiceStubClassComposerTest.golden"; - private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; @@ -63,7 +59,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "EchoStub.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java index 8748d67872..da0308a349 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java @@ -50,16 +50,6 @@ import org.junit.Test; public class ServiceStubSettingsClassComposerTest { - private static final String GOLDENFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - private static final String TESTFILES_DIRECTORY = - "src/test/java/com/google/api/generator/gapic/testdata/"; - private static final String GOLDENFILES_NAME_LOGGING = - "ServiceStubSettingsClassComposerTestLogging.golden"; - private static final String GOLDENFILES_NAME_ECHO = - "ServiceStubSettingsClassComposerTestEcho.golden"; - private static final String GOLDENFILES_NAME_PUBLISHER = - "ServiceStubSettingsClassComposerTestPublisher.golden"; @Test public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() throws IOException { @@ -85,13 +75,13 @@ public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() thro parseServices(serviceFileDescriptor, serviceDescriptor, messageTypes, resourceNames); String filename = "logging_gapic.yaml"; - Path path = Paths.get(TESTFILES_DIRECTORY, filename); + Path path = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, filename); Optional> batchingSettingsOpt = BatchingSettingsConfigParser.parse(Optional.of(path.toString())); assertTrue(batchingSettingsOpt.isPresent()); String jsonFilename = "logging_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional configOpt = ServiceConfigParser.parse(jsonPath.toString(), batchingSettingsOpt); assertTrue(configOpt.isPresent()); @@ -103,7 +93,8 @@ public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() thro JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME_LOGGING); + Path goldenFilePath = + Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "LoggingServiceV2StubSettings.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } @@ -125,13 +116,13 @@ public void generateServiceStubSettingsClasses_batchingWithNonemptyResponses() parseServices(serviceFileDescriptor, serviceDescriptor, messageTypes, resourceNames); String filename = "pubsub_gapic.yaml"; - Path path = Paths.get(TESTFILES_DIRECTORY, filename); + Path path = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, filename); Optional> batchingSettingsOpt = BatchingSettingsConfigParser.parse(Optional.of(path.toString())); assertTrue(batchingSettingsOpt.isPresent()); String jsonFilename = "pubsub_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional configOpt = ServiceConfigParser.parse(jsonPath.toString(), batchingSettingsOpt); assertTrue(configOpt.isPresent()); @@ -144,7 +135,8 @@ public void generateServiceStubSettingsClasses_batchingWithNonemptyResponses() JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME_PUBLISHER); + Path goldenFilePath = + Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "PublisherStubSettings.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } @@ -160,7 +152,7 @@ public void generateServiceStubSettingsClasses_basic() throws IOException { parseServices(echoFileDescriptor, echoServiceDescriptor, messageTypes, resourceNames); String jsonFilename = "showcase_grpc_service_config.json"; - Path jsonPath = Paths.get(TESTFILES_DIRECTORY, jsonFilename); + Path jsonPath = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, jsonFilename); Optional configOpt = ServiceConfigParser.parse(jsonPath.toString(), Optional.empty()); assertTrue(configOpt.isPresent()); @@ -173,7 +165,8 @@ public void generateServiceStubSettingsClasses_basic() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME_ECHO); + Path goldenFilePath = + Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "EchoStubSettings.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceSettingsClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/EchoSettings.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceSettingsClassComposerTest.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/EchoSettings.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/EchoStub.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubClassComposerTest.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/EchoStub.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestEcho.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/EchoStubSettings.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestEcho.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/EchoStubSettings.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestMultiPattern.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/FoobarName.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestMultiPattern.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/FoobarName.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceCallableFactoryClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcEchoCallableFactory.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceCallableFactoryClassComposerTest.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcEchoCallableFactory.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceStubClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcEchoStub.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcServiceStubClassComposerTest.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/GrpcEchoStub.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestLogging.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/LoggingServiceV2StubSettings.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestLogging.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/LoggingServiceV2StubSettings.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/MockEcho.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceClassComposerTest.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/MockEcho.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceImplClassComposerTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/MockEchoImpl.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/MockServiceImplClassComposerTest.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/MockEchoImpl.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestPublisher.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/PublisherStubSettings.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/ServiceStubSettingsClassComposerTestPublisher.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/PublisherStubSettings.golden diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestOnePattern.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/SessionName.golden similarity index 100% rename from src/test/java/com/google/api/generator/gapic/composer/goldens/ResourceNameHelperClassComposerTestOnePattern.golden rename to src/test/java/com/google/api/generator/gapic/composer/goldens/SessionName.golden From 8360bf8bc2fea98ea184c0ccaed2b5c82934ade8 Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Thu, 24 Sep 2020 05:52:43 +0000 Subject: [PATCH 09/16] format --- .../com/google/api/generator/gapic/composer/BUILD.bazel | 2 +- .../api/generator/gapic/composer/ComposerConstants.java | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel index 9712f5f86d..932f3e9476 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel @@ -18,7 +18,7 @@ TESTS = [ filegroup( name = "composer_files", - srcs = ["{0}.java".format(f) for f in TESTS], + srcs = glob(["*.java"]), ) java_proto_library( diff --git a/src/test/java/com/google/api/generator/gapic/composer/ComposerConstants.java b/src/test/java/com/google/api/generator/gapic/composer/ComposerConstants.java index 2aa3704cb2..97d3b6b23b 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ComposerConstants.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ComposerConstants.java @@ -15,7 +15,8 @@ package com.google.api.generator.gapic.composer; public class ComposerConstants { - public static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/composer/goldens/"; - public static final String TESTFILES_DIRECTORY = + public static final String GOLDENFILES_DIRECTORY = + "src/test/java/com/google/api/generator/gapic/composer/goldens/"; + public static final String TESTFILES_DIRECTORY = "src/test/java/com/google/api/generator/gapic/testdata/"; -} \ No newline at end of file +} From b138429ca6bf09abd3627a0d4711d48a4b8f5936 Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Thu, 24 Sep 2020 05:55:46 +0000 Subject: [PATCH 10/16] format --- .../com/google/api/generator/engine/JavaCodeGeneratorTest.java | 3 +-- .../generator/gapic/composer/MockServiceClassComposerTest.java | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java b/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java index f262bb9e60..3383fb94b0 100644 --- a/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java +++ b/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java @@ -64,7 +64,6 @@ public class JavaCodeGeneratorTest { private static final String GOLDENFILES_DIRECTORY = "src/test/java/com/google/api/generator/engine/goldens/"; - private static final String GOLDENFILES_NAME = "JavaCodeGeneratorTest.golden"; // Create shared VaporReferences. private static final VaporReference stubRef = createVaporReference("com.google.gax.grpc", "Stub"); private static final VaporReference bookKindRef = @@ -173,7 +172,7 @@ public void validJavaClass() { .build(); JavaWriterVisitor javaWriterVisitor = new JavaWriterVisitor(); libraryServiceStubClass.accept(javaWriterVisitor); - Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, GOLDENFILES_NAME); + Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, "JavaCodeGeneratorTest.golden"); Assert.assertCodeEquals(goldenFilePath, javaWriterVisitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java index 87dbce90ea..5303ab557a 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java @@ -36,7 +36,6 @@ import org.junit.Test; public class MockServiceClassComposerTest { - private ServiceDescriptor echoService; private FileDescriptor echoFileDescriptor; From 97e2763950eff814d1c7916b5709d866076f37a7 Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Thu, 24 Sep 2020 18:24:22 +0000 Subject: [PATCH 11/16] support update goldens for ast integration test --- BUILD.bazel | 9 ++++++++- .../google/api/generator/engine/BUILD.bazel | 18 ++++++++++++++++++ .../engine/JavaCodeGeneratorTest.java | 3 +++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/BUILD.bazel b/BUILD.bazel index ba95d15151..5e676035af 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -52,9 +52,13 @@ java_binary( name = "junit_runner", srcs = [ "//src/test/java/com/google/api/generator/gapic/dummy:dummy_files", + "//src/test/java/com/google/api/generator/engine:engine_files", "//src/test/java/com/google/api/generator/test/framework:framework_files", ], - data = ["//src/test/java/com/google/api/generator/gapic/dummy/goldens:goldens_files"], + data = [ + "//src/test/java/com/google/api/generator/gapic/dummy/goldens:goldens_files", + "//src/test/java/com/google/api/generator/engine/goldens:goldens_files", + ], jvm_flags = ["-Xmx512m"], main_class = "com.google.api.generator.test.framework.SingleJUnitTestRunner", visibility = ["//visibility:public"], @@ -62,6 +66,9 @@ java_binary( "//src/main/java/com/google/api/generator/engine/ast", "//src/main/java/com/google/api/generator/engine/writer", "//src/test/java/com/google/api/generator/test/framework", + "//src/main/java/com/google/api/generator/engine/lexicon", + "@com_google_guava_guava//:com_google_guava_guava", + "@com_google_truth_truth//jar", "@io_github_java_diff_utils//jar", "@junit_junit//jar", "@org_hamcrest_hamcrest_core//jar", diff --git a/src/test/java/com/google/api/generator/engine/BUILD.bazel b/src/test/java/com/google/api/generator/engine/BUILD.bazel index 54b08dfd36..2dce9a9b88 100644 --- a/src/test/java/com/google/api/generator/engine/BUILD.bazel +++ b/src/test/java/com/google/api/generator/engine/BUILD.bazel @@ -1,3 +1,5 @@ +load("//:rules_bazel/java/java_diff_test.bzl", "updated_golden") + package(default_visibility = ["//visibility:public"]) filegroup( @@ -23,5 +25,21 @@ TESTS = [ "//src/main/java/com/google/api/generator/engine/writer", "//src/test/java/com/google/api/generator/test/framework", "@junit_junit//jar", + "@com_google_guava_guava//jar", + "@com_google_truth_truth//jar", ], ) for test_name in TESTS] + +TEST_CLASS_NAME = "com.google.api.generator.engine.JavaCodeGeneratorTest" + +# Run `bazel run src/test/java/com/google/api/generator/engine:JavaCodeGeneratorTest_update` +# to update goldens as expected generated code. +updated_golden( + name = "JavaCodeGeneratorTest_update", + srcs = [ + ":engine_files", + "//src/test/java/com/google/api/generator/engine/goldens:goldens_files", + "//src/test/java/com/google/api/generator/test/framework:framework_files", + ], + test_class_name = TEST_CLASS_NAME, +) diff --git a/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java b/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java index 3383fb94b0..8ed58c13cb 100644 --- a/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java +++ b/src/test/java/com/google/api/generator/engine/JavaCodeGeneratorTest.java @@ -50,6 +50,7 @@ import com.google.api.generator.engine.ast.WhileStatement; import com.google.api.generator.engine.writer.JavaWriterVisitor; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Path; @@ -172,6 +173,8 @@ public void validJavaClass() { .build(); JavaWriterVisitor javaWriterVisitor = new JavaWriterVisitor(); libraryServiceStubClass.accept(javaWriterVisitor); + Utils.saveCodegenToFile( + this.getClass(), "JavaCodeGeneratorTest.golden", javaWriterVisitor.write()); Path goldenFilePath = Paths.get(GOLDENFILES_DIRECTORY, "JavaCodeGeneratorTest.golden"); Assert.assertCodeEquals(goldenFilePath, javaWriterVisitor.write()); } From 6e71a8d8e023fe7922b552f4d49abbaddc5190da Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Thu, 24 Sep 2020 19:53:54 +0000 Subject: [PATCH 12/16] support update goldens for omposer tests --- BUILD.bazel | 15 +++++++++ rules_bazel/java/java_diff_test.bzl | 2 +- .../api/generator/gapic/composer/BUILD.bazel | 32 +++++++++++++++++++ .../BatchingDescriptorComposerTest.java | 7 ++++ .../gapic/composer/ComposerTest.java | 2 ++ ...rviceCallableFactoryClassComposerTest.java | 2 ++ .../GrpcServiceStubClassComposerTest.java | 2 ++ .../MockServiceClassComposerTest.java | 2 ++ .../MockServiceImplClassComposerTest.java | 2 ++ .../ResourceNameHelperClassComposerTest.java | 3 ++ .../ServiceSettingsClassComposerTest.java | 2 ++ .../ServiceStubClassComposerTest.java | 2 ++ .../ServiceStubSettingsClassComposerTest.java | 9 ++++-- ...ngDescriptorComposerTestSubresponse.golden | 2 +- 14 files changed, 80 insertions(+), 4 deletions(-) diff --git a/BUILD.bazel b/BUILD.bazel index 5e676035af..5e64347072 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -53,11 +53,15 @@ java_binary( srcs = [ "//src/test/java/com/google/api/generator/gapic/dummy:dummy_files", "//src/test/java/com/google/api/generator/engine:engine_files", + "//src/test/java/com/google/api/generator/gapic/composer:composer_files", "//src/test/java/com/google/api/generator/test/framework:framework_files", ], data = [ "//src/test/java/com/google/api/generator/gapic/dummy/goldens:goldens_files", "//src/test/java/com/google/api/generator/engine/goldens:goldens_files", + "//src/test/java/com/google/api/generator/gapic/composer/goldens:goldens_files", + "//src/test/java/com/google/api/generator/gapic/testdata:gapic_config_files", + "//src/test/java/com/google/api/generator/gapic/testdata:service_config_files", ], jvm_flags = ["-Xmx512m"], main_class = "com.google.api.generator.test.framework.SingleJUnitTestRunner", @@ -67,7 +71,18 @@ java_binary( "//src/main/java/com/google/api/generator/engine/writer", "//src/test/java/com/google/api/generator/test/framework", "//src/main/java/com/google/api/generator/engine/lexicon", + "//src/main/java/com/google/api/generator/gapic/composer", + "//src/main/java/com/google/api/generator/gapic/model", + "//src/main/java/com/google/api/generator/gapic/protoparser", + "//src/test/java/com/google/api/generator/gapic/testdata:showcase_java_proto", + "//src/test/java/com/google/api/generator/gapic/composer:common_resources_java_proto", "@com_google_guava_guava//:com_google_guava_guava", + "@com_google_api_gax_java//gax", + "@com_google_googleapis//google/logging/v2:logging_java_proto", + "@com_google_googleapis//google/pubsub/v1:pubsub_java_proto", + "@com_google_googleapis//google/rpc:rpc_java_proto", + "@com_google_protobuf//:protobuf_java", + "//:service_config_java_proto", "@com_google_truth_truth//jar", "@io_github_java_diff_utils//jar", "@junit_junit//jar", diff --git a/rules_bazel/java/java_diff_test.bzl b/rules_bazel/java/java_diff_test.bzl index 0b3ec96168..696594d709 100644 --- a/rules_bazel/java/java_diff_test.bzl +++ b/rules_bazel/java/java_diff_test.bzl @@ -39,7 +39,7 @@ junit_output_zip = rule( ), }, outputs = { - "output": "%{name}%.zip", + "output": "%{name}.zip", }, implementation = _junit_output_impl, ) diff --git a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel index 932f3e9476..70afd80770 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel @@ -1,3 +1,5 @@ +load("//:rules_bazel/java/java_diff_test.bzl", "updated_golden") + package(default_visibility = ["//visibility:public"]) TESTS = [ @@ -16,6 +18,19 @@ TESTS = [ "ServiceStubClassComposerTest", ] +UPDATE_GOLDENS_TESTS = [ + "BatchingDescriptorComposerTest", + "ComposerTest", + "GrpcServiceCallableFactoryClassComposerTest", + "GrpcServiceStubClassComposerTest", + "MockServiceClassComposerTest", + "MockServiceImplClassComposerTest", + "ResourceNameHelperClassComposerTest", + "ServiceSettingsClassComposerTest", + "ServiceStubSettingsClassComposerTest", + "ServiceStubClassComposerTest", +] + filegroup( name = "composer_files", srcs = glob(["*.java"]), @@ -63,3 +78,20 @@ java_proto_library( "@junit_junit//jar", ], ) for test_name in TESTS] + +TEST_CLASS_DIR = "com.google.api.generator.gapic.composer." +# Run `bazel run src/test/java/com/google/api/generator/gapic/composer:testTargetName_update` +# to update goldens as expected generated code. +# `ServiceClient*` tests are not supported now since they are still in active development. + +[updated_golden( + name = test_name + "_update", + srcs = [ + ":composer_files", + "//src/test/java/com/google/api/generator/gapic/testdata:gapic_config_files", + "//src/test/java/com/google/api/generator/gapic/testdata:service_config_files", + "//src/test/java/com/google/api/generator/gapic/composer/goldens:goldens_files", + "//src/test/java/com/google/api/generator/test/framework:framework_files", + ], + test_class_name = TEST_CLASS_DIR + test_name, +) for test_name in UPDATE_GOLDENS_TESTS] \ No newline at end of file diff --git a/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java index a556b191f0..8802489354 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposerTest.java @@ -29,6 +29,7 @@ import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.gapic.protoparser.ServiceConfigParser; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import com.google.logging.v2.LogEntryProto; import com.google.logging.v2.LoggingConfigProto; import com.google.logging.v2.LoggingMetricsProto; @@ -99,6 +100,8 @@ public void batchingDescriptor_hasSubresponseField() { method, batchingSetting, messageTypes); batchingDescriptorExpr.accept(writerVisitor); + Utils.saveCodegenToFile( + this.getClass(), "BatchingDescriptorComposerTestSubresponse.golden", writerVisitor.write()); Path goldenFilePath = Paths.get( ComposerConstants.GOLDENFILES_DIRECTORY, @@ -155,6 +158,10 @@ public void batchingDescriptor_noSubresponseField() { method, batchingSetting, messageTypes); batchingDescriptorExpr.accept(writerVisitor); + Utils.saveCodegenToFile( + this.getClass(), + "BatchingDescriptorComposerTestNoSubresponse.golden", + writerVisitor.write()); Path goldenFilePath = Paths.get( ComposerConstants.GOLDENFILES_DIRECTORY, diff --git a/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java index 3f2980bede..95270eecef 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ComposerTest.java @@ -20,6 +20,7 @@ import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.GapicClass.Kind; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; @@ -39,6 +40,7 @@ public void gapicClass_addApacheLicense() { Composer.addApacheLicense(Arrays.asList(GapicClass.create(Kind.TEST, classDef))); JavaWriterVisitor visitor = new JavaWriterVisitor(); gapicClassWithHeaderList.get(0).classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "ComposerTest.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "ComposerTest.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java index 32414a301b..4437b3a166 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceCallableFactoryClassComposerTest.java @@ -23,6 +23,7 @@ import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; @@ -60,6 +61,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "GrpcEchoCallableFactory.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "GrpcEchoCallableFactory.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); diff --git a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java index 53ea2c413e..e3f63dcaa8 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposerTest.java @@ -23,6 +23,7 @@ import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; @@ -59,6 +60,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "GrpcEchoStub.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "GrpcEchoStub.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java index 5303ab557a..aa4e19b271 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/MockServiceClassComposerTest.java @@ -23,6 +23,7 @@ import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; @@ -59,6 +60,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "MockEcho.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "MockEcho.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java index cd2fb25b2e..6e0295adb2 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/MockServiceImplClassComposerTest.java @@ -23,6 +23,7 @@ import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; @@ -60,6 +61,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "MockEchoImpl.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "MockEchoImpl.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java index 9570ed428f..80b4cb7788 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposerTest.java @@ -24,6 +24,7 @@ import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; @@ -179,6 +180,7 @@ public void generateResourceNameClass_echoFoobarMultiplePatterns() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "FoobarName.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "FoobarName.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } @@ -204,6 +206,7 @@ public void generateResourceNameClass_testingSessionOnePattern() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "SessionName.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "SessionName.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java index 0ba1c09956..17aa47ed38 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposerTest.java @@ -23,6 +23,7 @@ import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; @@ -60,6 +61,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "EchoSettings.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "EchoSettings.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java index e282bec281..87417b7c6e 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubClassComposerTest.java @@ -23,6 +23,7 @@ import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.showcase.v1beta1.EchoOuterClass; @@ -59,6 +60,7 @@ public void generateServiceClasses() { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "EchoStub.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "EchoStub.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java index da0308a349..f582cf7236 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposerTest.java @@ -28,6 +28,7 @@ import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.gapic.protoparser.ServiceConfigParser; import com.google.api.generator.test.framework.Assert; +import com.google.api.generator.test.framework.Utils; import com.google.logging.v2.LogEntryProto; import com.google.logging.v2.LoggingConfigProto; import com.google.logging.v2.LoggingMetricsProto; @@ -52,7 +53,7 @@ public class ServiceStubSettingsClassComposerTest { @Test - public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() throws IOException { + public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() { FileDescriptor serviceFileDescriptor = LoggingProto.getDescriptor(); ServiceDescriptor serviceDescriptor = serviceFileDescriptor.getServices().get(0); assertEquals(serviceDescriptor.getName(), "LoggingServiceV2"); @@ -93,6 +94,8 @@ public void generateServiceStubSettingsClasses_batchingWithEmptyResponses() thro JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile( + this.getClass(), "LoggingServiceV2StubSettings.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "LoggingServiceV2StubSettings.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); @@ -135,13 +138,14 @@ public void generateServiceStubSettingsClasses_batchingWithNonemptyResponses() JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "PublisherStubSettings.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "PublisherStubSettings.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } @Test - public void generateServiceStubSettingsClasses_basic() throws IOException { + public void generateServiceStubSettingsClasses_basic() { FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor(); ServiceDescriptor echoServiceDescriptor = echoFileDescriptor.getServices().get(0); assertEquals(echoServiceDescriptor.getName(), "Echo"); @@ -165,6 +169,7 @@ public void generateServiceStubSettingsClasses_basic() throws IOException { JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "EchoStubSettings.golden", visitor.write()); Path goldenFilePath = Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "EchoStubSettings.golden"); Assert.assertCodeEquals(goldenFilePath, visitor.write()); diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden index 1ebfca8696..a322c69aec 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden @@ -56,4 +56,4 @@ public long countBytes(PublishRequest request) { return request.getSerializedSize(); } -} +} \ No newline at end of file From 5d43a016d68b3752c7b03b8de29df11b3362514c Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Tue, 29 Sep 2020 02:05:51 +0000 Subject: [PATCH 13/16] fix --- .../api/generator/gapic/composer/BUILD.bazel | 34 +++++++++++++++++++ ...ngDescriptorComposerTestSubresponse.golden | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel index 1e86c323b6..c7e147a7ed 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel @@ -1,3 +1,5 @@ +load("//:rules_bazel/java/java_diff_test.bzl", "updated_golden") + package(default_visibility = ["//visibility:public"]) TESTS = [ @@ -18,6 +20,19 @@ TESTS = [ "ServiceStubClassComposerTest", ] +UPDATE_GOLDENS_TESTS = [ + "BatchingDescriptorComposerTest", + "ComposerTest", + "GrpcServiceCallableFactoryClassComposerTest", + "GrpcServiceStubClassComposerTest", + "MockServiceClassComposerTest", + "MockServiceImplClassComposerTest", + "ResourceNameHelperClassComposerTest", + "ServiceSettingsClassComposerTest", + "ServiceStubSettingsClassComposerTest", + "ServiceStubClassComposerTest", +] + filegroup( name = "composer_files", srcs = glob(["*.java"]), @@ -69,3 +84,22 @@ java_proto_library( "@junit_junit//jar", ], ) for test_name in TESTS] + + + +TEST_CLASS_DIR = "com.google.api.generator.gapic.composer." +# Run `bazel run src/test/java/com/google/api/generator/gapic/composer:testTargetName_update` +# to update goldens as expected generated code. +# `ServiceClient*` tests are not supported now since they are still in active development. + +[updated_golden( + name = test_name + "_update", + srcs = [ + ":composer_files", + "//src/test/java/com/google/api/generator/gapic/testdata:gapic_config_files", + "//src/test/java/com/google/api/generator/gapic/testdata:service_config_files", + "//src/test/java/com/google/api/generator/gapic/composer/goldens:goldens_files", + "//src/test/java/com/google/api/generator/test/framework:framework_files", + ], + test_class_name = TEST_CLASS_DIR + test_name, +) for test_name in UPDATE_GOLDENS_TESTS] diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden index 1ebfca8696..a322c69aec 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/BatchingDescriptorComposerTestSubresponse.golden @@ -56,4 +56,4 @@ public long countBytes(PublishRequest request) { return request.getSerializedSize(); } -} +} \ No newline at end of file From 31bd32c4269f8f02b4115d44a79f31766168286a Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Wed, 30 Sep 2020 04:46:50 +0000 Subject: [PATCH 14/16] update --- src/test/java/com/google/api/generator/engine/BUILD.bazel | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/com/google/api/generator/engine/BUILD.bazel b/src/test/java/com/google/api/generator/engine/BUILD.bazel index 2dce9a9b88..2cc9ca1e36 100644 --- a/src/test/java/com/google/api/generator/engine/BUILD.bazel +++ b/src/test/java/com/google/api/generator/engine/BUILD.bazel @@ -38,8 +38,6 @@ updated_golden( name = "JavaCodeGeneratorTest_update", srcs = [ ":engine_files", - "//src/test/java/com/google/api/generator/engine/goldens:goldens_files", - "//src/test/java/com/google/api/generator/test/framework:framework_files", ], test_class_name = TEST_CLASS_NAME, ) From bd2fba01a0f5246103dc740e19f28df5f2f92bf0 Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Thu, 1 Oct 2020 07:00:11 +0000 Subject: [PATCH 15/16] remove unneeded dependencies --- src/test/java/com/google/api/generator/engine/BUILD.bazel | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/com/google/api/generator/engine/BUILD.bazel b/src/test/java/com/google/api/generator/engine/BUILD.bazel index dbddf4a9d5..1bcbd20f5f 100644 --- a/src/test/java/com/google/api/generator/engine/BUILD.bazel +++ b/src/test/java/com/google/api/generator/engine/BUILD.bazel @@ -25,8 +25,6 @@ TESTS = [ "//src/main/java/com/google/api/generator/engine/writer", "//src/test/java/com/google/api/generator/test/framework", "@junit_junit//jar", - "@com_google_guava_guava//jar", - "@com_google_truth_truth//jar", ], ) for test_name in TESTS] From 8bef5b81c01f0b46be604764a27430137feff80e Mon Sep 17 00:00:00 2001 From: Xiaozhen Liu Date: Fri, 2 Oct 2020 17:13:58 +0000 Subject: [PATCH 16/16] remove unneeded dependencies --- .../java/com/google/api/generator/gapic/composer/BUILD.bazel | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel index 1ae87a0580..6e02d520d4 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/BUILD.bazel @@ -98,8 +98,6 @@ TEST_CLASS_DIR = "com.google.api.generator.gapic.composer." ":composer_files", "//src/test/java/com/google/api/generator/gapic/testdata:gapic_config_files", "//src/test/java/com/google/api/generator/gapic/testdata:service_config_files", - "//src/test/java/com/google/api/generator/gapic/composer/goldens:goldens_files", - "//src/test/java/com/google/api/generator/test/framework:framework_files", ], test_class_name = TEST_CLASS_DIR + test_name, ) for test_name in UPDATE_GOLDENS_TESTS]