From 90c4f38df675056042cd91ea0f410c4b6d77e4c8 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Tue, 27 Oct 2020 10:39:18 -0700 Subject: [PATCH 01/26] fix: support non-name fields with res-refs in resname def parsing --- .../gapic/protoparser/ResourceNameParser.java | 23 ++++++-- .../protoparser/ResourceNameParserTest.java | 53 ++++++++++++++++--- .../testdata/bad_message_resname_def.proto | 11 ++++ .../api/generator/gapic/testdata/locker.proto | 13 ++++- 4 files changed, 87 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/ResourceNameParser.java b/src/main/java/com/google/api/generator/gapic/protoparser/ResourceNameParser.java index 4a66becd4e..16e8f96beb 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/ResourceNameParser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/ResourceNameParser.java @@ -22,9 +22,11 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Strings; +import com.google.protobuf.DescriptorProtos.FieldOptions; import com.google.protobuf.DescriptorProtos.FileOptions; import com.google.protobuf.DescriptorProtos.MessageOptions; import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import java.util.ArrayList; import java.util.HashMap; @@ -107,12 +109,25 @@ static Optional parseResourceNameFromMessageType( } ResourceDescriptor protoResource = messageOptions.getExtension(ResourceProto.resource); - // aip.dev/4231. + // Validation - check that a resource name field is present. if (Strings.isNullOrEmpty(protoResource.getNameField())) { - Preconditions.checkNotNull( - messageTypeDescriptor.findFieldByName(ResourceNameConstants.NAME_FIELD_NAME), + // aip.dev/4231 + boolean resourceNameFieldFound = + messageTypeDescriptor.findFieldByName(ResourceNameConstants.NAME_FIELD_NAME) != null; + // If this is null, look for a field with a resource reference is found. + // Example: AccountBudgetProposal. + for (FieldDescriptor fieldDescriptor : messageTypeDescriptor.getFields()) { + FieldOptions fieldOptions = fieldDescriptor.getOptions(); + if (fieldOptions.hasExtension(ResourceProto.resourceReference)) { + resourceNameFieldFound = true; + break; + } + } + Preconditions.checkState( + resourceNameFieldFound, String.format( - "Message %s has a resource annotation but no \"name\" field", + "Message %s has a resource annotation but no field titled \"name\" or containing a" + + " resource reference", messageTypeDescriptor.getName())); } diff --git a/src/test/java/com/google/api/generator/gapic/protoparser/ResourceNameParserTest.java b/src/test/java/com/google/api/generator/gapic/protoparser/ResourceNameParserTest.java index c02a8f4427..9ecd696e3a 100644 --- a/src/test/java/com/google/api/generator/gapic/protoparser/ResourceNameParserTest.java +++ b/src/test/java/com/google/api/generator/gapic/protoparser/ResourceNameParserTest.java @@ -125,7 +125,7 @@ public void parseResourceNames_messageResourceDefinition() { List messageDescriptors = lockerServiceFileDescriptor.getMessageTypes(); Map typeStringsToResourceNames = ResourceNameParser.parseResourceNamesFromMessages(messageDescriptors, pakkage); - assertEquals(1, typeStringsToResourceNames.size()); + assertEquals(2, typeStringsToResourceNames.size()); ResourceName resourceName = typeStringsToResourceNames.get("testgapic.googleapis.com/Document"); assertEquals(2, resourceName.patterns().size()); @@ -140,7 +140,31 @@ public void parseResourceNames_messageResourceDefinition() { } @Test - public void parseResourceNames_messageWithoutResourceDefinition() { + public void parseResourceNames_badMessageResourceNameDefinitionMissingNameField() { + FileDescriptor protoFileDescriptor = BadMessageResnameDefProto.getDescriptor(); + List messageDescriptors = protoFileDescriptor.getMessageTypes(); + Descriptor messageDescriptor = messageDescriptors.get(0); + String pakkage = TypeParser.getPackage(protoFileDescriptor); + + assertThrows( + IllegalStateException.class, + () -> ResourceNameParser.parseResourceNameFromMessageType(messageDescriptor, pakkage)); + } + + @Test + public void parseResourceNameFromMessage_basicResourceDefinition() { + String pakkage = TypeParser.getPackage(lockerServiceFileDescriptor); + List messageDescriptors = lockerServiceFileDescriptor.getMessageTypes(); + Descriptor documentMessageDescriptor = messageDescriptors.get(0); + assertEquals("Document", documentMessageDescriptor.getName()); + Optional resourceNameOpt = + ResourceNameParser.parseResourceNameFromMessageType(documentMessageDescriptor, pakkage); + assertTrue(resourceNameOpt.isPresent()); + assertEquals("testgapic.googleapis.com/Document", resourceNameOpt.get().resourceTypeString()); + } + + @Test + public void parseResourceNamesFromMessage_noResourceDefinition() { String pakkage = TypeParser.getPackage(lockerServiceFileDescriptor); List messageDescriptors = lockerServiceFileDescriptor.getMessageTypes(); Descriptor folderMessageDescriptor = messageDescriptors.get(1); @@ -151,15 +175,28 @@ public void parseResourceNames_messageWithoutResourceDefinition() { } @Test - public void parseResourceNames_badMessageResourceNameDefinitionMissingNameField() { + public void parseResourceNameFromMessage_nonNameResourceReferenceField() { + String pakkage = TypeParser.getPackage(lockerServiceFileDescriptor); + List messageDescriptors = lockerServiceFileDescriptor.getMessageTypes(); + Descriptor binderMessageDescriptor = messageDescriptors.get(2); + assertEquals("Binder", binderMessageDescriptor.getName()); + Optional resourceNameOpt = + ResourceNameParser.parseResourceNameFromMessageType(binderMessageDescriptor, pakkage); + assertTrue(resourceNameOpt.isPresent()); + assertEquals("testgapic.googleapis.com/Binder", resourceNameOpt.get().resourceTypeString()); + } + + @Test + public void parseResourceNamesFromMessage_noNameOrResourceReferenceField() { FileDescriptor protoFileDescriptor = BadMessageResnameDefProto.getDescriptor(); - List messageDescriptors = protoFileDescriptor.getMessageTypes(); - Descriptor messageDescriptor = messageDescriptors.get(0); String pakkage = TypeParser.getPackage(protoFileDescriptor); - + List messageDescriptors = protoFileDescriptor.getMessageTypes(); + Descriptor pencilMessageDescriptor = messageDescriptors.get(1); + assertEquals("Pencil", pencilMessageDescriptor.getName()); assertThrows( - NullPointerException.class, - () -> ResourceNameParser.parseResourceNameFromMessageType(messageDescriptor, pakkage)); + IllegalStateException.class, + () -> + ResourceNameParser.parseResourceNameFromMessageType(pencilMessageDescriptor, pakkage)); } @Test diff --git a/src/test/java/com/google/api/generator/gapic/testdata/bad_message_resname_def.proto b/src/test/java/com/google/api/generator/gapic/testdata/bad_message_resname_def.proto index 705082e96a..c79e10b9b8 100644 --- a/src/test/java/com/google/api/generator/gapic/testdata/bad_message_resname_def.proto +++ b/src/test/java/com/google/api/generator/gapic/testdata/bad_message_resname_def.proto @@ -32,3 +32,14 @@ message BarFoo { string display_name = 1; } + +// A proto with a resource definition, but missing a field titled "name" or +// containing a resource reference. +message Pencil { + option (google.api.resource) = { + type: "testgapic.googleapis.com/Pencil" + pattern: "pencils/{pencil}" + }; + + string owner = 1; +} diff --git a/src/test/java/com/google/api/generator/gapic/testdata/locker.proto b/src/test/java/com/google/api/generator/gapic/testdata/locker.proto index a6744c7bbe..9be138d33a 100644 --- a/src/test/java/com/google/api/generator/gapic/testdata/locker.proto +++ b/src/test/java/com/google/api/generator/gapic/testdata/locker.proto @@ -79,7 +79,7 @@ message Document { pattern: "*" }; - // The resource name of the user. + // The resource name of the document. string name = 1; } @@ -88,6 +88,17 @@ message Folder { "cloudresourcemanager.googleapis.com/Folder"]; } +message Binder { + option (google.api.resource) = { + type: "testgapic.googleapis.com/Binder" + pattern: "binders/{binder}" + }; + + // The resource name of the binder. + string binder_name = 1 [(google.api.resource_reference).type = + "testgapic.googleapis.com/Binder"]; +} + message GetFolderRequest { string name = 1 [ (google.api.resource_reference).type = From a74be70e02235ef30cb38cf5bba53db51e17f11c Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Tue, 27 Oct 2020 13:02:43 -0700 Subject: [PATCH 02/26] fix: add workaround for missing default_host and oauth_scopes annotation --- .../generator/gapic/protoparser/Parser.java | 44 ++++++++++++------- .../BatchingDescriptorComposerTest.java | 12 ++++- ...rviceCallableFactoryClassComposerTest.java | 4 +- .../GrpcServiceStubClassComposerTest.java | 16 +++++-- .../MockServiceClassComposerTest.java | 4 +- .../MockServiceImplClassComposerTest.java | 4 +- .../ResourceNameHelperClassComposerTest.java | 10 ++++- .../composer/RetrySettingsComposerTest.java | 30 +++++++++---- .../ServiceClientClassComposerTest.java | 7 ++- .../ServiceClientTestClassComposerTest.java | 16 +++++-- .../ServiceSettingsClassComposerTest.java | 4 +- .../ServiceStubClassComposerTest.java | 4 +- .../ServiceStubSettingsClassComposerTest.java | 2 +- .../gapic/model/GapicServiceConfigTest.java | 3 +- .../gapic/protoparser/ParserTest.java | 4 +- 15 files changed, 121 insertions(+), 43 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java index 8c2ca268eb..40440d7ee0 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java @@ -130,7 +130,12 @@ public static List parseServices( fileToGenerate); services.addAll( - parseService(fileDescriptor, messageTypes, resourceNames, outputArgResourceNames)); + parseService( + fileDescriptor, + messageTypes, + resourceNames, + serviceYamlProtoOpt, + outputArgResourceNames)); } return services; @@ -140,28 +145,37 @@ public static List parseService( FileDescriptor fileDescriptor, Map messageTypes, Map resourceNames, + Optional serviceYamlProtoOpt, Set outputArgResourceNames) { String pakkage = TypeParser.getPackage(fileDescriptor); return fileDescriptor.getServices().stream() .map( s -> { - // TODO(miraleung, v2): Handle missing default_host and oauth_scopes annotations. + // Workaround for a missing default_host and oauth_scopes annotation from a service + // definition. This can happen for protos that bypass the publishing process. + // TODO(miraleung): Remove this workaround later? ServiceOptions serviceOptions = s.getOptions(); - // The proto publishing process will insert these two fields from the 1P esrvice - // config YAML file, so we can assume they must be present for v1 for the - // microgenerator. - Preconditions.checkState( - serviceOptions.hasExtension(ClientProto.defaultHost), - String.format("Default host annotation not found in service %s", s.getName())); + String defaultHost = null; + if (serviceOptions.hasExtension(ClientProto.defaultHost)) { + defaultHost = + sanitizeDefaultHost(serviceOptions.getExtension(ClientProto.defaultHost)); + } else if (serviceYamlProtoOpt.isPresent()) { + // Fall back to the DNS name supplied in the service .yaml config. + defaultHost = serviceYamlProtoOpt.get().getName(); + } Preconditions.checkState( - serviceOptions.hasExtension(ClientProto.oauthScopes), - String.format("Oauth scopes annotation not found in service %s", s.getName())); - - String defaultHost = - sanitizeDefaultHost(serviceOptions.getExtension(ClientProto.defaultHost)); - List oauthScopes = - Arrays.asList(serviceOptions.getExtension(ClientProto.oauthScopes).split(COMMA)); + !Strings.isNullOrEmpty(defaultHost), + String.format( + "Default host not found in service YAML config file or annotation for %s", + s.getName())); + + List oauthScopes = Collections.emptyList(); + if (serviceOptions.hasExtension(ClientProto.oauthScopes)) { + oauthScopes = + Arrays.asList( + serviceOptions.getExtension(ClientProto.oauthScopes).split(COMMA)); + } Service.Builder serviceBuilder = Service.builder(); if (fileDescriptor.toProto().hasSourceCodeInfo()) { 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 8802489354..e2d366370e 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 @@ -74,7 +74,11 @@ public void batchingDescriptor_hasSubresponseField() { Set outputResourceNames = new HashSet<>(); List services = Parser.parseService( - serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); + serviceFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); String filename = "pubsub_gapic.yaml"; Path path = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, filename); @@ -132,7 +136,11 @@ public void batchingDescriptor_noSubresponseField() { Set outputResourceNames = new HashSet<>(); List services = Parser.parseService( - serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); + serviceFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); String filename = "logging_gapic.yaml"; Path path = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, filename); 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 4437b3a166..bc1f8d0c09 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 @@ -32,6 +32,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -53,7 +54,8 @@ public void generateServiceClasses() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); Service echoProtoService = services.get(0); GapicClass clazz = 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 28f7bec18f..47c7767d45 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,6 +36,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.junit.Test; @@ -50,7 +51,8 @@ public void generateGrpcServiceStubClass_simple() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); Service echoProtoService = services.get(0); GapicClass clazz = GrpcServiceStubClassComposer.instance().generate(echoProtoService, messageTypes); @@ -73,7 +75,11 @@ public void generateGrpcServiceStubClass_httpBindings() { Set outputResourceNames = new HashSet<>(); List services = Parser.parseService( - testingFileDescriptor, messageTypes, resourceNames, outputResourceNames); + testingFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); Service testingProtoService = services.get(0); GapicClass clazz = GrpcServiceStubClassComposer.instance().generate(testingProtoService, messageTypes); @@ -102,7 +108,11 @@ public void generateGrpcServiceStubClass_httpBindingsWithSubMessageFields() { Set outputResourceNames = new HashSet<>(); List services = Parser.parseService( - serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); + serviceFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); Service service = services.get(0); GapicClass clazz = GrpcServiceStubClassComposer.instance().generate(service, messageTypes); 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 aa4e19b271..61785acb7b 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 @@ -32,6 +32,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -53,7 +54,8 @@ public void generateServiceClasses() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); Service echoProtoService = services.get(0); GapicClass clazz = MockServiceClassComposer.instance().generate(echoProtoService, messageTypes); 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 6e0295adb2..624126bb96 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 @@ -32,6 +32,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -53,7 +54,8 @@ public void generateServiceClasses() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); Service echoProtoService = services.get(0); GapicClass clazz = 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 39b76b2d85..cf29462c31 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 @@ -35,6 +35,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -88,7 +89,8 @@ public void generateResourceNameClass_echoFoobarMultiplePatterns() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); ResourceName foobarResname = resourceNames.get("showcase.googleapis.com/Foobar"); assertThat(outputResourceNames).contains(foobarResname); @@ -114,7 +116,11 @@ public void generateResourceNameClass_testingSessionOnePattern() { Set outputResourceNames = new HashSet<>(); List services = Parser.parseService( - testingFileDescriptor, messageTypes, resourceNames, outputResourceNames); + testingFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); ResourceName sessionResname = resourceNames.get("showcase.googleapis.com/Session"); assertThat(outputResourceNames).contains(sessionResname); 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 be764f7073..a0f74f2052 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 @@ -81,7 +81,8 @@ public void paramDefinitionsBlock_noConfigsFound() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); assertEquals(1, services.size()); Service service = services.get(0); @@ -118,7 +119,8 @@ public void paramDefinitionsBlock_basic() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); assertEquals(1, services.size()); Service service = services.get(0); @@ -159,7 +161,8 @@ public void codesDefinitionsBlock_noConfigsFound() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); assertEquals(1, services.size()); Service service = services.get(0); @@ -196,7 +199,8 @@ public void codesDefinitionsBlock_basic() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); assertEquals(1, services.size()); Service service = services.get(0); @@ -236,7 +240,8 @@ public void simpleBuilderExpr_basic() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); assertEquals(1, services.size()); Service service = services.get(0); @@ -318,7 +323,8 @@ public void lroBuilderExpr() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); assertEquals(1, services.size()); Service service = services.get(0); @@ -379,7 +385,11 @@ public void batchingSettings_minimalFlowControlSettings() { Set outputResourceNames = new HashSet<>(); List services = Parser.parseService( - serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); + serviceFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); String filename = "pubsub_gapic.yaml"; Path path = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, filename); @@ -456,7 +466,11 @@ public void batchingSettings_fullFlowControlSettings() { Set outputResourceNames = new HashSet<>(); List services = Parser.parseService( - serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); + serviceFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); String filename = "logging_gapic.yaml"; Path path = Paths.get(ComposerConstants.TESTFILES_DIRECTORY, filename); 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 7e2f8d24d0..1a882a6a30 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 @@ -33,6 +33,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.junit.Test; @@ -47,7 +48,8 @@ public void generateServiceClasses() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); Service echoProtoService = services.get(0); GapicClass clazz = @@ -70,7 +72,8 @@ public void generateServiceClasses_methodSignatureHasNestedFields() { Map resourceNames = Parser.parseResourceNames(fileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(fileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + fileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); Service protoService = services.get(0); GapicClass clazz = ServiceClientClassComposer.instance().generate(protoService, messageTypes); 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 7a4c45c510..358b830b5e 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 @@ -40,6 +40,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.junit.Test; @@ -54,7 +55,8 @@ public void generateClientTest_echoClient() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); Service echoProtoService = services.get(0); GapicClass clazz = @@ -85,7 +87,11 @@ public void generateClientTest_pubSubPublisherClient() { Set outputResourceNames = new HashSet<>(); List services = Parser.parseService( - serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); + serviceFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); Service subscriptionService = services.get(1); assertEquals("Subscriber", subscriptionService.name()); @@ -128,7 +134,11 @@ public void generateClientTest_logging() { Set outputResourceNames = new HashSet<>(); List services = Parser.parseService( - serviceFileDescriptor, messageTypes, resourceNames, outputResourceNames); + serviceFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); Service loggingService = services.get(0); GapicClass clazz = 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 17aa47ed38..bd7b41eb16 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 @@ -32,6 +32,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -53,7 +54,8 @@ public void generateServiceClasses() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); Service echoProtoService = services.get(0); GapicClass clazz = 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 87417b7c6e..2e7a390b0b 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 @@ -32,6 +32,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -53,7 +54,8 @@ public void generateServiceClasses() { Map resourceNames = Parser.parseResourceNames(echoFileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); Service echoProtoService = services.get(0); GapicClass clazz = ServiceStubClassComposer.instance().generate(echoProtoService, messageTypes); 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 21048a3189..527e513101 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 @@ -182,6 +182,6 @@ private static List parseServices( Map resourceNames) { Set outputResourceNames = new HashSet<>(); return Parser.parseService( - protoFileDescriptor, messageTypes, resourceNames, outputResourceNames); + protoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); } } diff --git a/src/test/java/com/google/api/generator/gapic/model/GapicServiceConfigTest.java b/src/test/java/com/google/api/generator/gapic/model/GapicServiceConfigTest.java index 7d1ba5c9d5..43564350d5 100644 --- a/src/test/java/com/google/api/generator/gapic/model/GapicServiceConfigTest.java +++ b/src/test/java/com/google/api/generator/gapic/model/GapicServiceConfigTest.java @@ -209,7 +209,8 @@ private static Service parseService(FileDescriptor fileDescriptor) { Map resourceNames = Parser.parseResourceNames(fileDescriptor); Set outputResourceNames = new HashSet<>(); List services = - Parser.parseService(fileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + fileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); assertEquals(1, services.size()); return services.get(0); diff --git a/src/test/java/com/google/api/generator/gapic/protoparser/ParserTest.java b/src/test/java/com/google/api/generator/gapic/protoparser/ParserTest.java index 5668d86445..d092b7111b 100644 --- a/src/test/java/com/google/api/generator/gapic/protoparser/ParserTest.java +++ b/src/test/java/com/google/api/generator/gapic/protoparser/ParserTest.java @@ -41,6 +41,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -371,7 +372,8 @@ public void parseResourceNames_inputTypeHasReferenceNotInMethodSignature() { Map messageTypes = Parser.parseMessages(testingFileDescriptor); Map resourceNames = Parser.parseResourceNames(testingFileDescriptor); Set outputResourceNames = new HashSet<>(); - Parser.parseService(testingFileDescriptor, messageTypes, resourceNames, outputResourceNames); + Parser.parseService( + testingFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames); assertEquals(2, outputResourceNames.size()); From fdb1ffb761f96a336b21c127b146599a4560c2e2 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Tue, 27 Oct 2020 13:19:07 -0700 Subject: [PATCH 03/26] fix: clarify LRO parsing error messages --- .../google/api/generator/gapic/protoparser/Parser.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java index 40440d7ee0..3f56eac203 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java @@ -367,10 +367,16 @@ static LongrunningOperation parseLro( Message responseMessage = messageTypes.get(responseTypeName); Message metadataMessage = messageTypes.get(metadataTypeName); Preconditions.checkNotNull( - responseMessage, String.format("LRO response message %s not found", responseTypeName)); + responseMessage, + String.format( + "LRO response message %s not found on method %s", + responseTypeName, methodDescriptor.getName())); // TODO(miraleung): Check that the packages are equal if those strings are not empty. Preconditions.checkNotNull( - metadataMessage, String.format("LRO metadata message %s not found", metadataTypeName)); + metadataMessage, + String.format( + "LRO metadata message %s not found in method %s", + metadataTypeName, methodDescriptor.getName())); return LongrunningOperation.withTypes(responseMessage.type(), metadataMessage.type()); } From 642c6060336abd7af402dc5d43b0ff264ba4750b Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Tue, 27 Oct 2020 18:32:29 -0700 Subject: [PATCH 04/26] feat: support deeply-nested types in AST and proto message parsing --- .../engine/ast/ConcreteReference.java | 13 ++++- .../api/generator/engine/ast/Reference.java | 2 +- .../generator/engine/ast/VaporReference.java | 36 ++++++------ .../engine/writer/ImportWriterVisitor.java | 7 ++- .../composer/BatchingDescriptorComposer.java | 2 +- .../GrpcServiceStubClassComposer.java | 2 +- .../ResourceNameHelperClassComposer.java | 4 +- .../composer/ServiceClientClassComposer.java | 4 +- .../ServiceClientTestClassComposer.java | 4 +- .../ServiceSettingsClassComposer.java | 8 +-- .../composer/ServiceStubClassComposer.java | 2 +- .../ServiceStubSettingsClassComposer.java | 7 ++- .../api/generator/gapic/model/Message.java | 10 +++- .../generator/gapic/protoparser/Parser.java | 50 +++++++++++------ .../gapic/protoparser/TypeParser.java | 47 ++++++++++------ .../engine/ast/VaporReferenceTest.java | 12 ++-- .../generator/gapic/protoparser/BUILD.bazel | 1 + .../gapic/protoparser/TypeParserTest.java | 55 +++++++++++++++++++ .../api/generator/gapic/testdata/BUILD.bazel | 1 + .../gapic/testdata/nested_message.proto | 36 ++++++++++++ 20 files changed, 225 insertions(+), 78 deletions(-) create mode 100644 src/test/java/com/google/api/generator/gapic/protoparser/TypeParserTest.java create mode 100644 src/test/java/com/google/api/generator/gapic/testdata/nested_message.proto diff --git a/src/main/java/com/google/api/generator/engine/ast/ConcreteReference.java b/src/main/java/com/google/api/generator/engine/ast/ConcreteReference.java index 58494fe7a5..bb92b2bebf 100644 --- a/src/main/java/com/google/api/generator/engine/ast/ConcreteReference.java +++ b/src/main/java/com/google/api/generator/engine/ast/ConcreteReference.java @@ -89,11 +89,18 @@ public String pakkage() { public abstract boolean useFullName(); @Override - public String enclosingClassName() { + public ImmutableList enclosingClassNames() { if (!hasEnclosingClass()) { - return null; + return ImmutableList.of(); } - return clazz().getEnclosingClass().getSimpleName(); + // The innermost type will be the last element in the list. + ImmutableList.Builder listBuilder = new ImmutableList.Builder<>(); + Class currentClz = clazz(); + while (currentClz.getEnclosingClass() != null) { + listBuilder.add(currentClz.getEnclosingClass().getSimpleName()); + currentClz = currentClz.getEnclosingClass(); + } + return listBuilder.build(); } @Override diff --git a/src/main/java/com/google/api/generator/engine/ast/Reference.java b/src/main/java/com/google/api/generator/engine/ast/Reference.java index ed26731f0f..7031b5cbe6 100644 --- a/src/main/java/com/google/api/generator/engine/ast/Reference.java +++ b/src/main/java/com/google/api/generator/engine/ast/Reference.java @@ -30,7 +30,7 @@ public interface Reference { boolean useFullName(); @Nullable - String enclosingClassName(); + ImmutableList enclosingClassNames(); @Nullable Reference wildcardUpperBound(); diff --git a/src/main/java/com/google/api/generator/engine/ast/VaporReference.java b/src/main/java/com/google/api/generator/engine/ast/VaporReference.java index cd9361ebe3..a2f0176c36 100644 --- a/src/main/java/com/google/api/generator/engine/ast/VaporReference.java +++ b/src/main/java/com/google/api/generator/engine/ast/VaporReference.java @@ -15,9 +15,9 @@ package com.google.api.generator.engine.ast; import com.google.auto.value.AutoValue; -import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Objects; import javax.annotation.Nullable; @@ -43,7 +43,7 @@ public abstract class VaporReference implements Reference { @Nullable @Override - public abstract String enclosingClassName(); + public abstract ImmutableList enclosingClassNames(); @Nullable public abstract Reference supertypeReference(); @@ -56,9 +56,9 @@ public Reference wildcardUpperBound() { @Override public String fullName() { - // TODO(unsupported): Nested classes with depth greater than 1. if (hasEnclosingClass()) { - return String.format("%s.%s.%s", pakkage(), enclosingClassName(), plainName()); + return String.format( + "%s.%s.%s", pakkage(), String.join(DOT, enclosingClassNames()), plainName()); } return String.format("%s.%s", pakkage(), plainName()); } @@ -68,7 +68,7 @@ public String fullName() { @Override public boolean hasEnclosingClass() { - return !Strings.isNullOrEmpty(enclosingClassName()); + return !enclosingClassNames().isEmpty(); } @Override @@ -86,7 +86,7 @@ public boolean isSupertypeOrEquals(Reference other) { VaporReference ref = (VaporReference) other; return pakkage().equals(ref.pakkage()) && plainName().equals(ref.plainName()) - && Objects.equals(enclosingClassName(), ref.enclosingClassName()); + && Objects.equals(enclosingClassNames(), ref.enclosingClassNames()); } @Override @@ -112,14 +112,14 @@ public boolean equals(Object o) { return pakkage().equals(ref.pakkage()) && name().equals(ref.name()) && generics().equals(ref.generics()) - && Objects.equals(enclosingClassName(), ref.enclosingClassName()); + && Objects.equals(enclosingClassNames(), ref.enclosingClassNames()); } @Override public int hashCode() { int hash = 17 * pakkage().hashCode() + 19 * name().hashCode() + 23 * generics().hashCode(); - if (!Strings.isNullOrEmpty(enclosingClassName())) { - hash += 29 * enclosingClassName().hashCode(); + if (!enclosingClassNames().isEmpty()) { + hash += 29 * enclosingClassNames().hashCode(); } return hash; } @@ -133,7 +133,8 @@ public static Builder builder() { return new AutoValue_VaporReference.Builder() .setUseFullName(false) .setGenerics(ImmutableList.of()) - .setIsStaticImport(false); + .setIsStaticImport(false) + .setEnclosingClassNames(Collections.emptyList()); } // Private. @@ -153,7 +154,11 @@ public Builder setGenerics(Reference... references) { public abstract Builder setGenerics(List clazzes); - public abstract Builder setEnclosingClassName(String enclosingClassName); + public Builder setEnclosingClassNames(String... enclosingClassNames) { + return setEnclosingClassNames(Arrays.asList(enclosingClassNames)); + } + + public abstract Builder setEnclosingClassNames(List enclosingClassNames); public abstract Builder setIsStaticImport(boolean isStaticImport); @@ -166,8 +171,7 @@ public Builder setGenerics(Reference... references) { abstract ImmutableList generics(); - @Nullable - abstract String enclosingClassName(); + abstract ImmutableList enclosingClassNames(); abstract boolean isStaticImport(); @@ -180,11 +184,11 @@ public VaporReference build() { setPlainName(name()); - setIsStaticImport(enclosingClassName() != null && isStaticImport()); + setIsStaticImport(!enclosingClassNames().isEmpty() && isStaticImport()); StringBuilder sb = new StringBuilder(); - if (enclosingClassName() != null && !isStaticImport()) { - sb.append(enclosingClassName()); + if (!enclosingClassNames().isEmpty() && !isStaticImport()) { + sb.append(String.join(DOT, enclosingClassNames())); sb.append(DOT); } diff --git a/src/main/java/com/google/api/generator/engine/writer/ImportWriterVisitor.java b/src/main/java/com/google/api/generator/engine/writer/ImportWriterVisitor.java index af456a33db..a040823e7b 100644 --- a/src/main/java/com/google/api/generator/engine/writer/ImportWriterVisitor.java +++ b/src/main/java/com/google/api/generator/engine/writer/ImportWriterVisitor.java @@ -68,6 +68,7 @@ import javax.annotation.Nullable; public class ImportWriterVisitor implements AstNodeVisitor { + private static final String DOT = "."; private static final String NEWLINE = "\n"; private static final String PKG_JAVA_LANG = "java.lang"; @@ -423,7 +424,8 @@ private void references(List refs) { if (ref.isStaticImport() && !Strings.isNullOrEmpty(currentClassName) - && ref.enclosingClassName().equals(currentClassName)) { + && !ref.enclosingClassNames().isEmpty() + && ref.enclosingClassNames().contains(currentClassName)) { continue; } @@ -432,7 +434,8 @@ private void references(List refs) { staticImports.add(ref.fullName()); } else { if (ref.hasEnclosingClass()) { - imports.add(String.format("%s.%s", ref.pakkage(), ref.enclosingClassName())); + imports.add( + String.format("%s.%s", ref.pakkage(), String.join(DOT, ref.enclosingClassNames()))); } else { imports.add(ref.fullName()); } diff --git a/src/main/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposer.java b/src/main/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposer.java index 5d15f481e0..4202809ce1 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/BatchingDescriptorComposer.java @@ -153,7 +153,7 @@ private static MethodDefinition createGetRequestBuilderMethod( TypeNode builderType = TypeNode.withReference( VaporReference.builder() - .setEnclosingClassName(method.inputType().reference().name()) + .setEnclosingClassNames(method.inputType().reference().name()) .setName("Builder") .setPakkage(method.inputType().reference().pakkage()) .build()); diff --git a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java index 0d688dfc47..b556f03dcb 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java @@ -1049,7 +1049,7 @@ private static Map createDynamicTypes(Service service, String VaporReference.builder() .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) .setPakkage(service.pakkage()) - .setEnclosingClassName(String.format("%sClient", service.name())) + .setEnclosingClassNames(String.format("%sClient", service.name())) .setIsStaticImport(true) .build())))); return types; diff --git a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java index 8fcb09896b..c1e499fbec 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java @@ -1575,7 +1575,7 @@ private static Map createDynamicTypes( VaporReference.builder() .setName("Builder") .setPakkage(resourceName.pakkage()) - .setEnclosingClassName(thisClassName) + .setEnclosingClassNames(thisClassName) .setIsStaticImport(true) .build())); @@ -1591,7 +1591,7 @@ private static Map createDynamicTypes( VaporReference.builder() .setName(s) .setPakkage(resourceName.pakkage()) - .setEnclosingClassName(thisClassName) + .setEnclosingClassNames(thisClassName) .setIsStaticImport(true) .build())))); } diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java index 9c6b88bfba..87f9cbcdca 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java @@ -1440,7 +1440,7 @@ private static Map createVaporTypes(Service service) { VaporReference.builder() .setName( String.format(t, JavaStyle.toUpperCamelCase(method.name()))) - .setEnclosingClassName(getClientClassName(service.name())) + .setEnclosingClassNames(getClientClassName(service.name())) .setPakkage(service.pakkage()) .setIsStaticImport(true) // Same class, so they won't be imported. .build())))); @@ -1465,7 +1465,7 @@ private static Map createVaporTypes(Service service) { VaporReference.builder() .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) .setPakkage(service.pakkage()) - .setEnclosingClassName(getClientClassName(service.name())) + .setEnclosingClassNames(getClientClassName(service.name())) .setIsStaticImport(true) .build())))); return types; diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java index 3c18458963..0b2b9cf020 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java @@ -1749,7 +1749,7 @@ private static Map createDynamicTypes(Service service) { VaporReference.builder() .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) .setPakkage(service.pakkage()) - .setEnclosingClassName(getClientClassName(service.name())) + .setEnclosingClassNames(getClientClassName(service.name())) .setIsStaticImport(true) .build())))); return types; @@ -1864,7 +1864,7 @@ private static TypeNode getPagedResponseType(Method method, Service service) { VaporReference.builder() .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, method.name())) .setPakkage(service.pakkage()) - .setEnclosingClassName(getClientClassName(service.name())) + .setEnclosingClassNames(getClientClassName(service.name())) .setIsStaticImport(true) .build()); } diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java index accb22d978..45f625f32f 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceSettingsClassComposer.java @@ -230,7 +230,7 @@ private static MethodDefinition createCreatorMethod( TypeNode.withReference( VaporReference.builder() .setName("Builder") - .setEnclosingClassName(String.format("%sSettings", service.name())) + .setEnclosingClassNames(String.format("%sSettings", service.name())) .setPakkage(service.pakkage()) .build()); Expr returnMethodExpr = @@ -712,7 +712,7 @@ private static Map createDynamicTypes(Service service) { TypeNode.withReference( VaporReference.builder() .setName(BUILDER_CLASS_NAME) - .setEnclosingClassName(getThisClassName(service.name())) + .setEnclosingClassNames(getThisClassName(service.name())) .setPakkage(service.pakkage()) .setIsStaticImport(true) .build())); @@ -729,7 +729,7 @@ private static Map createDynamicTypes(Service service) { VaporReference.builder() .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) .setPakkage(service.pakkage()) - .setEnclosingClassName(getClientClassName(service.name())) + .setEnclosingClassNames(getClientClassName(service.name())) .setIsStaticImport(true) .build())))); return types; @@ -828,7 +828,7 @@ private static TypeNode getStubSettingsBuilderType(Service service) { VaporReference.builder() .setPakkage(service.pakkage()) .setName(BUILDER_CLASS_NAME) - .setEnclosingClassName(getStubSettingsClassName(service.name())) + .setEnclosingClassNames(getStubSettingsClassName(service.name())) .build()); } diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java index 6afbf9256b..ce1f79727e 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java @@ -262,7 +262,7 @@ private static Map createTypes( VaporReference.builder() .setName(String.format(PAGED_RESPONSE_TYPE_NAME_PATTERN, m.name())) .setPakkage(service.pakkage()) - .setEnclosingClassName(getClientClassName(service.name())) + .setEnclosingClassNames(getClientClassName(service.name())) .setIsStaticImport(true) .build())))); diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java index 2b35fcf842..ede0311809 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubSettingsClassComposer.java @@ -133,6 +133,7 @@ public class ServiceStubSettingsClassComposer { private static final String OPERATION_SETTINGS_LITERAL = "OperationSettings"; private static final String SETTINGS_LITERAL = "Settings"; + private static final String DOT = "."; private static final String LEFT_BRACE = "{"; private static final String RIGHT_BRACE = "}"; private static final String SLASH = "/"; @@ -1369,7 +1370,7 @@ private static List createNestedClassConstructorMethods( t -> TypeNode.withReference( VaporReference.builder() - .setName(t.reference().enclosingClassName()) + .setName(String.join(DOT, t.reference().enclosingClassNames())) .setPakkage(t.reference().pakkage()) .build()); List ctorBodyStatements = new ArrayList<>(); @@ -1845,7 +1846,7 @@ private static Map createDynamicTypes(Service service, String VaporReference.builder() .setName(NESTED_BUILDER_CLASS_NAME) .setPakkage(pakkage) - .setEnclosingClassName(thisClassName) + .setEnclosingClassNames(thisClassName) .setIsStaticImport(true) .build())); @@ -1874,7 +1875,7 @@ private static Map createDynamicTypes(Service service, String VaporReference.builder() .setName(getPagedResponseTypeName(m.name())) .setPakkage(service.pakkage()) - .setEnclosingClassName(String.format("%sClient", service.name())) + .setEnclosingClassNames(String.format("%sClient", service.name())) .setIsStaticImport(true) .build())))); diff --git a/src/main/java/com/google/api/generator/gapic/model/Message.java b/src/main/java/com/google/api/generator/gapic/model/Message.java index b9a613d000..14c9b9cf12 100644 --- a/src/main/java/com/google/api/generator/gapic/model/Message.java +++ b/src/main/java/com/google/api/generator/gapic/model/Message.java @@ -19,6 +19,7 @@ import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -41,6 +42,11 @@ public abstract class Message { @Nullable public abstract ResourceName resource(); + // The nested types in left-to-right order, if any. + // Example: com.google.Foo.Bar.Car.ThisType will have the outer types listed in the order + // [Foo, Bar, Car]. + public abstract ImmutableList outerNestedTypes(); + public abstract Builder toBuilder(); public boolean hasResource() { @@ -60,7 +66,7 @@ public Field findAndUnwrapFirstRepeatedField() { } public static Builder builder() { - return new AutoValue_Message.Builder(); + return new AutoValue_Message.Builder().setOuterNestedTypes(Collections.emptyList()); } @AutoValue.Builder @@ -73,6 +79,8 @@ public abstract static class Builder { public abstract Builder setResource(ResourceName resource); + public abstract Builder setOuterNestedTypes(List outerNestedTypes); + abstract Builder setFieldMap(Map fieldMap); abstract ImmutableList fields(); diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java index 3f56eac203..53578d3d0e 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java @@ -215,22 +215,40 @@ public static Map parseMessages(CodeGeneratorRequest request) { } public static Map parseMessages(FileDescriptor fileDescriptor) { - String pakkage = TypeParser.getPackage(fileDescriptor); - return fileDescriptor.getMessageTypes().stream() - .collect( - Collectors.toMap( - md -> md.getName(), - md -> - Message.builder() - .setType( - TypeNode.withReference( - VaporReference.builder() - .setName(md.getName()) - .setPakkage(pakkage) - .build())) - .setName(md.getName()) - .setFields(parseFields(md)) - .build())); + // TODO(miraleung): Preserve nested type and package data in the type key. + Map messages = new HashMap<>(); + for (Descriptor messageDescriptor : fileDescriptor.getMessageTypes()) { + messages.putAll(parseMessages(messageDescriptor)); + } + return messages; + } + + private static Map parseMessages(Descriptor messageDescriptor) { + return parseMessages(messageDescriptor, new ArrayList()); + } + + private static Map parseMessages( + Descriptor messageDescriptor, List outerNestedTypes) { + Map messages = new HashMap<>(); + String messageName = messageDescriptor.getName(); + if (!messageDescriptor.getNestedTypes().isEmpty()) { + for (Descriptor nestedMessage : messageDescriptor.getNestedTypes()) { + outerNestedTypes.add(messageName); + messages.putAll(parseMessages(nestedMessage, outerNestedTypes)); + } + } + String pakkage = TypeParser.getPackage(messageDescriptor.getFile()); + messages.put( + messageName, + Message.builder() + .setType( + TypeNode.withReference( + VaporReference.builder().setName(messageName).setPakkage(pakkage).build())) + .setName(messageName) + .setFields(parseFields(messageDescriptor)) + .setOuterNestedTypes(outerNestedTypes) + .build()); + return messages; } /** diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/TypeParser.java b/src/main/java/com/google/api/generator/gapic/protoparser/TypeParser.java index ae8439a647..a5f45faad9 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/TypeParser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/TypeParser.java @@ -28,6 +28,7 @@ import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; import com.google.protobuf.Descriptors.FileDescriptor; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -115,16 +116,21 @@ static Reference parseFieldReference(FieldDescriptor field) { @VisibleForTesting static Reference parseMessageReference(@Nonnull Descriptor messageDescriptor) { // TODO(miraleung): Handle deeper levels of nesting. - String pakkage = getPackage(messageDescriptor.getFile()); - VaporReference.Builder messageReferenceBuilder = - VaporReference.builder().setName(messageDescriptor.getName()).setPakkage(pakkage); - - boolean isNestedType = messageDescriptor.getContainingType() != null; - if (isNestedType) { - String enclosingClassName = messageDescriptor.getContainingType().getName(); - messageReferenceBuilder.setEnclosingClassName(enclosingClassName); + List outerNestedTypeNames = new ArrayList<>(); + Descriptor containingType = messageDescriptor.getContainingType(); + while (containingType != null) { + // Outermost type in the nested type hierarchy lies at index 0. + outerNestedTypeNames.add(0, containingType.getName()); + containingType = containingType.getContainingType(); } - Reference messageReference = messageReferenceBuilder.build(); + + String pakkage = getPackage(messageDescriptor.getFile()); + Reference messageReference = + VaporReference.builder() + .setName(messageDescriptor.getName()) + .setPakkage(pakkage) + .setEnclosingClassNames(outerNestedTypeNames) + .build(); String protoPackage = messageDescriptor.getFile().getPackage(); Preconditions.checkState( messageReference @@ -142,17 +148,22 @@ static Reference parseMessageReference(@Nonnull Descriptor messageDescriptor) { static Reference parseEnumReference(@Nonnull EnumDescriptor enumDescriptor) { // This is similar to parseMessageReference, but we make it a separate method because // EnumDescriptor and Descriptor are sibling types. + List outerNestedTypeNames = new ArrayList<>(); + Descriptor containingType = enumDescriptor.getContainingType(); + while (containingType != null) { + // Outermost type in the nested type hierarchy lies at index 0. + outerNestedTypeNames.add(0, containingType.getName()); + containingType = containingType.getContainingType(); + } + // TODO(miraleung): Handle deeper levels of nesting. String pakkage = getPackage(enumDescriptor.getFile()); - VaporReference.Builder enumReferenceBuilder = - VaporReference.builder().setName(enumDescriptor.getName()).setPakkage(pakkage); - - boolean isNestedType = enumDescriptor.getContainingType() != null; - if (isNestedType) { - String enclosingClassName = enumDescriptor.getContainingType().getName(); - enumReferenceBuilder.setEnclosingClassName(enclosingClassName); - } - Reference enumReference = enumReferenceBuilder.build(); + Reference enumReference = + VaporReference.builder() + .setName(enumDescriptor.getName()) + .setPakkage(pakkage) + .setEnclosingClassNames(outerNestedTypeNames) + .build(); String protoPackage = enumDescriptor.getFile().getPackage(); Preconditions.checkState( enumReference diff --git a/src/test/java/com/google/api/generator/engine/ast/VaporReferenceTest.java b/src/test/java/com/google/api/generator/engine/ast/VaporReferenceTest.java index 59a09a3a25..042e4b4582 100644 --- a/src/test/java/com/google/api/generator/engine/ast/VaporReferenceTest.java +++ b/src/test/java/com/google/api/generator/engine/ast/VaporReferenceTest.java @@ -55,12 +55,14 @@ public void basic_nested() { String enclosingClassName = "Babbage"; Reference ref = VaporReference.builder() - .setEnclosingClassName(enclosingClassName) + .setEnclosingClassNames("Babbage", "Ada") .setName(name) .setPakkage(pkg) .build(); - assertEquals(ref.name(), String.format("%s.%s", enclosingClassName, name)); - assertEquals(ref.fullName(), String.format("%s.%s.%s", pkg, enclosingClassName, name)); + + assertEquals(ref.name(), "Babbage.Ada.Charles"); + assertTrue(ref.hasEnclosingClass()); + assertEquals(ref.fullName(), String.format("%s.%s.%s.%s", pkg, "Babbage", "Ada", name)); assertTrue(ref.hasEnclosingClass()); assertTrue(ref.isFromPackage(pkg)); assertFalse(ref.isFromPackage("com.google.example.library")); @@ -74,7 +76,7 @@ public void basic_nestedAndStaticImport() { String enclosingClassName = "Babbage"; Reference ref = VaporReference.builder() - .setEnclosingClassName(enclosingClassName) + .setEnclosingClassNames(enclosingClassName) .setName(name) .setPakkage(pkg) .setIsStaticImport(true) @@ -109,7 +111,7 @@ public void enclosingClass() { VaporReference.builder() .setName(name) .setPakkage(pkg) - .setEnclosingClassName(enclosingName) + .setEnclosingClassNames(enclosingName) .build(); assertTrue(ref.hasEnclosingClass()); assertEquals(ref.fullName(), String.format("%s.%s.%s", pkg, enclosingName, name)); diff --git a/src/test/java/com/google/api/generator/gapic/protoparser/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/protoparser/BUILD.bazel index b4af740184..7df82d359f 100644 --- a/src/test/java/com/google/api/generator/gapic/protoparser/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/protoparser/BUILD.bazel @@ -13,6 +13,7 @@ TESTS = [ "ServiceConfigParserTest", "ServiceYamlParserTest", "SourceCodeInfoParserTest", + "TypeParserTest", ] filegroup( diff --git a/src/test/java/com/google/api/generator/gapic/protoparser/TypeParserTest.java b/src/test/java/com/google/api/generator/gapic/protoparser/TypeParserTest.java new file mode 100644 index 0000000000..37ace31584 --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/protoparser/TypeParserTest.java @@ -0,0 +1,55 @@ +// 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.protoparser; + +import static junit.framework.Assert.assertEquals; + +import com.google.api.generator.engine.ast.Reference; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import com.google.protobuf.Descriptors.MethodDescriptor; +import com.google.protobuf.Descriptors.ServiceDescriptor; +import com.google.showcase.v1beta1.EchoOuterClass; +import com.google.testgapic.v1beta1.NestedMessageProto; +import org.junit.Test; + +public class TypeParserTest { + private static final String ECHO_PACKAGE = "com.google.showcase.v1beta1"; + // TODO(miraleung): Backfill with more tests (e.g. field, message, methods) for Parser.java. + @Test + public void parseMessageType_basic() { + FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor(); + ServiceDescriptor echoService = echoFileDescriptor.getServices().get(0); + assertEquals(echoService.getName(), "Echo"); + + MethodDescriptor echoMethodDescriptor = echoService.getMethods().get(0); + Reference reference = TypeParser.parseMessageReference(echoMethodDescriptor.getInputType()); + assertEquals("com.google.showcase.v1beta1.EchoRequest", reference.fullName()); + } + + @Test + public void parseMessageType_nested() { + FileDescriptor fileDescriptor = NestedMessageProto.getDescriptor(); + Descriptor messageDescriptor = fileDescriptor.getMessageTypes().get(0); + assertEquals("Outer", messageDescriptor.getName()); + messageDescriptor = messageDescriptor.getNestedTypes().get(0); + assertEquals("Middle", messageDescriptor.getName()); + messageDescriptor = messageDescriptor.getNestedTypes().get(0); + assertEquals("Inner", messageDescriptor.getName()); + + Reference reference = TypeParser.parseMessageReference(messageDescriptor); + assertEquals("com.google.testgapic.v1beta1.Outer.Middle.Inner", reference.fullName()); + } +} diff --git a/src/test/java/com/google/api/generator/gapic/testdata/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/testdata/BUILD.bazel index 9b425d8013..4909db60e6 100644 --- a/src/test/java/com/google/api/generator/gapic/testdata/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/testdata/BUILD.bazel @@ -60,6 +60,7 @@ proto_library( srcs = [ "bad_message_resname_def.proto", "locker.proto", + "nested_message.proto", ], deps = [ "@com_google_googleapis//google/api:annotations_proto", diff --git a/src/test/java/com/google/api/generator/gapic/testdata/nested_message.proto b/src/test/java/com/google/api/generator/gapic/testdata/nested_message.proto new file mode 100644 index 0000000000..1b2bae113e --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/testdata/nested_message.proto @@ -0,0 +1,36 @@ +// Copyright 2018 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. + +syntax = "proto3"; + +package google.testgapic; + +option java_package = "com.google.testgapic.v1beta1"; +option java_multiple_files = true; +option java_outer_classname = "NestedMessageProto"; + +message Outer { + string name = 1; + + Middle middle = 2; + + Middle.Inner innermost = 3; + + message Middle { + int32 x = 4; + message Inner { + int32 y = 5; + } + } +} From 3e26d879b83918fc7e67ee14974b3dc2a7c6cc74 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Wed, 28 Oct 2020 12:41:39 -0700 Subject: [PATCH 05/26] fix: prevent resname tokens from matching subcomponents --- .../gapic/composer/ResourceNameTokenizer.java | 35 +++++++++++++++---- .../composer/ResourceNameTokenizerTest.java | 10 ++++++ 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameTokenizer.java b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameTokenizer.java index 671b5b6bcf..67d295d1a5 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameTokenizer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameTokenizer.java @@ -15,6 +15,7 @@ package com.google.api.generator.gapic.composer; import com.google.api.pathtemplate.PathTemplate; +import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -22,9 +23,13 @@ import java.util.stream.Collectors; public class ResourceNameTokenizer { - private static final String SLASH = "/"; private static final String LEFT_BRACE = "{"; private static final String RIGHT_BRACE = "}"; + private static final String SLASH = "/"; + private static final String EMPTY = ""; + + private static final String EQUALS_WILDCARD = "=*"; + private static final String EQUALS_PATH_WILDCARD = "=**"; static List> parseTokenHierarchy(List patterns) { List nonSlashSepStrings = Arrays.asList("}_{", "}-{", "}.{", "}~{"); @@ -36,7 +41,9 @@ static List> parseTokenHierarchy(List patterns) { String[] patternTokens = pattern.split(SLASH); for (String patternToken : patternTokens) { if (patternToken.startsWith(LEFT_BRACE) && patternToken.endsWith(RIGHT_BRACE)) { - String processedPatternToken = patternToken; + String processedPatternToken = + // Replacement order matters - ensure the first is not a subcomponent of the second. + patternToken.replace(EQUALS_PATH_WILDCARD, EMPTY).replace(EQUALS_WILDCARD, EMPTY); // Handle non-slash separators. if (nonSlashSepStrings.stream().anyMatch(s -> patternToken.contains(s))) { @@ -44,14 +51,28 @@ static List> parseTokenHierarchy(List patterns) { processedPatternToken = processedPatternToken.replace(str, "_"); } } else { + final int processedPatternTokenLength = processedPatternToken.length(); // Handles wildcards. - processedPatternToken = + List candidateVars = vars.stream() - .filter(v -> patternToken.contains(v)) - .collect(Collectors.toList()) - .get(0); + // Check that the token size is within ~3 of the var, to avoid mismatching on + // variables with same-named subcomponents. + // Otherwise, "customer_client_link" will match with "customer". + .filter( + v -> + patternToken.contains(v) + // Accounting for braces. + && processedPatternTokenLength - v.length() < 3) + .collect(Collectors.toList()); + Preconditions.checkState( + !candidateVars.isEmpty(), + String.format( + "No variable candidates found for token %s in pattern %s", + processedPatternToken, pattern)); + processedPatternToken = candidateVars.get(0); } - hierarchy.add(processedPatternToken.replace("{", "").replace("}", "")); + hierarchy.add( + processedPatternToken.replace(LEFT_BRACE, EMPTY).replace(RIGHT_BRACE, EMPTY)); } } tokenHierachies.add(hierarchy); diff --git a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameTokenizerTest.java b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameTokenizerTest.java index aed8624d92..3c61e206ba 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/ResourceNameTokenizerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/ResourceNameTokenizerTest.java @@ -51,6 +51,16 @@ public void parseTokenHierarchy_basic() { assertThat(tokenHierarchies.get(2)).containsExactly("project", "autoscaling_policy"); } + @Test + public void parseTokenHierarchy_substringsInPattern() { + List patterns = + Arrays.asList( + "customers/{customer}/customerExtensionSettings/{customer_extension_setting}"); + List> tokenHierarchies = ResourceNameTokenizer.parseTokenHierarchy(patterns); + assertEquals(1, tokenHierarchies.size()); + assertThat(tokenHierarchies.get(0)).containsExactly("customer", "customer_extension_setting"); + } + @Test public void parseTokenHierarchy_wildcards() { List patterns = From 837da38f959407f179c057744346d47f839bff7c Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Wed, 28 Oct 2020 13:49:04 -0700 Subject: [PATCH 06/26] fix: use TypeParser for proto message parsing --- .../com/google/api/generator/gapic/protoparser/Parser.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java index 53578d3d0e..4e61c0df2a 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java @@ -18,7 +18,6 @@ import com.google.api.ResourceDescriptor; import com.google.api.ResourceProto; import com.google.api.generator.engine.ast.TypeNode; -import com.google.api.generator.engine.ast.VaporReference; import com.google.api.generator.gapic.model.Field; import com.google.api.generator.gapic.model.GapicBatchingSettings; import com.google.api.generator.gapic.model.GapicContext; @@ -241,9 +240,7 @@ private static Map parseMessages( messages.put( messageName, Message.builder() - .setType( - TypeNode.withReference( - VaporReference.builder().setName(messageName).setPakkage(pakkage).build())) + .setType(TypeParser.parseType(messageDescriptor)) .setName(messageName) .setFields(parseFields(messageDescriptor)) .setOuterNestedTypes(outerNestedTypes) From a5fc33257deae52563054ddab006f0d62e1ef754 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Wed, 28 Oct 2020 16:39:18 -0700 Subject: [PATCH 07/26] fix: use generic types in field instantiation in ServiceClientTest --- .../gapic/composer/DefaultValueComposer.java | 16 +++++-- .../composer/DefaultValueComposerTest.java | 4 +- .../goldens/SubscriberClientTest.golden | 48 ++++++++++--------- 3 files changed, 39 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/DefaultValueComposer.java b/src/main/java/com/google/api/generator/gapic/composer/DefaultValueComposer.java index 1268cb7750..db69075920 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/DefaultValueComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/DefaultValueComposer.java @@ -77,10 +77,18 @@ static Expr createDefaultValue( } static Expr createDefaultValue(Field f) { + return createDefaultValue(f, false); + } + + static Expr createDefaultValue(Field f, boolean useExplicitInitTypeInGenerics) { if (f.isRepeated()) { - TypeNode newType = - TypeNode.withReference( - ConcreteReference.withClazz(f.isMap() ? HashMap.class : ArrayList.class)); + ConcreteReference.Builder refBuilder = + ConcreteReference.builder().setClazz(f.isMap() ? HashMap.class : ArrayList.class); + if (useExplicitInitTypeInGenerics) { + refBuilder = refBuilder.setGenerics(f.type().reference().generics().get(0)); + } + + TypeNode newType = TypeNode.withReference(refBuilder.build()); return NewObjectExpr.builder().setType(newType).setIsGeneric(true).build(); } @@ -238,7 +246,7 @@ static Expr createSimpleMessageBuilderExpr( .setReturnType(TypeNode.STRING) .build(); } else { - defaultExpr = createDefaultValue(field); + defaultExpr = createDefaultValue(field, true); } builderExpr = MethodInvocationExpr.builder() diff --git a/src/test/java/com/google/api/generator/gapic/composer/DefaultValueComposerTest.java b/src/test/java/com/google/api/generator/gapic/composer/DefaultValueComposerTest.java index 43f2507dad..0c397692b1 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/DefaultValueComposerTest.java +++ b/src/test/java/com/google/api/generator/gapic/composer/DefaultValueComposerTest.java @@ -273,8 +273,8 @@ public void createSimpleMessage_containsRepeatedField() { message, typeStringsToResourceNames, messageTypes); expr.accept(writerVisitor); assertEquals( - "PagedExpandResponse.newBuilder().addAllResponses(new" - + " ArrayList<>()).setNextPageToken(\"next_page_token-1530815211\").build()", + "PagedExpandResponse.newBuilder().addAllResponses(new ArrayList())" + + ".setNextPageToken(\"next_page_token-1530815211\").build()", writerVisitor.write()); } diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/SubscriberClientTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/SubscriberClientTest.golden index 8a03a3ca8e..150a8926e5 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/SubscriberClientTest.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/SubscriberClientTest.golden @@ -81,7 +81,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -140,7 +140,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -199,7 +199,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -258,7 +258,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -317,7 +317,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -366,7 +366,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -415,7 +415,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -781,7 +781,7 @@ public class SubscriberClientTest { @Test public void pullTest() throws Exception { PullResponse expectedResponse = - PullResponse.newBuilder().addAllReceivedMessages(new ArrayList<>()).build(); + PullResponse.newBuilder().addAllReceivedMessages(new ArrayList()).build(); mockSubscriber.addResponse(expectedResponse); SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); @@ -823,7 +823,7 @@ public class SubscriberClientTest { @Test public void pullTest2() throws Exception { PullResponse expectedResponse = - PullResponse.newBuilder().addAllReceivedMessages(new ArrayList<>()).build(); + PullResponse.newBuilder().addAllReceivedMessages(new ArrayList()).build(); mockSubscriber.addResponse(expectedResponse); String subscription = "subscription341203229"; @@ -865,14 +865,16 @@ public class SubscriberClientTest { @Test public void streamingPullTest() throws Exception { StreamingPullResponse expectedResponse = - StreamingPullResponse.newBuilder().addAllReceivedMessages(new ArrayList<>()).build(); + StreamingPullResponse.newBuilder() + .addAllReceivedMessages(new ArrayList()) + .build(); mockSubscriber.addResponse(expectedResponse); StreamingPullRequest request = StreamingPullRequest.newBuilder() .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) - .addAllAckIds(new ArrayList<>()) - .addAllModifyDeadlineSeconds(new ArrayList<>()) - .addAllModifyDeadlineAckIds(new ArrayList<>()) + .addAllAckIds(new ArrayList()) + .addAllModifyDeadlineSeconds(new ArrayList()) + .addAllModifyDeadlineAckIds(new ArrayList()) .setStreamAckDeadlineSeconds(1875467245) .setClientId("client_id-1904089585") .setMaxOutstandingMessages(-1315266996) @@ -901,9 +903,9 @@ public class SubscriberClientTest { StreamingPullRequest request = StreamingPullRequest.newBuilder() .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) - .addAllAckIds(new ArrayList<>()) - .addAllModifyDeadlineSeconds(new ArrayList<>()) - .addAllModifyDeadlineAckIds(new ArrayList<>()) + .addAllAckIds(new ArrayList()) + .addAllModifyDeadlineSeconds(new ArrayList()) + .addAllModifyDeadlineAckIds(new ArrayList()) .setStreamAckDeadlineSeconds(1875467245) .setClientId("client_id-1904089585") .setMaxOutstandingMessages(-1315266996) @@ -1011,7 +1013,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1051,7 +1053,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1179,7 +1181,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1222,7 +1224,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1265,7 +1267,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1308,7 +1310,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1351,7 +1353,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); From b71b786bb68f4b367137c99d37e05794a9ae7b3a Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 13:50:49 -0700 Subject: [PATCH 08/26] fix: prevent descension into map types in nested message parsing --- .../api/generator/gapic/protoparser/Parser.java | 15 +++++++++++++++ .../gapic/protoparser/SourceCodeInfoParser.java | 3 ++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java index 4e61c0df2a..c16246a70e 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java @@ -232,11 +232,16 @@ private static Map parseMessages( String messageName = messageDescriptor.getName(); if (!messageDescriptor.getNestedTypes().isEmpty()) { for (Descriptor nestedMessage : messageDescriptor.getNestedTypes()) { + if (isMapType(nestedMessage)) { + continue; + } outerNestedTypes.add(messageName); messages.putAll(parseMessages(nestedMessage, outerNestedTypes)); } } String pakkage = TypeParser.getPackage(messageDescriptor.getFile()); + List fieldNames = + messageDescriptor.getFields().stream().map(f -> f.getName()).collect(Collectors.toList()); messages.put( messageName, Message.builder() @@ -248,6 +253,16 @@ private static Map parseMessages( return messages; } + private static boolean isMapType(Descriptor messageDescriptor) { + List fieldNames = + messageDescriptor.getFields().stream().map(f -> f.getName()).collect(Collectors.toList()); + // Ends in "Entry" and has exactly two fields, named "key" and "value". + return messageDescriptor.getName().endsWith("Entry") + && fieldNames.size() == 2 + && fieldNames.get(0).equals("key") + && fieldNames.get(1).equals("value"); + } + /** * Populates ResourceName objects in Message POJOs. * diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/SourceCodeInfoParser.java b/src/main/java/com/google/api/generator/gapic/protoparser/SourceCodeInfoParser.java index bfa4c62297..28ae95c926 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/SourceCodeInfoParser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/SourceCodeInfoParser.java @@ -76,7 +76,8 @@ public SourceCodeInfoLocation getLocation(FieldDescriptor field) { if (!file.toProto().hasSourceCodeInfo()) { return null; } - return SourceCodeInfoLocation.create(getLocation(file, buildPath(field))); + Location fieldLocation = getLocation(file, buildPath(field)); + return SourceCodeInfoLocation.create(fieldLocation); } /** Gets the location of a service, if available. */ From 602e1df70be04ab5474c96dda9d1abafb94e13e1 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 16:11:55 -0700 Subject: [PATCH 09/26] fix: merge master --- test/integration/BUILD.bazel | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/test/integration/BUILD.bazel b/test/integration/BUILD.bazel index f778566ed1..48f6c2ddbb 100644 --- a/test/integration/BUILD.bazel +++ b/test/integration/BUILD.bazel @@ -1,12 +1,13 @@ load( "@com_google_googleapis_imports//:imports.bzl", "proto_library_with_info", + java_gapic_assembly_gradle_pkg = "java_gapic_assembly_gradle_pkg2", java_gapic_library = "java_gapic_library2", ) load( "//:rules_bazel/java/integration_test.bzl", - "integration_test", "golden_update", + "integration_test", ) package(default_visibility = ["//visibility:public"]) @@ -23,20 +24,20 @@ integration_test( integration_test( name = "asset", - target = ":asset_java_gapic", data = ["//test/integration/goldens/asset:goldens_files"], + target = ":asset_java_gapic", ) golden_update( name = "redis_update", - target = ":redis_java_gapic", data = ["//test/integration/goldens/redis:goldens_files"], + target = ":redis_java_gapic", ) golden_update( name = "asset_update", - target = ":asset_java_gapic", data = ["//test/integration/goldens/asset:goldens_files"], + target = ":asset_java_gapic", ) #################################################### @@ -86,6 +87,17 @@ java_gapic_library( ], ) +java_gapic_assembly_gradle_pkg( + name = "google-cloud-redis-v1-java", + deps = [ + ":redis_java_gapic", + "@com_google_googleapis//google/cloud/redis/v1:redis_java_grpc", + "@com_google_googleapis//google/cloud/redis/v1:redis_java_proto", + "@com_google_googleapis//google/cloud/redis/v1:redis_proto", + ], +) + +# Logging API java_gapic_library( name = "logging_java_gapic", srcs = ["@com_google_googleapis//google/logging/v2:logging_proto_with_info"], @@ -101,3 +113,12 @@ java_gapic_library( ], ) +java_gapic_assembly_gradle_pkg( + name = "google-cloud-logging-v2-java", + deps = [ + ":logging_java_gapic", + "@com_google_googleapis//google/logging/v2:logging_java_grpc", + "@com_google_googleapis//google/logging/v2:logging_java_proto", + "@com_google_googleapis//google/logging/v2:logging_proto", + ], +) From 07dddb82ee6c65fd243aed3504de59d5fd4448d9 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 14:24:19 -0700 Subject: [PATCH 10/26] fix: use both map generics in ServiceClientTest codegen --- .../gapic/composer/DefaultValueComposer.java | 6 +++- .../goldens/SubscriberClientTest.golden | 28 +++++++++---------- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/DefaultValueComposer.java b/src/main/java/com/google/api/generator/gapic/composer/DefaultValueComposer.java index db69075920..98143f5574 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/DefaultValueComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/DefaultValueComposer.java @@ -85,7 +85,11 @@ static Expr createDefaultValue(Field f, boolean useExplicitInitTypeInGenerics) { ConcreteReference.Builder refBuilder = ConcreteReference.builder().setClazz(f.isMap() ? HashMap.class : ArrayList.class); if (useExplicitInitTypeInGenerics) { - refBuilder = refBuilder.setGenerics(f.type().reference().generics().get(0)); + if (f.isMap()) { + refBuilder = refBuilder.setGenerics(f.type().reference().generics().subList(0, 2)); + } else { + refBuilder = refBuilder.setGenerics(f.type().reference().generics().get(0)); + } } TypeNode newType = TypeNode.withReference(refBuilder.build()); diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/SubscriberClientTest.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/SubscriberClientTest.golden index 150a8926e5..0e03fd0e11 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/SubscriberClientTest.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/SubscriberClientTest.golden @@ -81,7 +81,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -140,7 +140,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -199,7 +199,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -258,7 +258,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -317,7 +317,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -366,7 +366,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -415,7 +415,7 @@ public class SubscriberClientTest { .setPushConfig(PushConfig.newBuilder().build()) .setAckDeadlineSeconds(2135351438) .setRetainAckedMessages(true) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .setEnableMessageOrdering(true) .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) .setFilter("filter-1274492040") @@ -1013,7 +1013,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1053,7 +1053,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1181,7 +1181,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1224,7 +1224,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1267,7 +1267,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1310,7 +1310,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); @@ -1353,7 +1353,7 @@ public class SubscriberClientTest { Snapshot.newBuilder() .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) - .putAllLabels(new HashMap()) + .putAllLabels(new HashMap()) .build(); mockSubscriber.addResponse(expectedResponse); From 5e95e8f0f46e97cee064cf9216a7db212709f0a2 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 15:14:15 -0700 Subject: [PATCH 11/26] fix: dir structure of generated files --- rules_java_gapic/java_gapic.bzl | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/rules_java_gapic/java_gapic.bzl b/rules_java_gapic/java_gapic.bzl index 5420724de8..2bbcd1f0b4 100644 --- a/rules_java_gapic/java_gapic.bzl +++ b/rules_java_gapic/java_gapic.bzl @@ -31,9 +31,14 @@ def _java_gapic_postprocess_srcjar_impl(ctx): unzip -q temp-codegen.srcjar -d {output_dir_path} # This may fail if there are spaces and/or too many files (exceed max length of command length). {formatter} --replace $(find {output_dir_path} -type f -printf "%p ") - zip -r -j {output_srcjar_name}.srcjar {output_dir_path}/src/main/* - zip -r -j {output_srcjar_name}-resource-name.srcjar {output_dir_path}/proto/src/main/* - zip -r -j {output_srcjar_name}-tests.srcjar {output_dir_path}/src/test/* + WORKING_DIR=`pwd` + cd {output_dir_path}/src/main/java + zip -r $WORKING_DIR/{output_srcjar_name}.srcjar ./ + cd $WORKING_DIR/{output_dir_path}/proto/src/main/java + zip -r $WORKING_DIR/{output_srcjar_name}-resource-name.srcjar ./ + cd $WORKING_DIR/{output_dir_path}/proto/src/test/java + zip -r $WORKING_DIR/{output_srcjar_name}-tests.srcjar ./ + cd $WORKING_DIR mv {output_srcjar_name}.srcjar {output_main} mv {output_srcjar_name}-resource-name.srcjar {output_resource_name} mv {output_srcjar_name}-tests.srcjar {output_test} From c37c2d0897584caf0cfc616cd9ccb33d3bd1c827 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 15:52:03 -0700 Subject: [PATCH 12/26] test: add asset API gradle pkg rules --- test/integration/BUILD.bazel | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/test/integration/BUILD.bazel b/test/integration/BUILD.bazel index 48f6c2ddbb..9318b7637c 100644 --- a/test/integration/BUILD.bazel +++ b/test/integration/BUILD.bazel @@ -45,6 +45,7 @@ golden_update( #################################################### # These will eventually go away once more APIs in googleapis have been migrated to the microgenerator. +# Asset API. java_gapic_library( name = "asset_java_gapic", srcs = ["@com_google_googleapis//google/cloud/asset/v1:asset_proto_with_info"], @@ -56,8 +57,22 @@ java_gapic_library( "@com_google_googleapis//google/iam/v1:iam_java_grpc", ], deps = [ - "@com_google_googleapis//google/cloud/asset/v1:asset_java_proto", "@com_google_googleapis//google/iam/v1:iam_java_proto", + "@com_google_googleapis//google/identity/accesscontextmanager/v1:accesscontextmanager_proto", + ], +) + +java_gapic_assembly_gradle_pkg( + name = "google-cloud-asset-v1-java", + deps = [ + ":asset_java_gapic", + "@com_google_googleapis//google/cloud/orgpolicy/v1:orgpolicy_java_proto", + "@com_google_googleapis//google/cloud/asset/v1:asset_java_grpc", + "@com_google_googleapis//google/identity/accesscontextmanager/type:type_java_proto", + "@com_google_googleapis//google/identity/accesscontextmanager/v1:accesscontextmanager_java_proto", + "@com_google_googleapis//google/cloud/asset/v1:asset_java_proto", + "@com_google_googleapis//google/cloud/asset/v1:asset_proto", + #"@com_google_googleapis//google/iam/v1:iam_java_proto", ], ) From 8a7196fa93cccf333e02fdb701698ccd0e6a190f Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 16:40:00 -0700 Subject: [PATCH 13/26] fix: remove unused dep --- test/integration/BUILD.bazel | 1 - 1 file changed, 1 deletion(-) diff --git a/test/integration/BUILD.bazel b/test/integration/BUILD.bazel index 9318b7637c..1540d23005 100644 --- a/test/integration/BUILD.bazel +++ b/test/integration/BUILD.bazel @@ -72,7 +72,6 @@ java_gapic_assembly_gradle_pkg( "@com_google_googleapis//google/identity/accesscontextmanager/v1:accesscontextmanager_java_proto", "@com_google_googleapis//google/cloud/asset/v1:asset_java_proto", "@com_google_googleapis//google/cloud/asset/v1:asset_proto", - #"@com_google_googleapis//google/iam/v1:iam_java_proto", ], ) From f7f80990a476aa1ef8761fba3f08dfdf69342228 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 16:47:04 -0700 Subject: [PATCH 14/26] test: add logging integration target and goldens, consolidate rules --- test/integration/BUILD.bazel | 43 +- test/integration/goldens/logging/BUILD.bazel | 6 + .../logging/BillingAccountLocationName.java | 188 ++ .../goldens/logging/BillingAccountName.java | 163 ++ .../goldens/logging/CmekSettingsName.java | 375 ++++ .../logging/ConfigServiceV2Client.java | 1707 +++++++++++++++++ .../logging/ConfigServiceV2Settings.java | 327 ++++ .../goldens/logging/ConfigServiceV2Stub.java | 134 ++ .../logging/ConfigServiceV2StubSettings.java | 806 ++++++++ .../goldens/logging/FolderLocationName.java | 186 ++ .../goldens/logging/FolderName.java | 163 ++ .../GrpcConfigServiceV2CallableFactory.java | 113 ++ .../logging/GrpcConfigServiceV2Stub.java | 627 ++++++ .../GrpcLoggingServiceV2CallableFactory.java | 113 ++ .../logging/GrpcLoggingServiceV2Stub.java | 310 +++ .../GrpcMetricsServiceV2CallableFactory.java | 113 ++ .../logging/GrpcMetricsServiceV2Stub.java | 293 +++ .../goldens/logging/LocationName.java | 186 ++ .../goldens/logging/LogBucketName.java | 540 ++++++ .../goldens/logging/LogExclusionName.java | 449 +++++ .../goldens/logging/LogMetricName.java | 185 ++ test/integration/goldens/logging/LogName.java | 435 +++++ .../goldens/logging/LogSinkName.java | 439 +++++ .../logging/LoggingServiceV2Client.java | 888 +++++++++ .../logging/LoggingServiceV2Settings.java | 231 +++ .../goldens/logging/LoggingServiceV2Stub.java | 87 + .../logging/LoggingServiceV2StubSettings.java | 598 ++++++ .../logging/MetricsServiceV2Client.java | 545 ++++++ .../logging/MetricsServiceV2Settings.java | 216 +++ .../goldens/logging/MetricsServiceV2Stub.java | 69 + .../logging/MetricsServiceV2StubSettings.java | 442 +++++ .../logging/OrganizationLocationName.java | 186 ++ .../goldens/logging/OrganizationName.java | 163 ++ .../goldens/logging/ProjectName.java | 163 ++ .../goldens/logging/package-info.java | 43 + 35 files changed, 11507 insertions(+), 25 deletions(-) create mode 100644 test/integration/goldens/logging/BUILD.bazel create mode 100644 test/integration/goldens/logging/BillingAccountLocationName.java create mode 100644 test/integration/goldens/logging/BillingAccountName.java create mode 100644 test/integration/goldens/logging/CmekSettingsName.java create mode 100644 test/integration/goldens/logging/ConfigServiceV2Client.java create mode 100644 test/integration/goldens/logging/ConfigServiceV2Settings.java create mode 100644 test/integration/goldens/logging/ConfigServiceV2Stub.java create mode 100644 test/integration/goldens/logging/ConfigServiceV2StubSettings.java create mode 100644 test/integration/goldens/logging/FolderLocationName.java create mode 100644 test/integration/goldens/logging/FolderName.java create mode 100644 test/integration/goldens/logging/GrpcConfigServiceV2CallableFactory.java create mode 100644 test/integration/goldens/logging/GrpcConfigServiceV2Stub.java create mode 100644 test/integration/goldens/logging/GrpcLoggingServiceV2CallableFactory.java create mode 100644 test/integration/goldens/logging/GrpcLoggingServiceV2Stub.java create mode 100644 test/integration/goldens/logging/GrpcMetricsServiceV2CallableFactory.java create mode 100644 test/integration/goldens/logging/GrpcMetricsServiceV2Stub.java create mode 100644 test/integration/goldens/logging/LocationName.java create mode 100644 test/integration/goldens/logging/LogBucketName.java create mode 100644 test/integration/goldens/logging/LogExclusionName.java create mode 100644 test/integration/goldens/logging/LogMetricName.java create mode 100644 test/integration/goldens/logging/LogName.java create mode 100644 test/integration/goldens/logging/LogSinkName.java create mode 100644 test/integration/goldens/logging/LoggingServiceV2Client.java create mode 100644 test/integration/goldens/logging/LoggingServiceV2Settings.java create mode 100644 test/integration/goldens/logging/LoggingServiceV2Stub.java create mode 100644 test/integration/goldens/logging/LoggingServiceV2StubSettings.java create mode 100644 test/integration/goldens/logging/MetricsServiceV2Client.java create mode 100644 test/integration/goldens/logging/MetricsServiceV2Settings.java create mode 100644 test/integration/goldens/logging/MetricsServiceV2Stub.java create mode 100644 test/integration/goldens/logging/MetricsServiceV2StubSettings.java create mode 100644 test/integration/goldens/logging/OrganizationLocationName.java create mode 100644 test/integration/goldens/logging/OrganizationName.java create mode 100644 test/integration/goldens/logging/ProjectName.java create mode 100644 test/integration/goldens/logging/package-info.java diff --git a/test/integration/BUILD.bazel b/test/integration/BUILD.bazel index 9318b7637c..e5f066e6ea 100644 --- a/test/integration/BUILD.bazel +++ b/test/integration/BUILD.bazel @@ -16,29 +16,23 @@ package(default_visibility = ["//visibility:public"]) # Integration Test Rules #################################################### -integration_test( - name = "redis", - data = ["//test/integration/goldens/redis:goldens_files"], - target = ":redis_java_gapic", -) - -integration_test( - name = "asset", - data = ["//test/integration/goldens/asset:goldens_files"], - target = ":asset_java_gapic", -) +INTEGRATION_TEST_LIBRARIES = [ + "asset", + "logging", + "redis", +] -golden_update( - name = "redis_update", - data = ["//test/integration/goldens/redis:goldens_files"], - target = ":redis_java_gapic", -) +[integration_test( + name = lib_name, + data = ["//test/integration/goldens/%s:goldens_files" % lib_name], + target = ":%s_java_gapic" % lib_name, +) for lib_name in INTEGRATION_TEST_LIBRARIES] -golden_update( - name = "asset_update", - data = ["//test/integration/goldens/asset:goldens_files"], - target = ":asset_java_gapic", -) +[golden_update( + name = "%s_update" % lib_name, + data = ["//test/integration/goldens/%s:goldens_files" % lib_name], + target = ":%s_java_gapic" % lib_name, +) for lib_name in INTEGRATION_TEST_LIBRARIES] #################################################### # API Library Rules @@ -66,13 +60,12 @@ java_gapic_assembly_gradle_pkg( name = "google-cloud-asset-v1-java", deps = [ ":asset_java_gapic", - "@com_google_googleapis//google/cloud/orgpolicy/v1:orgpolicy_java_proto", "@com_google_googleapis//google/cloud/asset/v1:asset_java_grpc", - "@com_google_googleapis//google/identity/accesscontextmanager/type:type_java_proto", - "@com_google_googleapis//google/identity/accesscontextmanager/v1:accesscontextmanager_java_proto", "@com_google_googleapis//google/cloud/asset/v1:asset_java_proto", "@com_google_googleapis//google/cloud/asset/v1:asset_proto", - #"@com_google_googleapis//google/iam/v1:iam_java_proto", + "@com_google_googleapis//google/cloud/orgpolicy/v1:orgpolicy_java_proto", + "@com_google_googleapis//google/identity/accesscontextmanager/type:type_java_proto", + "@com_google_googleapis//google/identity/accesscontextmanager/v1:accesscontextmanager_java_proto", ], ) diff --git a/test/integration/goldens/logging/BUILD.bazel b/test/integration/goldens/logging/BUILD.bazel new file mode 100644 index 0000000000..0b74aed56b --- /dev/null +++ b/test/integration/goldens/logging/BUILD.bazel @@ -0,0 +1,6 @@ +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "goldens_files", + srcs = glob(["*.java"]), +) diff --git a/test/integration/goldens/logging/BillingAccountLocationName.java b/test/integration/goldens/logging/BillingAccountLocationName.java new file mode 100644 index 0000000000..3d108a3a4b --- /dev/null +++ b/test/integration/goldens/logging/BillingAccountLocationName.java @@ -0,0 +1,188 @@ +/* + * 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.logging.v2; + +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 BillingAccountLocationName implements ResourceName { + private static final PathTemplate BILLING_ACCOUNT_LOCATION = + PathTemplate.createWithoutUrlEncoding( + "billingAccounts/{billing_account}/locations/{location}"); + private volatile Map fieldValuesMap; + private final String billingAccount; + private final String location; + + private BillingAccountLocationName(Builder builder) { + billingAccount = Preconditions.checkNotNull(builder.getBillingAccount()); + location = Preconditions.checkNotNull(builder.getLocation()); + } + + public String getBillingAccount() { + return billingAccount; + } + + public String getLocation() { + return location; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static BillingAccountLocationName of(String billingAccount, String location) { + return newBuilder().setBillingAccount(billingAccount).setLocation(location).build(); + } + + public static String format(String billingAccount, String location) { + return newBuilder().setBillingAccount(billingAccount).setLocation(location).build().toString(); + } + + public static BillingAccountLocationName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + BILLING_ACCOUNT_LOCATION.validatedMatch( + formattedString, + "BillingAccountLocationName.parse: formattedString not in valid format"); + return of(matchMap.get("billing_account"), matchMap.get("location")); + } + + 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 (BillingAccountLocationName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return BILLING_ACCOUNT_LOCATION.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(billingAccount)) { + fieldMapBuilder.put("billing_account", billingAccount); + } + if (!Objects.isNull(location)) { + fieldMapBuilder.put("location", location); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return BILLING_ACCOUNT_LOCATION.instantiate("billing_account", billingAccount); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + BillingAccountLocationName that = ((BillingAccountLocationName) o); + return Objects.equals(this.billingAccount, that.billingAccount) + && Objects.equals(this.location, that.location); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(billingAccount); + h *= 1000003; + h ^= Objects.hashCode(location); + return h; + } + + /** Builder for billingAccounts/{billing_account}/locations/{location}. */ + public static class Builder { + private String billingAccount; + private String location; + + private Builder() {} + + public String getBillingAccount() { + return billingAccount; + } + + public String getLocation() { + return location; + } + + public Builder setBillingAccount(String billingAccount) { + this.billingAccount = billingAccount; + return this; + } + + public Builder setLocation(String location) { + this.location = location; + return this; + } + + private Builder(BillingAccountLocationName billingAccountLocationName) { + billingAccount = billingAccountLocationName.billingAccount; + location = billingAccountLocationName.location; + } + + public BillingAccountLocationName build() { + return new BillingAccountLocationName(this); + } + } +} diff --git a/test/integration/goldens/logging/BillingAccountName.java b/test/integration/goldens/logging/BillingAccountName.java new file mode 100644 index 0000000000..aac4c70071 --- /dev/null +++ b/test/integration/goldens/logging/BillingAccountName.java @@ -0,0 +1,163 @@ +/* + * 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.logging.v2; + +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 BillingAccountName implements ResourceName { + private static final PathTemplate BILLING_ACCOUNT = + PathTemplate.createWithoutUrlEncoding("billingAccounts/{billing_account}"); + private volatile Map fieldValuesMap; + private final String billingAccount; + + private BillingAccountName(Builder builder) { + billingAccount = Preconditions.checkNotNull(builder.getBillingAccount()); + } + + public String getBillingAccount() { + return billingAccount; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static BillingAccountName of(String billingAccount) { + return newBuilder().setBillingAccount(billingAccount).build(); + } + + public static String format(String billingAccount) { + return newBuilder().setBillingAccount(billingAccount).build().toString(); + } + + public static BillingAccountName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + BILLING_ACCOUNT.validatedMatch( + formattedString, "BillingAccountName.parse: formattedString not in valid format"); + return of(matchMap.get("billing_account")); + } + + 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 (BillingAccountName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return BILLING_ACCOUNT.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(billingAccount)) { + fieldMapBuilder.put("billing_account", billingAccount); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return BILLING_ACCOUNT.instantiate("billing_account", billingAccount); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + BillingAccountName that = ((BillingAccountName) o); + return Objects.equals(this.billingAccount, that.billingAccount); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(billingAccount); + return h; + } + + /** Builder for billingAccounts/{billing_account}. */ + public static class Builder { + private String billingAccount; + + private Builder() {} + + public String getBillingAccount() { + return billingAccount; + } + + public Builder setBillingAccount(String billingAccount) { + this.billingAccount = billingAccount; + return this; + } + + private Builder(BillingAccountName billingAccountName) { + billingAccount = billingAccountName.billingAccount; + } + + public BillingAccountName build() { + return new BillingAccountName(this); + } + } +} diff --git a/test/integration/goldens/logging/CmekSettingsName.java b/test/integration/goldens/logging/CmekSettingsName.java new file mode 100644 index 0000000000..e90b6428a1 --- /dev/null +++ b/test/integration/goldens/logging/CmekSettingsName.java @@ -0,0 +1,375 @@ +/* + * 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.logging.v2; + +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 CmekSettingsName implements ResourceName { + private static final PathTemplate PROJECT = + PathTemplate.createWithoutUrlEncoding("projects/{project}/cmekSettings"); + private static final PathTemplate ORGANIZATION = + PathTemplate.createWithoutUrlEncoding("organizations/{organization}/cmekSettings"); + private static final PathTemplate FOLDER = + PathTemplate.createWithoutUrlEncoding("folders/{folder}/cmekSettings"); + private static final PathTemplate BILLING_ACCOUNT = + PathTemplate.createWithoutUrlEncoding("billingAccounts/{billing_account}/cmekSettings"); + private volatile Map fieldValuesMap; + private PathTemplate pathTemplate; + private String fixedValue; + private final String project; + private final String organization; + private final String folder; + private final String billingAccount; + + private CmekSettingsName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + organization = null; + folder = null; + billingAccount = null; + pathTemplate = PROJECT; + } + + private CmekSettingsName(OrganizationBuilder builder) { + organization = Preconditions.checkNotNull(builder.getOrganization()); + project = null; + folder = null; + billingAccount = null; + pathTemplate = ORGANIZATION; + } + + private CmekSettingsName(FolderBuilder builder) { + folder = Preconditions.checkNotNull(builder.getFolder()); + project = null; + organization = null; + billingAccount = null; + pathTemplate = FOLDER; + } + + private CmekSettingsName(BillingAccountBuilder builder) { + billingAccount = Preconditions.checkNotNull(builder.getBillingAccount()); + project = null; + organization = null; + folder = null; + pathTemplate = BILLING_ACCOUNT; + } + + public String getProject() { + return project; + } + + public String getOrganization() { + return organization; + } + + public String getFolder() { + return folder; + } + + public String getBillingAccount() { + return billingAccount; + } + + 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 newProjectBuilder() { + return new Builder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static OrganizationBuilder newOrganizationBuilder() { + return new OrganizationBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static FolderBuilder newFolderBuilder() { + return new FolderBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static BillingAccountBuilder newBillingAccountBuilder() { + return new BillingAccountBuilder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static CmekSettingsName of(String project) { + return newBuilder().setProject(project).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static CmekSettingsName ofProjectName(String project) { + return newBuilder().setProject(project).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static CmekSettingsName ofOrganizationName(String organization) { + return newOrganizationBuilder().setOrganization(organization).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static CmekSettingsName ofFolderName(String folder) { + return newFolderBuilder().setFolder(folder).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static CmekSettingsName ofBillingAccountName(String billingAccount) { + return newBillingAccountBuilder().setBillingAccount(billingAccount).build(); + } + + public static String format(String project) { + return newBuilder().setProject(project).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatProjectName(String project) { + return newBuilder().setProject(project).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatOrganizationName(String organization) { + return newOrganizationBuilder().setOrganization(organization).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatFolderName(String folder) { + return newFolderBuilder().setFolder(folder).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatBillingAccountName(String billingAccount) { + return newBillingAccountBuilder().setBillingAccount(billingAccount).build().toString(); + } + + public static CmekSettingsName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + if (PROJECT.matches(formattedString)) { + Map matchMap = PROJECT.match(formattedString); + return ofProjectName(matchMap.get("project")); + } else if (ORGANIZATION.matches(formattedString)) { + Map matchMap = ORGANIZATION.match(formattedString); + return ofOrganizationName(matchMap.get("organization")); + } else if (FOLDER.matches(formattedString)) { + Map matchMap = FOLDER.match(formattedString); + return ofFolderName(matchMap.get("folder")); + } else if (BILLING_ACCOUNT.matches(formattedString)) { + Map matchMap = BILLING_ACCOUNT.match(formattedString); + return ofBillingAccountName(matchMap.get("billing_account")); + } + throw new ValidationException("CmekSettingsName.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 (CmekSettingsName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT.matches(formattedString) + || ORGANIZATION.matches(formattedString) + || FOLDER.matches(formattedString) + || BILLING_ACCOUNT.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(project)) { + fieldMapBuilder.put("project", project); + } + if (!Objects.isNull(organization)) { + fieldMapBuilder.put("organization", organization); + } + if (!Objects.isNull(folder)) { + fieldMapBuilder.put("folder", folder); + } + if (!Objects.isNull(billingAccount)) { + fieldMapBuilder.put("billing_account", billingAccount); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return !Objects.isNull(fixedValue) ? fixedValue : pathTemplate.instantiate(getFieldValuesMap()); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + CmekSettingsName that = ((CmekSettingsName) o); + return Objects.equals(this.project, that.project) + && Objects.equals(this.organization, that.organization) + && Objects.equals(this.folder, that.folder) + && Objects.equals(this.billingAccount, that.billingAccount); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(fixedValue); + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(organization); + h *= 1000003; + h ^= Objects.hashCode(folder); + h *= 1000003; + h ^= Objects.hashCode(billingAccount); + return h; + } + + /** Builder for projects/{project}/cmekSettings. */ + public static class Builder { + private String project; + + private Builder() {} + + public String getProject() { + return project; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + private Builder(CmekSettingsName cmekSettingsName) { + Preconditions.checkArgument( + Objects.equals(cmekSettingsName.pathTemplate, PROJECT), + "toBuilder is only supported when CmekSettingsName has the pattern of projects/{project}/cmekSettings"); + project = cmekSettingsName.project; + } + + public CmekSettingsName build() { + return new CmekSettingsName(this); + } + } + + /** Builder for organizations/{organization}/cmekSettings. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class OrganizationBuilder { + private String organization; + + private OrganizationBuilder() {} + + public String getOrganization() { + return organization; + } + + public OrganizationBuilder setOrganization(String organization) { + this.organization = organization; + return this; + } + + public CmekSettingsName build() { + return new CmekSettingsName(this); + } + } + + /** Builder for folders/{folder}/cmekSettings. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class FolderBuilder { + private String folder; + + private FolderBuilder() {} + + public String getFolder() { + return folder; + } + + public FolderBuilder setFolder(String folder) { + this.folder = folder; + return this; + } + + public CmekSettingsName build() { + return new CmekSettingsName(this); + } + } + + /** Builder for billingAccounts/{billing_account}/cmekSettings. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class BillingAccountBuilder { + private String billingAccount; + + private BillingAccountBuilder() {} + + public String getBillingAccount() { + return billingAccount; + } + + public BillingAccountBuilder setBillingAccount(String billingAccount) { + this.billingAccount = billingAccount; + return this; + } + + public CmekSettingsName build() { + return new CmekSettingsName(this); + } + } +} diff --git a/test/integration/goldens/logging/ConfigServiceV2Client.java b/test/integration/goldens/logging/ConfigServiceV2Client.java new file mode 100644 index 0000000000..f3b1c319ba --- /dev/null +++ b/test/integration/goldens/logging/ConfigServiceV2Client.java @@ -0,0 +1,1707 @@ +/* + * 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.logging.v2; + +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.paging.AbstractFixedSizeCollection; +import com.google.api.gax.paging.AbstractPage; +import com.google.api.gax.paging.AbstractPagedListResponse; +import com.google.api.gax.rpc.PageContext; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.logging.v2.stub.ConfigServiceV2Stub; +import com.google.logging.v2.stub.ConfigServiceV2StubSettings; +import com.google.protobuf.Empty; +import com.google.protobuf.FieldMask; +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. +/** + * Service Description: Service for configuring sinks used to route log entries. + * + *

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 ConfigServiceV2Settings to + * create(). For example: + * + *

To customize credentials: + * + *

To customize the endpoint: + */ +@BetaApi +@Generated("by gapic-generator") +public class ConfigServiceV2Client implements BackgroundResource { + private final ConfigServiceV2Settings settings; + private final ConfigServiceV2Stub stub; + + /** Constructs an instance of EchoClient with default settings. */ + public static final ConfigServiceV2Client create() throws IOException { + return create(ConfigServiceV2Settings.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 ConfigServiceV2Client create(ConfigServiceV2Settings settings) + throws IOException { + return new ConfigServiceV2Client(settings); + } + + /** + * Constructs an instance of EchoClient, using the given stub for making calls. This is for + * advanced usage - prefer using create(ConfigServiceV2Settings). + */ + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public static final ConfigServiceV2Client create(ConfigServiceV2Stub stub) { + return new ConfigServiceV2Client(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 ConfigServiceV2Client(ConfigServiceV2Settings settings) throws IOException { + this.settings = settings; + this.stub = ((ConfigServiceV2StubSettings) settings.getStubSettings()).createStub(); + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + protected ConfigServiceV2Client(ConfigServiceV2Stub stub) { + this.settings = null; + this.stub = stub; + } + + public final ConfigServiceV2Settings getSettings() { + return settings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public ConfigServiceV2Stub getStub() { + return stub; + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists buckets (Beta). + * + *

Sample code: + * + * @param parent Required. The parent resource whose buckets are to be listed: + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" Note: The locations portion of the resource + * must be specified, but supplying the character `-` in place of [LOCATION_ID] will return + * all buckets. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListBucketsPagedResponse listBuckets(BillingAccountLocationName parent) { + ListBucketsRequest request = + ListBucketsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listBuckets(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists buckets (Beta). + * + *

Sample code: + * + * @param parent Required. The parent resource whose buckets are to be listed: + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" Note: The locations portion of the resource + * must be specified, but supplying the character `-` in place of [LOCATION_ID] will return + * all buckets. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListBucketsPagedResponse listBuckets(FolderLocationName parent) { + ListBucketsRequest request = + ListBucketsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listBuckets(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists buckets (Beta). + * + *

Sample code: + * + * @param parent Required. The parent resource whose buckets are to be listed: + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" Note: The locations portion of the resource + * must be specified, but supplying the character `-` in place of [LOCATION_ID] will return + * all buckets. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListBucketsPagedResponse listBuckets(LocationName parent) { + ListBucketsRequest request = + ListBucketsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listBuckets(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists buckets (Beta). + * + *

Sample code: + * + * @param parent Required. The parent resource whose buckets are to be listed: + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" Note: The locations portion of the resource + * must be specified, but supplying the character `-` in place of [LOCATION_ID] will return + * all buckets. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListBucketsPagedResponse listBuckets(OrganizationLocationName parent) { + ListBucketsRequest request = + ListBucketsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listBuckets(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists buckets (Beta). + * + *

Sample code: + * + * @param parent Required. The parent resource whose buckets are to be listed: + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" Note: The locations portion of the resource + * must be specified, but supplying the character `-` in place of [LOCATION_ID] will return + * all buckets. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListBucketsPagedResponse listBuckets(String parent) { + ListBucketsRequest request = ListBucketsRequest.newBuilder().setParent(parent).build(); + return listBuckets(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists buckets (Beta). + * + *

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 ListBucketsPagedResponse listBuckets(ListBucketsRequest request) { + return listBucketsPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists buckets (Beta). + * + *

Sample code: + */ + public final UnaryCallable + listBucketsPagedCallable() { + return stub.listBucketsPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists buckets (Beta). + * + *

Sample code: + */ + public final UnaryCallable listBucketsCallable() { + return stub.listBucketsCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a bucket (Beta). + * + *

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 LogBucket getBucket(GetBucketRequest request) { + return getBucketCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a bucket (Beta). + * + *

Sample code: + */ + public final UnaryCallable getBucketCallable() { + return stub.getBucketCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates a bucket. This method replaces the following fields in the existing bucket with values + * from the new bucket: `retention_period` If the retention period is decreased and the bucket is + * locked, FAILED_PRECONDITION will be returned. If the bucket has a LifecycleState of + * DELETE_REQUESTED, FAILED_PRECONDITION will be returned. A buckets region may not be modified + * after it is created. This method is in Beta. + * + *

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 LogBucket updateBucket(UpdateBucketRequest request) { + return updateBucketCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates a bucket. This method replaces the following fields in the existing bucket with values + * from the new bucket: `retention_period` If the retention period is decreased and the bucket is + * locked, FAILED_PRECONDITION will be returned. If the bucket has a LifecycleState of + * DELETE_REQUESTED, FAILED_PRECONDITION will be returned. A buckets region may not be modified + * after it is created. This method is in Beta. + * + *

Sample code: + */ + public final UnaryCallable updateBucketCallable() { + return stub.updateBucketCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists sinks. + * + *

Sample code: + * + * @param parent Required. The parent resource whose sinks are to be listed: + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSinksPagedResponse listSinks(BillingAccountName parent) { + ListSinksRequest request = + ListSinksRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listSinks(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists sinks. + * + *

Sample code: + * + * @param parent Required. The parent resource whose sinks are to be listed: + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSinksPagedResponse listSinks(FolderName parent) { + ListSinksRequest request = + ListSinksRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listSinks(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists sinks. + * + *

Sample code: + * + * @param parent Required. The parent resource whose sinks are to be listed: + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSinksPagedResponse listSinks(OrganizationName parent) { + ListSinksRequest request = + ListSinksRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listSinks(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists sinks. + * + *

Sample code: + * + * @param parent Required. The parent resource whose sinks are to be listed: + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSinksPagedResponse listSinks(ProjectName parent) { + ListSinksRequest request = + ListSinksRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listSinks(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists sinks. + * + *

Sample code: + * + * @param parent Required. The parent resource whose sinks are to be listed: + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSinksPagedResponse listSinks(String parent) { + ListSinksRequest request = ListSinksRequest.newBuilder().setParent(parent).build(); + return listSinks(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists sinks. + * + *

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 ListSinksPagedResponse listSinks(ListSinksRequest request) { + return listSinksPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists sinks. + * + *

Sample code: + */ + public final UnaryCallable listSinksPagedCallable() { + return stub.listSinksPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists sinks. + * + *

Sample code: + */ + public final UnaryCallable listSinksCallable() { + return stub.listSinksCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a sink. + * + *

Sample code: + * + * @param sink_name Required. The resource name of the sink: + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink getSink(LogSinkName sinkName) { + GetSinkRequest request = + GetSinkRequest.newBuilder() + .setSinkName(Objects.isNull(sinkName) ? null : sinkName.toString()) + .build(); + return getSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a sink. + * + *

Sample code: + * + * @param sink_name Required. The resource name of the sink: + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink getSink(String sinkName) { + GetSinkRequest request = GetSinkRequest.newBuilder().setSinkName(sinkName).build(); + return getSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a sink. + * + *

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 LogSink getSink(GetSinkRequest request) { + return getSinkCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a sink. + * + *

Sample code: + */ + public final UnaryCallable getSinkCallable() { + return stub.getSinkCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a sink that exports specified log entries to a destination. The export of + * newly-ingested log entries begins immediately, unless the sink's `writer_identity` is not + * permitted to write to the destination. A sink can export log entries only from the resource + * owning the sink. + * + *

Sample code: + * + * @param parent Required. The resource in which to create the sink: "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" Examples: `"projects/my-logging-project"`, + * `"organizations/123456789"`. + * @param sink Required. The new sink, whose `name` parameter is a sink identifier that is not + * already in use. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink createSink(BillingAccountName parent, LogSink sink) { + CreateSinkRequest request = + CreateSinkRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .setSink(sink) + .build(); + return createSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a sink that exports specified log entries to a destination. The export of + * newly-ingested log entries begins immediately, unless the sink's `writer_identity` is not + * permitted to write to the destination. A sink can export log entries only from the resource + * owning the sink. + * + *

Sample code: + * + * @param parent Required. The resource in which to create the sink: "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" Examples: `"projects/my-logging-project"`, + * `"organizations/123456789"`. + * @param sink Required. The new sink, whose `name` parameter is a sink identifier that is not + * already in use. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink createSink(FolderName parent, LogSink sink) { + CreateSinkRequest request = + CreateSinkRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .setSink(sink) + .build(); + return createSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a sink that exports specified log entries to a destination. The export of + * newly-ingested log entries begins immediately, unless the sink's `writer_identity` is not + * permitted to write to the destination. A sink can export log entries only from the resource + * owning the sink. + * + *

Sample code: + * + * @param parent Required. The resource in which to create the sink: "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" Examples: `"projects/my-logging-project"`, + * `"organizations/123456789"`. + * @param sink Required. The new sink, whose `name` parameter is a sink identifier that is not + * already in use. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink createSink(OrganizationName parent, LogSink sink) { + CreateSinkRequest request = + CreateSinkRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .setSink(sink) + .build(); + return createSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a sink that exports specified log entries to a destination. The export of + * newly-ingested log entries begins immediately, unless the sink's `writer_identity` is not + * permitted to write to the destination. A sink can export log entries only from the resource + * owning the sink. + * + *

Sample code: + * + * @param parent Required. The resource in which to create the sink: "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" Examples: `"projects/my-logging-project"`, + * `"organizations/123456789"`. + * @param sink Required. The new sink, whose `name` parameter is a sink identifier that is not + * already in use. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink createSink(ProjectName parent, LogSink sink) { + CreateSinkRequest request = + CreateSinkRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .setSink(sink) + .build(); + return createSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a sink that exports specified log entries to a destination. The export of + * newly-ingested log entries begins immediately, unless the sink's `writer_identity` is not + * permitted to write to the destination. A sink can export log entries only from the resource + * owning the sink. + * + *

Sample code: + * + * @param parent Required. The resource in which to create the sink: "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" Examples: `"projects/my-logging-project"`, + * `"organizations/123456789"`. + * @param sink Required. The new sink, whose `name` parameter is a sink identifier that is not + * already in use. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink createSink(String parent, LogSink sink) { + CreateSinkRequest request = + CreateSinkRequest.newBuilder().setParent(parent).setSink(sink).build(); + return createSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a sink that exports specified log entries to a destination. The export of + * newly-ingested log entries begins immediately, unless the sink's `writer_identity` is not + * permitted to write to the destination. A sink can export log entries only from the resource + * owning the sink. + * + *

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 LogSink createSink(CreateSinkRequest request) { + return createSinkCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a sink that exports specified log entries to a destination. The export of + * newly-ingested log entries begins immediately, unless the sink's `writer_identity` is not + * permitted to write to the destination. A sink can export log entries only from the resource + * owning the sink. + * + *

Sample code: + */ + public final UnaryCallable createSinkCallable() { + return stub.createSinkCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates a sink. This method replaces the following fields in the existing sink with values from + * the new sink: `destination`, and `filter`. The updated sink might also have a new + * `writer_identity`; see the `unique_writer_identity` field. + * + *

Sample code: + * + * @param sink_name Required. The full resource name of the sink to update, including the parent + * resource and the sink identifier: "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param sink Required. The updated sink, whose name is the same identifier that appears as part + * of `sink_name`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink updateSink(LogSinkName sinkName, LogSink sink) { + UpdateSinkRequest request = + UpdateSinkRequest.newBuilder() + .setSinkName(Objects.isNull(sinkName) ? null : sinkName.toString()) + .setSink(sink) + .build(); + return updateSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates a sink. This method replaces the following fields in the existing sink with values from + * the new sink: `destination`, and `filter`. The updated sink might also have a new + * `writer_identity`; see the `unique_writer_identity` field. + * + *

Sample code: + * + * @param sink_name Required. The full resource name of the sink to update, including the parent + * resource and the sink identifier: "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param sink Required. The updated sink, whose name is the same identifier that appears as part + * of `sink_name`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink updateSink(String sinkName, LogSink sink) { + UpdateSinkRequest request = + UpdateSinkRequest.newBuilder().setSinkName(sinkName).setSink(sink).build(); + return updateSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates a sink. This method replaces the following fields in the existing sink with values from + * the new sink: `destination`, and `filter`. The updated sink might also have a new + * `writer_identity`; see the `unique_writer_identity` field. + * + *

Sample code: + * + * @param sink_name Required. The full resource name of the sink to update, including the parent + * resource and the sink identifier: "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param sink Required. The updated sink, whose name is the same identifier that appears as part + * of `sink_name`. + * @param update_mask Optional. Field mask that specifies the fields in `sink` that need an + * update. A sink field will be overwritten if, and only if, it is in the update mask. `name` + * and output only fields cannot be updated. An empty updateMask is temporarily treated as + * using the following mask for backwards compatibility purposes: + * destination,filter,includeChildren At some point in the future, behavior will be removed + * and specifying an empty updateMask will be an error. For a detailed `FieldMask` definition, + * see + * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + * Example: `updateMask=filter`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink updateSink(LogSinkName sinkName, LogSink sink, FieldMask updateMask) { + UpdateSinkRequest request = + UpdateSinkRequest.newBuilder() + .setSinkName(Objects.isNull(sinkName) ? null : sinkName.toString()) + .setSink(sink) + .setUpdateMask(updateMask) + .build(); + return updateSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates a sink. This method replaces the following fields in the existing sink with values from + * the new sink: `destination`, and `filter`. The updated sink might also have a new + * `writer_identity`; see the `unique_writer_identity` field. + * + *

Sample code: + * + * @param sink_name Required. The full resource name of the sink to update, including the parent + * resource and the sink identifier: "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param sink Required. The updated sink, whose name is the same identifier that appears as part + * of `sink_name`. + * @param update_mask Optional. Field mask that specifies the fields in `sink` that need an + * update. A sink field will be overwritten if, and only if, it is in the update mask. `name` + * and output only fields cannot be updated. An empty updateMask is temporarily treated as + * using the following mask for backwards compatibility purposes: + * destination,filter,includeChildren At some point in the future, behavior will be removed + * and specifying an empty updateMask will be an error. For a detailed `FieldMask` definition, + * see + * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + * Example: `updateMask=filter`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogSink updateSink(String sinkName, LogSink sink, FieldMask updateMask) { + UpdateSinkRequest request = + UpdateSinkRequest.newBuilder() + .setSinkName(sinkName) + .setSink(sink) + .setUpdateMask(updateMask) + .build(); + return updateSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates a sink. This method replaces the following fields in the existing sink with values from + * the new sink: `destination`, and `filter`. The updated sink might also have a new + * `writer_identity`; see the `unique_writer_identity` field. + * + *

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 LogSink updateSink(UpdateSinkRequest request) { + return updateSinkCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates a sink. This method replaces the following fields in the existing sink with values from + * the new sink: `destination`, and `filter`. The updated sink might also have a new + * `writer_identity`; see the `unique_writer_identity` field. + * + *

Sample code: + */ + public final UnaryCallable updateSinkCallable() { + return stub.updateSinkCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a sink. If the sink has a unique `writer_identity`, then that service account is also + * deleted. + * + *

Sample code: + * + * @param sink_name Required. The full resource name of the sink to delete, including the parent + * resource and the sink identifier: "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Empty deleteSink(LogSinkName sinkName) { + DeleteSinkRequest request = + DeleteSinkRequest.newBuilder() + .setSinkName(Objects.isNull(sinkName) ? null : sinkName.toString()) + .build(); + return deleteSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a sink. If the sink has a unique `writer_identity`, then that service account is also + * deleted. + * + *

Sample code: + * + * @param sink_name Required. The full resource name of the sink to delete, including the parent + * resource and the sink identifier: "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Empty deleteSink(String sinkName) { + DeleteSinkRequest request = DeleteSinkRequest.newBuilder().setSinkName(sinkName).build(); + return deleteSink(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a sink. If the sink has a unique `writer_identity`, then that service account is also + * deleted. + * + *

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 Empty deleteSink(DeleteSinkRequest request) { + return deleteSinkCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a sink. If the sink has a unique `writer_identity`, then that service account is also + * deleted. + * + *

Sample code: + */ + public final UnaryCallable deleteSinkCallable() { + return stub.deleteSinkCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists all the exclusions in a parent resource. + * + *

Sample code: + * + * @param parent Required. The parent resource whose exclusions are to be listed. + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListExclusionsPagedResponse listExclusions(BillingAccountName parent) { + ListExclusionsRequest request = + ListExclusionsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listExclusions(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists all the exclusions in a parent resource. + * + *

Sample code: + * + * @param parent Required. The parent resource whose exclusions are to be listed. + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListExclusionsPagedResponse listExclusions(FolderName parent) { + ListExclusionsRequest request = + ListExclusionsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listExclusions(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists all the exclusions in a parent resource. + * + *

Sample code: + * + * @param parent Required. The parent resource whose exclusions are to be listed. + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListExclusionsPagedResponse listExclusions(OrganizationName parent) { + ListExclusionsRequest request = + ListExclusionsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listExclusions(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists all the exclusions in a parent resource. + * + *

Sample code: + * + * @param parent Required. The parent resource whose exclusions are to be listed. + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListExclusionsPagedResponse listExclusions(ProjectName parent) { + ListExclusionsRequest request = + ListExclusionsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listExclusions(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists all the exclusions in a parent resource. + * + *

Sample code: + * + * @param parent Required. The parent resource whose exclusions are to be listed. + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListExclusionsPagedResponse listExclusions(String parent) { + ListExclusionsRequest request = ListExclusionsRequest.newBuilder().setParent(parent).build(); + return listExclusions(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists all the exclusions in a parent resource. + * + *

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 ListExclusionsPagedResponse listExclusions(ListExclusionsRequest request) { + return listExclusionsPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists all the exclusions in a parent resource. + * + *

Sample code: + */ + public final UnaryCallable + listExclusionsPagedCallable() { + return stub.listExclusionsPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists all the exclusions in a parent resource. + * + *

Sample code: + */ + public final UnaryCallable + listExclusionsCallable() { + return stub.listExclusionsCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the description of an exclusion. + * + *

Sample code: + * + * @param name Required. The resource name of an existing exclusion: + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" Example: + * `"projects/my-project-id/exclusions/my-exclusion-id"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogExclusion getExclusion(LogExclusionName name) { + GetExclusionRequest request = + GetExclusionRequest.newBuilder() + .setName(Objects.isNull(name) ? null : name.toString()) + .build(); + return getExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the description of an exclusion. + * + *

Sample code: + * + * @param name Required. The resource name of an existing exclusion: + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" Example: + * `"projects/my-project-id/exclusions/my-exclusion-id"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogExclusion getExclusion(String name) { + GetExclusionRequest request = GetExclusionRequest.newBuilder().setName(name).build(); + return getExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the description of an exclusion. + * + *

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 LogExclusion getExclusion(GetExclusionRequest request) { + return getExclusionCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the description of an exclusion. + * + *

Sample code: + */ + public final UnaryCallable getExclusionCallable() { + return stub.getExclusionCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a new exclusion in a specified parent resource. Only log entries belonging to that + * resource can be excluded. You can have up to 10 exclusions in a resource. + * + *

Sample code: + * + * @param parent Required. The parent resource in which to create the exclusion: + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: + * `"projects/my-logging-project"`, `"organizations/123456789"`. + * @param exclusion Required. The new exclusion, whose `name` parameter is an exclusion name that + * is not already used in the parent resource. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogExclusion createExclusion(BillingAccountName parent, LogExclusion exclusion) { + CreateExclusionRequest request = + CreateExclusionRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .setExclusion(exclusion) + .build(); + return createExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a new exclusion in a specified parent resource. Only log entries belonging to that + * resource can be excluded. You can have up to 10 exclusions in a resource. + * + *

Sample code: + * + * @param parent Required. The parent resource in which to create the exclusion: + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: + * `"projects/my-logging-project"`, `"organizations/123456789"`. + * @param exclusion Required. The new exclusion, whose `name` parameter is an exclusion name that + * is not already used in the parent resource. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogExclusion createExclusion(FolderName parent, LogExclusion exclusion) { + CreateExclusionRequest request = + CreateExclusionRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .setExclusion(exclusion) + .build(); + return createExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a new exclusion in a specified parent resource. Only log entries belonging to that + * resource can be excluded. You can have up to 10 exclusions in a resource. + * + *

Sample code: + * + * @param parent Required. The parent resource in which to create the exclusion: + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: + * `"projects/my-logging-project"`, `"organizations/123456789"`. + * @param exclusion Required. The new exclusion, whose `name` parameter is an exclusion name that + * is not already used in the parent resource. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogExclusion createExclusion(OrganizationName parent, LogExclusion exclusion) { + CreateExclusionRequest request = + CreateExclusionRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .setExclusion(exclusion) + .build(); + return createExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a new exclusion in a specified parent resource. Only log entries belonging to that + * resource can be excluded. You can have up to 10 exclusions in a resource. + * + *

Sample code: + * + * @param parent Required. The parent resource in which to create the exclusion: + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: + * `"projects/my-logging-project"`, `"organizations/123456789"`. + * @param exclusion Required. The new exclusion, whose `name` parameter is an exclusion name that + * is not already used in the parent resource. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogExclusion createExclusion(ProjectName parent, LogExclusion exclusion) { + CreateExclusionRequest request = + CreateExclusionRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .setExclusion(exclusion) + .build(); + return createExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a new exclusion in a specified parent resource. Only log entries belonging to that + * resource can be excluded. You can have up to 10 exclusions in a resource. + * + *

Sample code: + * + * @param parent Required. The parent resource in which to create the exclusion: + * "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: + * `"projects/my-logging-project"`, `"organizations/123456789"`. + * @param exclusion Required. The new exclusion, whose `name` parameter is an exclusion name that + * is not already used in the parent resource. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogExclusion createExclusion(String parent, LogExclusion exclusion) { + CreateExclusionRequest request = + CreateExclusionRequest.newBuilder().setParent(parent).setExclusion(exclusion).build(); + return createExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a new exclusion in a specified parent resource. Only log entries belonging to that + * resource can be excluded. You can have up to 10 exclusions in a resource. + * + *

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 LogExclusion createExclusion(CreateExclusionRequest request) { + return createExclusionCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a new exclusion in a specified parent resource. Only log entries belonging to that + * resource can be excluded. You can have up to 10 exclusions in a resource. + * + *

Sample code: + */ + public final UnaryCallable createExclusionCallable() { + return stub.createExclusionCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Changes one or more properties of an existing exclusion. + * + *

Sample code: + * + * @param name Required. The resource name of the exclusion to update: + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" Example: + * `"projects/my-project-id/exclusions/my-exclusion-id"`. + * @param exclusion Required. New values for the existing exclusion. Only the fields specified in + * `update_mask` are relevant. + * @param update_mask Required. A non-empty list of fields to change in the existing exclusion. + * New values for the fields are taken from the corresponding fields in the + * [LogExclusion][google.logging.v2.LogExclusion] included in this request. Fields not + * mentioned in `update_mask` are not changed and are ignored in the request. For example, to + * change the filter and description of an exclusion, specify an `update_mask` of + * `"filter,description"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogExclusion updateExclusion( + LogExclusionName name, LogExclusion exclusion, FieldMask updateMask) { + UpdateExclusionRequest request = + UpdateExclusionRequest.newBuilder() + .setName(Objects.isNull(name) ? null : name.toString()) + .setExclusion(exclusion) + .setUpdateMask(updateMask) + .build(); + return updateExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Changes one or more properties of an existing exclusion. + * + *

Sample code: + * + * @param name Required. The resource name of the exclusion to update: + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" Example: + * `"projects/my-project-id/exclusions/my-exclusion-id"`. + * @param exclusion Required. New values for the existing exclusion. Only the fields specified in + * `update_mask` are relevant. + * @param update_mask Required. A non-empty list of fields to change in the existing exclusion. + * New values for the fields are taken from the corresponding fields in the + * [LogExclusion][google.logging.v2.LogExclusion] included in this request. Fields not + * mentioned in `update_mask` are not changed and are ignored in the request. For example, to + * change the filter and description of an exclusion, specify an `update_mask` of + * `"filter,description"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogExclusion updateExclusion( + String name, LogExclusion exclusion, FieldMask updateMask) { + UpdateExclusionRequest request = + UpdateExclusionRequest.newBuilder() + .setName(name) + .setExclusion(exclusion) + .setUpdateMask(updateMask) + .build(); + return updateExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Changes one or more properties of an existing exclusion. + * + *

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 LogExclusion updateExclusion(UpdateExclusionRequest request) { + return updateExclusionCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Changes one or more properties of an existing exclusion. + * + *

Sample code: + */ + public final UnaryCallable updateExclusionCallable() { + return stub.updateExclusionCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes an exclusion. + * + *

Sample code: + * + * @param name Required. The resource name of an existing exclusion to delete: + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" Example: + * `"projects/my-project-id/exclusions/my-exclusion-id"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Empty deleteExclusion(LogExclusionName name) { + DeleteExclusionRequest request = + DeleteExclusionRequest.newBuilder() + .setName(Objects.isNull(name) ? null : name.toString()) + .build(); + return deleteExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes an exclusion. + * + *

Sample code: + * + * @param name Required. The resource name of an existing exclusion to delete: + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" Example: + * `"projects/my-project-id/exclusions/my-exclusion-id"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Empty deleteExclusion(String name) { + DeleteExclusionRequest request = DeleteExclusionRequest.newBuilder().setName(name).build(); + return deleteExclusion(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes an exclusion. + * + *

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 Empty deleteExclusion(DeleteExclusionRequest request) { + return deleteExclusionCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes an exclusion. + * + *

Sample code: + */ + public final UnaryCallable deleteExclusionCallable() { + return stub.deleteExclusionCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the Logs Router CMEK settings for the given resource. Note: CMEK for the Logs Router can + * currently only be configured for GCP organizations. Once configured, it applies to all projects + * and folders in the GCP organization. See [Enabling CMEK for Logs + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. + * + *

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 CmekSettings getCmekSettings(GetCmekSettingsRequest request) { + return getCmekSettingsCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the Logs Router CMEK settings for the given resource. Note: CMEK for the Logs Router can + * currently only be configured for GCP organizations. Once configured, it applies to all projects + * and folders in the GCP organization. See [Enabling CMEK for Logs + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. + * + *

Sample code: + */ + public final UnaryCallable getCmekSettingsCallable() { + return stub.getCmekSettingsCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates the Logs Router CMEK settings for the given resource. Note: CMEK for the Logs Router + * can currently only be configured for GCP organizations. Once configured, it applies to all + * projects and folders in the GCP organization. + * [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] will fail if 1) + * `kms_key_name` is invalid, or 2) the associated service account does not have the required + * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or 3) access to the key + * is disabled. See [Enabling CMEK for Logs + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. + * + *

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 CmekSettings updateCmekSettings(UpdateCmekSettingsRequest request) { + return updateCmekSettingsCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates the Logs Router CMEK settings for the given resource. Note: CMEK for the Logs Router + * can currently only be configured for GCP organizations. Once configured, it applies to all + * projects and folders in the GCP organization. + * [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] will fail if 1) + * `kms_key_name` is invalid, or 2) the associated service account does not have the required + * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or 3) access to the key + * is disabled. See [Enabling CMEK for Logs + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. + * + *

Sample code: + */ + public final UnaryCallable updateCmekSettingsCallable() { + return stub.updateCmekSettingsCallable(); + } + + @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 ListBucketsPagedResponse + extends AbstractPagedListResponse< + ListBucketsRequest, + ListBucketsResponse, + LogBucket, + ListBucketsPage, + ListBucketsFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListBucketsPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListBucketsPagedResponse apply(ListBucketsPage input) { + return new ListBucketsPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListBucketsPagedResponse(ListBucketsPage page) { + super(page, ListBucketsFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListBucketsPage + extends AbstractPage { + + private ListBucketsPage( + PageContext context, + ListBucketsResponse response) { + super(context, response); + } + + private static ListBucketsPage createEmptyPage() { + return new ListBucketsPage(null, null); + } + + @Override + protected ListBucketsPage createPage( + PageContext context, + ListBucketsResponse response) { + return new ListBucketsPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListBucketsFixedSizeCollection + extends AbstractFixedSizeCollection< + ListBucketsRequest, + ListBucketsResponse, + LogBucket, + ListBucketsPage, + ListBucketsFixedSizeCollection> { + + private ListBucketsFixedSizeCollection(List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListBucketsFixedSizeCollection createEmptyCollection() { + return new ListBucketsFixedSizeCollection(null, 0); + } + + @Override + protected ListBucketsFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListBucketsFixedSizeCollection(pages, collectionSize); + } + } + + public static class ListSinksPagedResponse + extends AbstractPagedListResponse< + ListSinksRequest, + ListSinksResponse, + LogSink, + ListSinksPage, + ListSinksFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListSinksPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListSinksPagedResponse apply(ListSinksPage input) { + return new ListSinksPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListSinksPagedResponse(ListSinksPage page) { + super(page, ListSinksFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListSinksPage + extends AbstractPage { + + private ListSinksPage( + PageContext context, + ListSinksResponse response) { + super(context, response); + } + + private static ListSinksPage createEmptyPage() { + return new ListSinksPage(null, null); + } + + @Override + protected ListSinksPage createPage( + PageContext context, + ListSinksResponse response) { + return new ListSinksPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListSinksFixedSizeCollection + extends AbstractFixedSizeCollection< + ListSinksRequest, + ListSinksResponse, + LogSink, + ListSinksPage, + ListSinksFixedSizeCollection> { + + private ListSinksFixedSizeCollection(List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListSinksFixedSizeCollection createEmptyCollection() { + return new ListSinksFixedSizeCollection(null, 0); + } + + @Override + protected ListSinksFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListSinksFixedSizeCollection(pages, collectionSize); + } + } + + public static class ListExclusionsPagedResponse + extends AbstractPagedListResponse< + ListExclusionsRequest, + ListExclusionsResponse, + LogExclusion, + ListExclusionsPage, + ListExclusionsFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListExclusionsPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListExclusionsPagedResponse apply(ListExclusionsPage input) { + return new ListExclusionsPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListExclusionsPagedResponse(ListExclusionsPage page) { + super(page, ListExclusionsFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListExclusionsPage + extends AbstractPage< + ListExclusionsRequest, ListExclusionsResponse, LogExclusion, ListExclusionsPage> { + + private ListExclusionsPage( + PageContext context, + ListExclusionsResponse response) { + super(context, response); + } + + private static ListExclusionsPage createEmptyPage() { + return new ListExclusionsPage(null, null); + } + + @Override + protected ListExclusionsPage createPage( + PageContext context, + ListExclusionsResponse response) { + return new ListExclusionsPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListExclusionsFixedSizeCollection + extends AbstractFixedSizeCollection< + ListExclusionsRequest, + ListExclusionsResponse, + LogExclusion, + ListExclusionsPage, + ListExclusionsFixedSizeCollection> { + + private ListExclusionsFixedSizeCollection(List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListExclusionsFixedSizeCollection createEmptyCollection() { + return new ListExclusionsFixedSizeCollection(null, 0); + } + + @Override + protected ListExclusionsFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListExclusionsFixedSizeCollection(pages, collectionSize); + } + } +} diff --git a/test/integration/goldens/logging/ConfigServiceV2Settings.java b/test/integration/goldens/logging/ConfigServiceV2Settings.java new file mode 100644 index 0000000000..1ae26f5c78 --- /dev/null +++ b/test/integration/goldens/logging/ConfigServiceV2Settings.java @@ -0,0 +1,327 @@ +/* + * 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.logging.v2; + +import static com.google.logging.v2.ConfigServiceV2Client.ListBucketsPagedResponse; +import static com.google.logging.v2.ConfigServiceV2Client.ListExclusionsPagedResponse; +import static com.google.logging.v2.ConfigServiceV2Client.ListSinksPagedResponse; + +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.PagedCallSettings; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.logging.v2.stub.ConfigServiceV2StubSettings; +import com.google.protobuf.Empty; +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 ConfigServiceV2Client}. + * + *

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 listBuckets to 30 seconds: + */ +@Generated("by gapic-generator-java") +public class ConfigServiceV2Settings extends ClientSettings { + + /** Returns the object with the settings used for calls to listBuckets. */ + public PagedCallSettings + listBucketsSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).listBucketsSettings(); + } + + /** Returns the object with the settings used for calls to getBucket. */ + public UnaryCallSettings getBucketSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).getBucketSettings(); + } + + /** Returns the object with the settings used for calls to updateBucket. */ + public UnaryCallSettings updateBucketSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).updateBucketSettings(); + } + + /** Returns the object with the settings used for calls to listSinks. */ + public PagedCallSettings + listSinksSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).listSinksSettings(); + } + + /** Returns the object with the settings used for calls to getSink. */ + public UnaryCallSettings getSinkSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).getSinkSettings(); + } + + /** Returns the object with the settings used for calls to createSink. */ + public UnaryCallSettings createSinkSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).createSinkSettings(); + } + + /** Returns the object with the settings used for calls to updateSink. */ + public UnaryCallSettings updateSinkSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).updateSinkSettings(); + } + + /** Returns the object with the settings used for calls to deleteSink. */ + public UnaryCallSettings deleteSinkSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).deleteSinkSettings(); + } + + /** Returns the object with the settings used for calls to listExclusions. */ + public PagedCallSettings< + ListExclusionsRequest, ListExclusionsResponse, ListExclusionsPagedResponse> + listExclusionsSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).listExclusionsSettings(); + } + + /** Returns the object with the settings used for calls to getExclusion. */ + public UnaryCallSettings getExclusionSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).getExclusionSettings(); + } + + /** Returns the object with the settings used for calls to createExclusion. */ + public UnaryCallSettings createExclusionSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).createExclusionSettings(); + } + + /** Returns the object with the settings used for calls to updateExclusion. */ + public UnaryCallSettings updateExclusionSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).updateExclusionSettings(); + } + + /** Returns the object with the settings used for calls to deleteExclusion. */ + public UnaryCallSettings deleteExclusionSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).deleteExclusionSettings(); + } + + /** Returns the object with the settings used for calls to getCmekSettings. */ + public UnaryCallSettings getCmekSettingsSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).getCmekSettingsSettings(); + } + + /** Returns the object with the settings used for calls to updateCmekSettings. */ + public UnaryCallSettings updateCmekSettingsSettings() { + return ((ConfigServiceV2StubSettings) getStubSettings()).updateCmekSettingsSettings(); + } + + public static final ConfigServiceV2Settings create(ConfigServiceV2StubSettings stub) + throws IOException { + return new ConfigServiceV2Settings.Builder(stub.toBuilder()).build(); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return ConfigServiceV2StubSettings.defaultExecutorProviderBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return ConfigServiceV2StubSettings.getDefaultEndpoint(); + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return ConfigServiceV2StubSettings.getDefaultServiceScopes(); + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return ConfigServiceV2StubSettings.defaultCredentialsProviderBuilder(); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return ConfigServiceV2StubSettings.defaultGrpcTransportProviderBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return ConfigServiceV2StubSettings.defaultTransportChannelProvider(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return ConfigServiceV2StubSettings.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 ConfigServiceV2Settings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + } + + /** Builder for ConfigServiceV2Settings. */ + public static class Builder extends ClientSettings.Builder { + + protected Builder() throws IOException { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(ConfigServiceV2StubSettings.newBuilder(clientContext)); + } + + protected Builder(ConfigServiceV2Settings settings) { + super(settings.getStubSettings().toBuilder()); + } + + protected Builder(ConfigServiceV2StubSettings.Builder stubSettings) { + super(stubSettings); + } + + private static Builder createDefault() { + return new Builder(ConfigServiceV2StubSettings.newBuilder()); + } + + public ConfigServiceV2StubSettings.Builder getStubSettingsBuilder() { + return ((ConfigServiceV2StubSettings.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 listBuckets. */ + public PagedCallSettings.Builder< + ListBucketsRequest, ListBucketsResponse, ListBucketsPagedResponse> + listBucketsSettings() { + return getStubSettingsBuilder().listBucketsSettings(); + } + + /** Returns the builder for the settings used for calls to getBucket. */ + public UnaryCallSettings.Builder getBucketSettings() { + return getStubSettingsBuilder().getBucketSettings(); + } + + /** Returns the builder for the settings used for calls to updateBucket. */ + public UnaryCallSettings.Builder updateBucketSettings() { + return getStubSettingsBuilder().updateBucketSettings(); + } + + /** Returns the builder for the settings used for calls to listSinks. */ + public PagedCallSettings.Builder + listSinksSettings() { + return getStubSettingsBuilder().listSinksSettings(); + } + + /** Returns the builder for the settings used for calls to getSink. */ + public UnaryCallSettings.Builder getSinkSettings() { + return getStubSettingsBuilder().getSinkSettings(); + } + + /** Returns the builder for the settings used for calls to createSink. */ + public UnaryCallSettings.Builder createSinkSettings() { + return getStubSettingsBuilder().createSinkSettings(); + } + + /** Returns the builder for the settings used for calls to updateSink. */ + public UnaryCallSettings.Builder updateSinkSettings() { + return getStubSettingsBuilder().updateSinkSettings(); + } + + /** Returns the builder for the settings used for calls to deleteSink. */ + public UnaryCallSettings.Builder deleteSinkSettings() { + return getStubSettingsBuilder().deleteSinkSettings(); + } + + /** Returns the builder for the settings used for calls to listExclusions. */ + public PagedCallSettings.Builder< + ListExclusionsRequest, ListExclusionsResponse, ListExclusionsPagedResponse> + listExclusionsSettings() { + return getStubSettingsBuilder().listExclusionsSettings(); + } + + /** Returns the builder for the settings used for calls to getExclusion. */ + public UnaryCallSettings.Builder getExclusionSettings() { + return getStubSettingsBuilder().getExclusionSettings(); + } + + /** Returns the builder for the settings used for calls to createExclusion. */ + public UnaryCallSettings.Builder + createExclusionSettings() { + return getStubSettingsBuilder().createExclusionSettings(); + } + + /** Returns the builder for the settings used for calls to updateExclusion. */ + public UnaryCallSettings.Builder + updateExclusionSettings() { + return getStubSettingsBuilder().updateExclusionSettings(); + } + + /** Returns the builder for the settings used for calls to deleteExclusion. */ + public UnaryCallSettings.Builder deleteExclusionSettings() { + return getStubSettingsBuilder().deleteExclusionSettings(); + } + + /** Returns the builder for the settings used for calls to getCmekSettings. */ + public UnaryCallSettings.Builder + getCmekSettingsSettings() { + return getStubSettingsBuilder().getCmekSettingsSettings(); + } + + /** Returns the builder for the settings used for calls to updateCmekSettings. */ + public UnaryCallSettings.Builder + updateCmekSettingsSettings() { + return getStubSettingsBuilder().updateCmekSettingsSettings(); + } + + @Override + public ConfigServiceV2Settings build() throws IOException { + return new ConfigServiceV2Settings(this); + } + } +} diff --git a/test/integration/goldens/logging/ConfigServiceV2Stub.java b/test/integration/goldens/logging/ConfigServiceV2Stub.java new file mode 100644 index 0000000000..d49d790ea8 --- /dev/null +++ b/test/integration/goldens/logging/ConfigServiceV2Stub.java @@ -0,0 +1,134 @@ +/* + * 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.logging.v2.stub; + +import static com.google.logging.v2.ConfigServiceV2Client.ListBucketsPagedResponse; +import static com.google.logging.v2.ConfigServiceV2Client.ListExclusionsPagedResponse; +import static com.google.logging.v2.ConfigServiceV2Client.ListSinksPagedResponse; + +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.logging.v2.CmekSettings; +import com.google.logging.v2.CreateExclusionRequest; +import com.google.logging.v2.CreateSinkRequest; +import com.google.logging.v2.DeleteExclusionRequest; +import com.google.logging.v2.DeleteSinkRequest; +import com.google.logging.v2.GetBucketRequest; +import com.google.logging.v2.GetCmekSettingsRequest; +import com.google.logging.v2.GetExclusionRequest; +import com.google.logging.v2.GetSinkRequest; +import com.google.logging.v2.ListBucketsRequest; +import com.google.logging.v2.ListBucketsResponse; +import com.google.logging.v2.ListExclusionsRequest; +import com.google.logging.v2.ListExclusionsResponse; +import com.google.logging.v2.ListSinksRequest; +import com.google.logging.v2.ListSinksResponse; +import com.google.logging.v2.LogBucket; +import com.google.logging.v2.LogExclusion; +import com.google.logging.v2.LogSink; +import com.google.logging.v2.UpdateBucketRequest; +import com.google.logging.v2.UpdateCmekSettingsRequest; +import com.google.logging.v2.UpdateExclusionRequest; +import com.google.logging.v2.UpdateSinkRequest; +import com.google.protobuf.Empty; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Base stub class for the ConfigServiceV2 service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator") +public abstract class ConfigServiceV2Stub implements BackgroundResource { + + public UnaryCallable listBucketsPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listBucketsPagedCallable()"); + } + + public UnaryCallable listBucketsCallable() { + throw new UnsupportedOperationException("Not implemented: listBucketsCallable()"); + } + + public UnaryCallable getBucketCallable() { + throw new UnsupportedOperationException("Not implemented: getBucketCallable()"); + } + + public UnaryCallable updateBucketCallable() { + throw new UnsupportedOperationException("Not implemented: updateBucketCallable()"); + } + + public UnaryCallable listSinksPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listSinksPagedCallable()"); + } + + public UnaryCallable listSinksCallable() { + throw new UnsupportedOperationException("Not implemented: listSinksCallable()"); + } + + public UnaryCallable getSinkCallable() { + throw new UnsupportedOperationException("Not implemented: getSinkCallable()"); + } + + public UnaryCallable createSinkCallable() { + throw new UnsupportedOperationException("Not implemented: createSinkCallable()"); + } + + public UnaryCallable updateSinkCallable() { + throw new UnsupportedOperationException("Not implemented: updateSinkCallable()"); + } + + public UnaryCallable deleteSinkCallable() { + throw new UnsupportedOperationException("Not implemented: deleteSinkCallable()"); + } + + public UnaryCallable + listExclusionsPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listExclusionsPagedCallable()"); + } + + public UnaryCallable listExclusionsCallable() { + throw new UnsupportedOperationException("Not implemented: listExclusionsCallable()"); + } + + public UnaryCallable getExclusionCallable() { + throw new UnsupportedOperationException("Not implemented: getExclusionCallable()"); + } + + public UnaryCallable createExclusionCallable() { + throw new UnsupportedOperationException("Not implemented: createExclusionCallable()"); + } + + public UnaryCallable updateExclusionCallable() { + throw new UnsupportedOperationException("Not implemented: updateExclusionCallable()"); + } + + public UnaryCallable deleteExclusionCallable() { + throw new UnsupportedOperationException("Not implemented: deleteExclusionCallable()"); + } + + public UnaryCallable getCmekSettingsCallable() { + throw new UnsupportedOperationException("Not implemented: getCmekSettingsCallable()"); + } + + public UnaryCallable updateCmekSettingsCallable() { + throw new UnsupportedOperationException("Not implemented: updateCmekSettingsCallable()"); + } + + @Override + public abstract void close(); +} diff --git a/test/integration/goldens/logging/ConfigServiceV2StubSettings.java b/test/integration/goldens/logging/ConfigServiceV2StubSettings.java new file mode 100644 index 0000000000..c51140e8fc --- /dev/null +++ b/test/integration/goldens/logging/ConfigServiceV2StubSettings.java @@ -0,0 +1,806 @@ +/* + * 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.logging.v2.stub; + +import static com.google.logging.v2.ConfigServiceV2Client.ListBucketsPagedResponse; +import static com.google.logging.v2.ConfigServiceV2Client.ListExclusionsPagedResponse; +import static com.google.logging.v2.ConfigServiceV2Client.ListSinksPagedResponse; + +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.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.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.CmekSettings; +import com.google.logging.v2.CreateExclusionRequest; +import com.google.logging.v2.CreateSinkRequest; +import com.google.logging.v2.DeleteExclusionRequest; +import com.google.logging.v2.DeleteSinkRequest; +import com.google.logging.v2.GetBucketRequest; +import com.google.logging.v2.GetCmekSettingsRequest; +import com.google.logging.v2.GetExclusionRequest; +import com.google.logging.v2.GetSinkRequest; +import com.google.logging.v2.ListBucketsRequest; +import com.google.logging.v2.ListBucketsResponse; +import com.google.logging.v2.ListExclusionsRequest; +import com.google.logging.v2.ListExclusionsResponse; +import com.google.logging.v2.ListSinksRequest; +import com.google.logging.v2.ListSinksResponse; +import com.google.logging.v2.LogBucket; +import com.google.logging.v2.LogExclusion; +import com.google.logging.v2.LogSink; +import com.google.logging.v2.UpdateBucketRequest; +import com.google.logging.v2.UpdateCmekSettingsRequest; +import com.google.logging.v2.UpdateExclusionRequest; +import com.google.logging.v2.UpdateSinkRequest; +import com.google.protobuf.Empty; +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 ConfigServiceV2Stub}. + * + *

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 listBuckets to 30 seconds: + */ +@BetaApi +@Generated("by gapic-generator-java") +public class ConfigServiceV2StubSettings 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") + .build(); + + private final PagedCallSettings + listBucketsSettings; + private final UnaryCallSettings getBucketSettings; + private final UnaryCallSettings updateBucketSettings; + private final PagedCallSettings + listSinksSettings; + private final UnaryCallSettings getSinkSettings; + private final UnaryCallSettings createSinkSettings; + private final UnaryCallSettings updateSinkSettings; + private final UnaryCallSettings deleteSinkSettings; + private final PagedCallSettings< + ListExclusionsRequest, ListExclusionsResponse, ListExclusionsPagedResponse> + listExclusionsSettings; + private final UnaryCallSettings getExclusionSettings; + private final UnaryCallSettings createExclusionSettings; + private final UnaryCallSettings updateExclusionSettings; + private final UnaryCallSettings deleteExclusionSettings; + private final UnaryCallSettings getCmekSettingsSettings; + private final UnaryCallSettings + updateCmekSettingsSettings; + + private static final PagedListDescriptor + LIST_BUCKETS_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListBucketsRequest injectToken(ListBucketsRequest payload, String token) { + return ListBucketsRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListBucketsRequest injectPageSize(ListBucketsRequest payload, int pageSize) { + return ListBucketsRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListBucketsRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListBucketsResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListBucketsResponse payload) { + return Objects.isNull(payload.getBucketsList()) + ? ImmutableList.of() + : payload.getBucketsList(); + } + }; + + private static final PagedListDescriptor + LIST_SINKS_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListSinksRequest injectToken(ListSinksRequest payload, String token) { + return ListSinksRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListSinksRequest injectPageSize(ListSinksRequest payload, int pageSize) { + return ListSinksRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListSinksRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListSinksResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListSinksResponse payload) { + return Objects.isNull(payload.getSinksList()) + ? ImmutableList.of() + : payload.getSinksList(); + } + }; + + private static final PagedListDescriptor< + ListExclusionsRequest, ListExclusionsResponse, LogExclusion> + LIST_EXCLUSIONS_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListExclusionsRequest injectToken(ListExclusionsRequest payload, String token) { + return ListExclusionsRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListExclusionsRequest injectPageSize( + ListExclusionsRequest payload, int pageSize) { + return ListExclusionsRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListExclusionsRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListExclusionsResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListExclusionsResponse payload) { + return Objects.isNull(payload.getExclusionsList()) + ? ImmutableList.of() + : payload.getExclusionsList(); + } + }; + + private static final PagedListResponseFactory< + ListBucketsRequest, ListBucketsResponse, ListBucketsPagedResponse> + LIST_BUCKETS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListBucketsRequest, ListBucketsResponse, ListBucketsPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListBucketsRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, LIST_BUCKETS_PAGE_STR_DESC, request, context); + return ListBucketsPagedResponse.createAsync(pageContext, futureResponse); + } + }; + + private static final PagedListResponseFactory< + ListSinksRequest, ListSinksResponse, ListSinksPagedResponse> + LIST_SINKS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListSinksRequest, ListSinksResponse, ListSinksPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListSinksRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, LIST_SINKS_PAGE_STR_DESC, request, context); + return ListSinksPagedResponse.createAsync(pageContext, futureResponse); + } + }; + + private static final PagedListResponseFactory< + ListExclusionsRequest, ListExclusionsResponse, ListExclusionsPagedResponse> + LIST_EXCLUSIONS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListExclusionsRequest, ListExclusionsResponse, ListExclusionsPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListExclusionsRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, LIST_EXCLUSIONS_PAGE_STR_DESC, request, context); + return ListExclusionsPagedResponse.createAsync(pageContext, futureResponse); + } + }; + + /** Returns the object with the settings used for calls to listBuckets. */ + public PagedCallSettings + listBucketsSettings() { + return listBucketsSettings; + } + + /** Returns the object with the settings used for calls to getBucket. */ + public UnaryCallSettings getBucketSettings() { + return getBucketSettings; + } + + /** Returns the object with the settings used for calls to updateBucket. */ + public UnaryCallSettings updateBucketSettings() { + return updateBucketSettings; + } + + /** Returns the object with the settings used for calls to listSinks. */ + public PagedCallSettings + listSinksSettings() { + return listSinksSettings; + } + + /** Returns the object with the settings used for calls to getSink. */ + public UnaryCallSettings getSinkSettings() { + return getSinkSettings; + } + + /** Returns the object with the settings used for calls to createSink. */ + public UnaryCallSettings createSinkSettings() { + return createSinkSettings; + } + + /** Returns the object with the settings used for calls to updateSink. */ + public UnaryCallSettings updateSinkSettings() { + return updateSinkSettings; + } + + /** Returns the object with the settings used for calls to deleteSink. */ + public UnaryCallSettings deleteSinkSettings() { + return deleteSinkSettings; + } + + /** Returns the object with the settings used for calls to listExclusions. */ + public PagedCallSettings< + ListExclusionsRequest, ListExclusionsResponse, ListExclusionsPagedResponse> + listExclusionsSettings() { + return listExclusionsSettings; + } + + /** Returns the object with the settings used for calls to getExclusion. */ + public UnaryCallSettings getExclusionSettings() { + return getExclusionSettings; + } + + /** Returns the object with the settings used for calls to createExclusion. */ + public UnaryCallSettings createExclusionSettings() { + return createExclusionSettings; + } + + /** Returns the object with the settings used for calls to updateExclusion. */ + public UnaryCallSettings updateExclusionSettings() { + return updateExclusionSettings; + } + + /** Returns the object with the settings used for calls to deleteExclusion. */ + public UnaryCallSettings deleteExclusionSettings() { + return deleteExclusionSettings; + } + + /** Returns the object with the settings used for calls to getCmekSettings. */ + public UnaryCallSettings getCmekSettingsSettings() { + return getCmekSettingsSettings; + } + + /** Returns the object with the settings used for calls to updateCmekSettings. */ + public UnaryCallSettings updateCmekSettingsSettings() { + return updateCmekSettingsSettings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public ConfigServiceV2Stub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(GrpcTransportChannel.getGrpcTransportName())) { + return GrpcConfigServiceV2Stub.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(ConfigServiceV2StubSettings.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 ConfigServiceV2StubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + + listBucketsSettings = settingsBuilder.listBucketsSettings().build(); + getBucketSettings = settingsBuilder.getBucketSettings().build(); + updateBucketSettings = settingsBuilder.updateBucketSettings().build(); + listSinksSettings = settingsBuilder.listSinksSettings().build(); + getSinkSettings = settingsBuilder.getSinkSettings().build(); + createSinkSettings = settingsBuilder.createSinkSettings().build(); + updateSinkSettings = settingsBuilder.updateSinkSettings().build(); + deleteSinkSettings = settingsBuilder.deleteSinkSettings().build(); + listExclusionsSettings = settingsBuilder.listExclusionsSettings().build(); + getExclusionSettings = settingsBuilder.getExclusionSettings().build(); + createExclusionSettings = settingsBuilder.createExclusionSettings().build(); + updateExclusionSettings = settingsBuilder.updateExclusionSettings().build(); + deleteExclusionSettings = settingsBuilder.deleteExclusionSettings().build(); + getCmekSettingsSettings = settingsBuilder.getCmekSettingsSettings().build(); + updateCmekSettingsSettings = settingsBuilder.updateCmekSettingsSettings().build(); + } + + /** Builder for ConfigServiceV2StubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final PagedCallSettings.Builder< + ListBucketsRequest, ListBucketsResponse, ListBucketsPagedResponse> + listBucketsSettings; + private final UnaryCallSettings.Builder getBucketSettings; + private final UnaryCallSettings.Builder updateBucketSettings; + private final PagedCallSettings.Builder< + ListSinksRequest, ListSinksResponse, ListSinksPagedResponse> + listSinksSettings; + private final UnaryCallSettings.Builder getSinkSettings; + private final UnaryCallSettings.Builder createSinkSettings; + private final UnaryCallSettings.Builder updateSinkSettings; + private final UnaryCallSettings.Builder deleteSinkSettings; + private final PagedCallSettings.Builder< + ListExclusionsRequest, ListExclusionsResponse, ListExclusionsPagedResponse> + listExclusionsSettings; + private final UnaryCallSettings.Builder getExclusionSettings; + private final UnaryCallSettings.Builder + createExclusionSettings; + private final UnaryCallSettings.Builder + updateExclusionSettings; + private final UnaryCallSettings.Builder deleteExclusionSettings; + private final UnaryCallSettings.Builder + getCmekSettingsSettings; + private final UnaryCallSettings.Builder + updateCmekSettingsSettings; + private static final ImmutableMap> + RETRYABLE_CODE_DEFINITIONS; + + static { + ImmutableMap.Builder> definitions = + ImmutableMap.builder(); + definitions.put("no_retry_codes", ImmutableSet.copyOf(Lists.newArrayList())); + definitions.put( + "retry_policy_3_codes", + ImmutableSet.copyOf( + Lists.newArrayList( + StatusCode.Code.DEADLINE_EXCEEDED, + StatusCode.Code.INTERNAL, + StatusCode.Code.UNAVAILABLE))); + definitions.put( + "no_retry_4_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().setRpcTimeoutMultiplier(1.0).build(); + definitions.put("no_retry_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_3_params", settings); + settings = + RetrySettings.newBuilder() + .setInitialRpcTimeout(Duration.ofMillis(120000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(120000L)) + .setTotalTimeout(Duration.ofMillis(120000L)) + .build(); + definitions.put("no_retry_4_params", settings); + RETRY_PARAM_DEFINITIONS = definitions.build(); + } + + protected Builder() { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(clientContext); + + listBucketsSettings = PagedCallSettings.newBuilder(LIST_BUCKETS_PAGE_STR_FACT); + getBucketSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + updateBucketSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + listSinksSettings = PagedCallSettings.newBuilder(LIST_SINKS_PAGE_STR_FACT); + getSinkSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + createSinkSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + updateSinkSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + deleteSinkSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + listExclusionsSettings = PagedCallSettings.newBuilder(LIST_EXCLUSIONS_PAGE_STR_FACT); + getExclusionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + createExclusionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + updateExclusionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + deleteExclusionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + getCmekSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + updateCmekSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + listBucketsSettings, + getBucketSettings, + updateBucketSettings, + listSinksSettings, + getSinkSettings, + createSinkSettings, + updateSinkSettings, + deleteSinkSettings, + listExclusionsSettings, + getExclusionSettings, + createExclusionSettings, + updateExclusionSettings, + deleteExclusionSettings, + getCmekSettingsSettings, + updateCmekSettingsSettings); + initDefaults(this); + } + + protected Builder(ConfigServiceV2StubSettings settings) { + super(settings); + + listBucketsSettings = settings.listBucketsSettings.toBuilder(); + getBucketSettings = settings.getBucketSettings.toBuilder(); + updateBucketSettings = settings.updateBucketSettings.toBuilder(); + listSinksSettings = settings.listSinksSettings.toBuilder(); + getSinkSettings = settings.getSinkSettings.toBuilder(); + createSinkSettings = settings.createSinkSettings.toBuilder(); + updateSinkSettings = settings.updateSinkSettings.toBuilder(); + deleteSinkSettings = settings.deleteSinkSettings.toBuilder(); + listExclusionsSettings = settings.listExclusionsSettings.toBuilder(); + getExclusionSettings = settings.getExclusionSettings.toBuilder(); + createExclusionSettings = settings.createExclusionSettings.toBuilder(); + updateExclusionSettings = settings.updateExclusionSettings.toBuilder(); + deleteExclusionSettings = settings.deleteExclusionSettings.toBuilder(); + getCmekSettingsSettings = settings.getCmekSettingsSettings.toBuilder(); + updateCmekSettingsSettings = settings.updateCmekSettingsSettings.toBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + listBucketsSettings, + getBucketSettings, + updateBucketSettings, + listSinksSettings, + getSinkSettings, + createSinkSettings, + updateSinkSettings, + deleteSinkSettings, + listExclusionsSettings, + getExclusionSettings, + createExclusionSettings, + updateExclusionSettings, + deleteExclusionSettings, + getCmekSettingsSettings, + updateCmekSettingsSettings); + } + + 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 + .listBucketsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .getBucketSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .updateBucketSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .listSinksSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_3_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_3_params")); + + builder + .getSinkSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_3_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_3_params")); + + builder + .createSinkSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_4_params")); + + builder + .updateSinkSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_3_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_3_params")); + + builder + .deleteSinkSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_3_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_3_params")); + + builder + .listExclusionsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_3_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_3_params")); + + builder + .getExclusionSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_3_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_3_params")); + + builder + .createExclusionSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_4_params")); + + builder + .updateExclusionSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_4_params")); + + builder + .deleteExclusionSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_3_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_3_params")); + + builder + .getCmekSettingsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .updateCmekSettingsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_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 listBuckets. */ + public PagedCallSettings.Builder< + ListBucketsRequest, ListBucketsResponse, ListBucketsPagedResponse> + listBucketsSettings() { + return listBucketsSettings; + } + + /** Returns the builder for the settings used for calls to getBucket. */ + public UnaryCallSettings.Builder getBucketSettings() { + return getBucketSettings; + } + + /** Returns the builder for the settings used for calls to updateBucket. */ + public UnaryCallSettings.Builder updateBucketSettings() { + return updateBucketSettings; + } + + /** Returns the builder for the settings used for calls to listSinks. */ + public PagedCallSettings.Builder + listSinksSettings() { + return listSinksSettings; + } + + /** Returns the builder for the settings used for calls to getSink. */ + public UnaryCallSettings.Builder getSinkSettings() { + return getSinkSettings; + } + + /** Returns the builder for the settings used for calls to createSink. */ + public UnaryCallSettings.Builder createSinkSettings() { + return createSinkSettings; + } + + /** Returns the builder for the settings used for calls to updateSink. */ + public UnaryCallSettings.Builder updateSinkSettings() { + return updateSinkSettings; + } + + /** Returns the builder for the settings used for calls to deleteSink. */ + public UnaryCallSettings.Builder deleteSinkSettings() { + return deleteSinkSettings; + } + + /** Returns the builder for the settings used for calls to listExclusions. */ + public PagedCallSettings.Builder< + ListExclusionsRequest, ListExclusionsResponse, ListExclusionsPagedResponse> + listExclusionsSettings() { + return listExclusionsSettings; + } + + /** Returns the builder for the settings used for calls to getExclusion. */ + public UnaryCallSettings.Builder getExclusionSettings() { + return getExclusionSettings; + } + + /** Returns the builder for the settings used for calls to createExclusion. */ + public UnaryCallSettings.Builder + createExclusionSettings() { + return createExclusionSettings; + } + + /** Returns the builder for the settings used for calls to updateExclusion. */ + public UnaryCallSettings.Builder + updateExclusionSettings() { + return updateExclusionSettings; + } + + /** Returns the builder for the settings used for calls to deleteExclusion. */ + public UnaryCallSettings.Builder deleteExclusionSettings() { + return deleteExclusionSettings; + } + + /** Returns the builder for the settings used for calls to getCmekSettings. */ + public UnaryCallSettings.Builder + getCmekSettingsSettings() { + return getCmekSettingsSettings; + } + + /** Returns the builder for the settings used for calls to updateCmekSettings. */ + public UnaryCallSettings.Builder + updateCmekSettingsSettings() { + return updateCmekSettingsSettings; + } + + @Override + public ConfigServiceV2StubSettings build() throws IOException { + return new ConfigServiceV2StubSettings(this); + } + } +} diff --git a/test/integration/goldens/logging/FolderLocationName.java b/test/integration/goldens/logging/FolderLocationName.java new file mode 100644 index 0000000000..526f0d1b62 --- /dev/null +++ b/test/integration/goldens/logging/FolderLocationName.java @@ -0,0 +1,186 @@ +/* + * 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.logging.v2; + +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 FolderLocationName implements ResourceName { + private static final PathTemplate FOLDER_LOCATION = + PathTemplate.createWithoutUrlEncoding("folders/{folder}/locations/{location}"); + private volatile Map fieldValuesMap; + private final String folder; + private final String location; + + private FolderLocationName(Builder builder) { + folder = Preconditions.checkNotNull(builder.getFolder()); + location = Preconditions.checkNotNull(builder.getLocation()); + } + + public String getFolder() { + return folder; + } + + public String getLocation() { + return location; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static FolderLocationName of(String folder, String location) { + return newBuilder().setFolder(folder).setLocation(location).build(); + } + + public static String format(String folder, String location) { + return newBuilder().setFolder(folder).setLocation(location).build().toString(); + } + + public static FolderLocationName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + FOLDER_LOCATION.validatedMatch( + formattedString, "FolderLocationName.parse: formattedString not in valid format"); + return of(matchMap.get("folder"), matchMap.get("location")); + } + + 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 (FolderLocationName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return FOLDER_LOCATION.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(folder)) { + fieldMapBuilder.put("folder", folder); + } + if (!Objects.isNull(location)) { + fieldMapBuilder.put("location", location); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return FOLDER_LOCATION.instantiate("folder", folder); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + FolderLocationName that = ((FolderLocationName) o); + return Objects.equals(this.folder, that.folder) + && Objects.equals(this.location, that.location); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(folder); + h *= 1000003; + h ^= Objects.hashCode(location); + return h; + } + + /** Builder for folders/{folder}/locations/{location}. */ + public static class Builder { + private String folder; + private String location; + + private Builder() {} + + public String getFolder() { + return folder; + } + + public String getLocation() { + return location; + } + + public Builder setFolder(String folder) { + this.folder = folder; + return this; + } + + public Builder setLocation(String location) { + this.location = location; + return this; + } + + private Builder(FolderLocationName folderLocationName) { + folder = folderLocationName.folder; + location = folderLocationName.location; + } + + public FolderLocationName build() { + return new FolderLocationName(this); + } + } +} diff --git a/test/integration/goldens/logging/FolderName.java b/test/integration/goldens/logging/FolderName.java new file mode 100644 index 0000000000..8f0c022439 --- /dev/null +++ b/test/integration/goldens/logging/FolderName.java @@ -0,0 +1,163 @@ +/* + * 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.logging.v2; + +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 FolderName implements ResourceName { + private static final PathTemplate FOLDER = + PathTemplate.createWithoutUrlEncoding("folders/{folder}"); + private volatile Map fieldValuesMap; + private final String folder; + + private FolderName(Builder builder) { + folder = Preconditions.checkNotNull(builder.getFolder()); + } + + public String getFolder() { + return folder; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static FolderName of(String folder) { + return newBuilder().setFolder(folder).build(); + } + + public static String format(String folder) { + return newBuilder().setFolder(folder).build().toString(); + } + + public static FolderName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + FOLDER.validatedMatch( + formattedString, "FolderName.parse: formattedString not in valid format"); + return of(matchMap.get("folder")); + } + + 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 (FolderName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return FOLDER.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(folder)) { + fieldMapBuilder.put("folder", folder); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return FOLDER.instantiate("folder", folder); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + FolderName that = ((FolderName) o); + return Objects.equals(this.folder, that.folder); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(folder); + return h; + } + + /** Builder for folders/{folder}. */ + public static class Builder { + private String folder; + + private Builder() {} + + public String getFolder() { + return folder; + } + + public Builder setFolder(String folder) { + this.folder = folder; + return this; + } + + private Builder(FolderName folderName) { + folder = folderName.folder; + } + + public FolderName build() { + return new FolderName(this); + } + } +} diff --git a/test/integration/goldens/logging/GrpcConfigServiceV2CallableFactory.java b/test/integration/goldens/logging/GrpcConfigServiceV2CallableFactory.java new file mode 100644 index 0000000000..98b2b97776 --- /dev/null +++ b/test/integration/goldens/logging/GrpcConfigServiceV2CallableFactory.java @@ -0,0 +1,113 @@ +/* + * 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.logging.v2.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 ConfigServiceV2 service API. + * + *

This class is for advanced usage. + */ +@Generated("by gapic-generator") +public class GrpcConfigServiceV2CallableFactory 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/test/integration/goldens/logging/GrpcConfigServiceV2Stub.java b/test/integration/goldens/logging/GrpcConfigServiceV2Stub.java new file mode 100644 index 0000000000..40914d3e93 --- /dev/null +++ b/test/integration/goldens/logging/GrpcConfigServiceV2Stub.java @@ -0,0 +1,627 @@ +/* + * 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.logging.v2.stub; + +import static com.google.logging.v2.ConfigServiceV2Client.ListBucketsPagedResponse; +import static com.google.logging.v2.ConfigServiceV2Client.ListExclusionsPagedResponse; +import static com.google.logging.v2.ConfigServiceV2Client.ListSinksPagedResponse; + +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.ClientContext; +import com.google.api.gax.rpc.RequestParamsExtractor; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.collect.ImmutableMap; +import com.google.logging.v2.CmekSettings; +import com.google.logging.v2.CreateExclusionRequest; +import com.google.logging.v2.CreateSinkRequest; +import com.google.logging.v2.DeleteExclusionRequest; +import com.google.logging.v2.DeleteSinkRequest; +import com.google.logging.v2.GetBucketRequest; +import com.google.logging.v2.GetCmekSettingsRequest; +import com.google.logging.v2.GetExclusionRequest; +import com.google.logging.v2.GetSinkRequest; +import com.google.logging.v2.ListBucketsRequest; +import com.google.logging.v2.ListBucketsResponse; +import com.google.logging.v2.ListExclusionsRequest; +import com.google.logging.v2.ListExclusionsResponse; +import com.google.logging.v2.ListSinksRequest; +import com.google.logging.v2.ListSinksResponse; +import com.google.logging.v2.LogBucket; +import com.google.logging.v2.LogExclusion; +import com.google.logging.v2.LogSink; +import com.google.logging.v2.UpdateBucketRequest; +import com.google.logging.v2.UpdateCmekSettingsRequest; +import com.google.logging.v2.UpdateExclusionRequest; +import com.google.logging.v2.UpdateSinkRequest; +import com.google.longrunning.stub.GrpcOperationsStub; +import com.google.protobuf.Empty; +import io.grpc.MethodDescriptor; +import io.grpc.protobuf.ProtoUtils; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * gRPC stub implementation for the ConfigServiceV2 service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public class GrpcConfigServiceV2Stub extends ConfigServiceV2Stub { + private static final MethodDescriptor + listBucketsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/ListBuckets") + .setRequestMarshaller(ProtoUtils.marshaller(ListBucketsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ListBucketsResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor getBucketMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/GetBucket") + .setRequestMarshaller(ProtoUtils.marshaller(GetBucketRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogBucket.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + updateBucketMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/UpdateBucket") + .setRequestMarshaller(ProtoUtils.marshaller(UpdateBucketRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogBucket.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + listSinksMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/ListSinks") + .setRequestMarshaller(ProtoUtils.marshaller(ListSinksRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(ListSinksResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor getSinkMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/GetSink") + .setRequestMarshaller(ProtoUtils.marshaller(GetSinkRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogSink.getDefaultInstance())) + .build(); + + private static final MethodDescriptor createSinkMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/CreateSink") + .setRequestMarshaller(ProtoUtils.marshaller(CreateSinkRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogSink.getDefaultInstance())) + .build(); + + private static final MethodDescriptor updateSinkMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/UpdateSink") + .setRequestMarshaller(ProtoUtils.marshaller(UpdateSinkRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogSink.getDefaultInstance())) + .build(); + + private static final MethodDescriptor deleteSinkMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/DeleteSink") + .setRequestMarshaller(ProtoUtils.marshaller(DeleteSinkRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + listExclusionsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/ListExclusions") + .setRequestMarshaller( + ProtoUtils.marshaller(ListExclusionsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ListExclusionsResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + getExclusionMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/GetExclusion") + .setRequestMarshaller(ProtoUtils.marshaller(GetExclusionRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogExclusion.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + createExclusionMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/CreateExclusion") + .setRequestMarshaller( + ProtoUtils.marshaller(CreateExclusionRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogExclusion.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + updateExclusionMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/UpdateExclusion") + .setRequestMarshaller( + ProtoUtils.marshaller(UpdateExclusionRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogExclusion.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + deleteExclusionMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/DeleteExclusion") + .setRequestMarshaller( + ProtoUtils.marshaller(DeleteExclusionRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + getCmekSettingsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/GetCmekSettings") + .setRequestMarshaller( + ProtoUtils.marshaller(GetCmekSettingsRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(CmekSettings.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + updateCmekSettingsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.ConfigServiceV2/UpdateCmekSettings") + .setRequestMarshaller( + ProtoUtils.marshaller(UpdateCmekSettingsRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(CmekSettings.getDefaultInstance())) + .build(); + + private final UnaryCallable listBucketsCallable; + private final UnaryCallable + listBucketsPagedCallable; + private final UnaryCallable getBucketCallable; + private final UnaryCallable updateBucketCallable; + private final UnaryCallable listSinksCallable; + private final UnaryCallable listSinksPagedCallable; + private final UnaryCallable getSinkCallable; + private final UnaryCallable createSinkCallable; + private final UnaryCallable updateSinkCallable; + private final UnaryCallable deleteSinkCallable; + private final UnaryCallable listExclusionsCallable; + private final UnaryCallable + listExclusionsPagedCallable; + private final UnaryCallable getExclusionCallable; + private final UnaryCallable createExclusionCallable; + private final UnaryCallable updateExclusionCallable; + private final UnaryCallable deleteExclusionCallable; + private final UnaryCallable getCmekSettingsCallable; + private final UnaryCallable updateCmekSettingsCallable; + + private final BackgroundResource backgroundResources; + private final GrpcOperationsStub operationsStub; + private final GrpcStubCallableFactory callableFactory; + + public static final GrpcConfigServiceV2Stub create(ConfigServiceV2StubSettings settings) + throws IOException { + return new GrpcConfigServiceV2Stub(settings, ClientContext.create(settings)); + } + + public static final GrpcConfigServiceV2Stub create(ClientContext clientContext) + throws IOException { + return new GrpcConfigServiceV2Stub( + ConfigServiceV2StubSettings.newBuilder().build(), clientContext); + } + + public static final GrpcConfigServiceV2Stub create( + ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { + return new GrpcConfigServiceV2Stub( + ConfigServiceV2StubSettings.newBuilder().build(), clientContext, callableFactory); + } + + protected GrpcConfigServiceV2Stub( + ConfigServiceV2StubSettings settings, ClientContext clientContext) throws IOException { + this(settings, clientContext, new GrpcConfigServiceV2CallableFactory()); + } + + protected GrpcConfigServiceV2Stub( + ConfigServiceV2StubSettings settings, + ClientContext clientContext, + GrpcStubCallableFactory callableFactory) + throws IOException { + this.callableFactory = callableFactory; + this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); + + GrpcCallSettings listBucketsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listBucketsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListBucketsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getBucketTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getBucketMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetBucketRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings updateBucketTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(updateBucketMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(UpdateBucketRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings listSinksTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listSinksMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListSinksRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getSinkTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getSinkMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetSinkRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("sink_name", String.valueOf(request.getSinkName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings createSinkTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(createSinkMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(CreateSinkRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings updateSinkTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(updateSinkMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(UpdateSinkRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("sink_name", String.valueOf(request.getSinkName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings deleteSinkTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(deleteSinkMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(DeleteSinkRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("sink_name", String.valueOf(request.getSinkName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + listExclusionsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listExclusionsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListExclusionsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getExclusionTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getExclusionMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetExclusionRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings createExclusionTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(createExclusionMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(CreateExclusionRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings updateExclusionTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(updateExclusionMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(UpdateExclusionRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings deleteExclusionTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(deleteExclusionMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(DeleteExclusionRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getCmekSettingsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getCmekSettingsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetCmekSettingsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings updateCmekSettingsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(updateCmekSettingsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(UpdateCmekSettingsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + + this.listBucketsCallable = + callableFactory.createUnaryCallable( + listBucketsTransportSettings, settings.listBucketsSettings(), clientContext); + this.listBucketsPagedCallable = + callableFactory.createPagedCallable( + listBucketsTransportSettings, settings.listBucketsSettings(), clientContext); + this.getBucketCallable = + callableFactory.createUnaryCallable( + getBucketTransportSettings, settings.getBucketSettings(), clientContext); + this.updateBucketCallable = + callableFactory.createUnaryCallable( + updateBucketTransportSettings, settings.updateBucketSettings(), clientContext); + this.listSinksCallable = + callableFactory.createUnaryCallable( + listSinksTransportSettings, settings.listSinksSettings(), clientContext); + this.listSinksPagedCallable = + callableFactory.createPagedCallable( + listSinksTransportSettings, settings.listSinksSettings(), clientContext); + this.getSinkCallable = + callableFactory.createUnaryCallable( + getSinkTransportSettings, settings.getSinkSettings(), clientContext); + this.createSinkCallable = + callableFactory.createUnaryCallable( + createSinkTransportSettings, settings.createSinkSettings(), clientContext); + this.updateSinkCallable = + callableFactory.createUnaryCallable( + updateSinkTransportSettings, settings.updateSinkSettings(), clientContext); + this.deleteSinkCallable = + callableFactory.createUnaryCallable( + deleteSinkTransportSettings, settings.deleteSinkSettings(), clientContext); + this.listExclusionsCallable = + callableFactory.createUnaryCallable( + listExclusionsTransportSettings, settings.listExclusionsSettings(), clientContext); + this.listExclusionsPagedCallable = + callableFactory.createPagedCallable( + listExclusionsTransportSettings, settings.listExclusionsSettings(), clientContext); + this.getExclusionCallable = + callableFactory.createUnaryCallable( + getExclusionTransportSettings, settings.getExclusionSettings(), clientContext); + this.createExclusionCallable = + callableFactory.createUnaryCallable( + createExclusionTransportSettings, settings.createExclusionSettings(), clientContext); + this.updateExclusionCallable = + callableFactory.createUnaryCallable( + updateExclusionTransportSettings, settings.updateExclusionSettings(), clientContext); + this.deleteExclusionCallable = + callableFactory.createUnaryCallable( + deleteExclusionTransportSettings, settings.deleteExclusionSettings(), clientContext); + this.getCmekSettingsCallable = + callableFactory.createUnaryCallable( + getCmekSettingsTransportSettings, settings.getCmekSettingsSettings(), clientContext); + this.updateCmekSettingsCallable = + callableFactory.createUnaryCallable( + updateCmekSettingsTransportSettings, + settings.updateCmekSettingsSettings(), + clientContext); + + this.backgroundResources = + new BackgroundResourceAggregation(clientContext.getBackgroundResources()); + } + + public GrpcOperationsStub getOperationsStub() { + return operationsStub; + } + + public UnaryCallable listBucketsCallable() { + return listBucketsCallable; + } + + public UnaryCallable listBucketsPagedCallable() { + return listBucketsPagedCallable; + } + + public UnaryCallable getBucketCallable() { + return getBucketCallable; + } + + public UnaryCallable updateBucketCallable() { + return updateBucketCallable; + } + + public UnaryCallable listSinksCallable() { + return listSinksCallable; + } + + public UnaryCallable listSinksPagedCallable() { + return listSinksPagedCallable; + } + + public UnaryCallable getSinkCallable() { + return getSinkCallable; + } + + public UnaryCallable createSinkCallable() { + return createSinkCallable; + } + + public UnaryCallable updateSinkCallable() { + return updateSinkCallable; + } + + public UnaryCallable deleteSinkCallable() { + return deleteSinkCallable; + } + + public UnaryCallable listExclusionsCallable() { + return listExclusionsCallable; + } + + public UnaryCallable + listExclusionsPagedCallable() { + return listExclusionsPagedCallable; + } + + public UnaryCallable getExclusionCallable() { + return getExclusionCallable; + } + + public UnaryCallable createExclusionCallable() { + return createExclusionCallable; + } + + public UnaryCallable updateExclusionCallable() { + return updateExclusionCallable; + } + + public UnaryCallable deleteExclusionCallable() { + return deleteExclusionCallable; + } + + public UnaryCallable getCmekSettingsCallable() { + return getCmekSettingsCallable; + } + + public UnaryCallable updateCmekSettingsCallable() { + return updateCmekSettingsCallable; + } + + @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/test/integration/goldens/logging/GrpcLoggingServiceV2CallableFactory.java b/test/integration/goldens/logging/GrpcLoggingServiceV2CallableFactory.java new file mode 100644 index 0000000000..e28e2e738f --- /dev/null +++ b/test/integration/goldens/logging/GrpcLoggingServiceV2CallableFactory.java @@ -0,0 +1,113 @@ +/* + * 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.logging.v2.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 LoggingServiceV2 service API. + * + *

This class is for advanced usage. + */ +@Generated("by gapic-generator") +public class GrpcLoggingServiceV2CallableFactory 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/test/integration/goldens/logging/GrpcLoggingServiceV2Stub.java b/test/integration/goldens/logging/GrpcLoggingServiceV2Stub.java new file mode 100644 index 0000000000..fd4bc1d3a1 --- /dev/null +++ b/test/integration/goldens/logging/GrpcLoggingServiceV2Stub.java @@ -0,0 +1,310 @@ +/* + * 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.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.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.ClientContext; +import com.google.api.gax.rpc.RequestParamsExtractor; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.collect.ImmutableMap; +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.WriteLogEntriesRequest; +import com.google.logging.v2.WriteLogEntriesResponse; +import com.google.longrunning.stub.GrpcOperationsStub; +import com.google.protobuf.Empty; +import io.grpc.MethodDescriptor; +import io.grpc.protobuf.ProtoUtils; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * gRPC stub implementation for the LoggingServiceV2 service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public class GrpcLoggingServiceV2Stub extends LoggingServiceV2Stub { + private static final MethodDescriptor deleteLogMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.LoggingServiceV2/DeleteLog") + .setRequestMarshaller(ProtoUtils.marshaller(DeleteLogRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + writeLogEntriesMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.LoggingServiceV2/WriteLogEntries") + .setRequestMarshaller( + ProtoUtils.marshaller(WriteLogEntriesRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(WriteLogEntriesResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + listLogEntriesMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.LoggingServiceV2/ListLogEntries") + .setRequestMarshaller( + ProtoUtils.marshaller(ListLogEntriesRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ListLogEntriesResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> + listMonitoredResourceDescriptorsMethodDescriptor = + MethodDescriptor + . + newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName( + "google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors") + .setRequestMarshaller( + ProtoUtils.marshaller( + ListMonitoredResourceDescriptorsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller( + ListMonitoredResourceDescriptorsResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + listLogsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.LoggingServiceV2/ListLogs") + .setRequestMarshaller(ProtoUtils.marshaller(ListLogsRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(ListLogsResponse.getDefaultInstance())) + .build(); + + private final UnaryCallable deleteLogCallable; + private final UnaryCallable + writeLogEntriesCallable; + private final UnaryCallable listLogEntriesCallable; + private final UnaryCallable + listLogEntriesPagedCallable; + private final UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> + listMonitoredResourceDescriptorsCallable; + private final UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsPagedResponse> + listMonitoredResourceDescriptorsPagedCallable; + private final UnaryCallable listLogsCallable; + private final UnaryCallable listLogsPagedCallable; + + private final BackgroundResource backgroundResources; + private final GrpcOperationsStub operationsStub; + private final GrpcStubCallableFactory callableFactory; + + public static final GrpcLoggingServiceV2Stub create(LoggingServiceV2StubSettings settings) + throws IOException { + return new GrpcLoggingServiceV2Stub(settings, ClientContext.create(settings)); + } + + public static final GrpcLoggingServiceV2Stub create(ClientContext clientContext) + throws IOException { + return new GrpcLoggingServiceV2Stub( + LoggingServiceV2StubSettings.newBuilder().build(), clientContext); + } + + public static final GrpcLoggingServiceV2Stub create( + ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { + return new GrpcLoggingServiceV2Stub( + LoggingServiceV2StubSettings.newBuilder().build(), clientContext, callableFactory); + } + + protected GrpcLoggingServiceV2Stub( + LoggingServiceV2StubSettings settings, ClientContext clientContext) throws IOException { + this(settings, clientContext, new GrpcLoggingServiceV2CallableFactory()); + } + + protected GrpcLoggingServiceV2Stub( + LoggingServiceV2StubSettings settings, + ClientContext clientContext, + GrpcStubCallableFactory callableFactory) + throws IOException { + this.callableFactory = callableFactory; + this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); + + GrpcCallSettings deleteLogTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(deleteLogMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(DeleteLogRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("log_name", String.valueOf(request.getLogName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + writeLogEntriesTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(writeLogEntriesMethodDescriptor) + .build(); + GrpcCallSettings + listLogEntriesTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listLogEntriesMethodDescriptor) + .build(); + GrpcCallSettings< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> + listMonitoredResourceDescriptorsTransportSettings = + GrpcCallSettings + . + newBuilder() + .setMethodDescriptor(listMonitoredResourceDescriptorsMethodDescriptor) + .build(); + GrpcCallSettings listLogsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listLogsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListLogsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + + this.deleteLogCallable = + callableFactory.createUnaryCallable( + deleteLogTransportSettings, settings.deleteLogSettings(), clientContext); + this.writeLogEntriesCallable = + callableFactory.createUnaryCallable( + writeLogEntriesTransportSettings, settings.writeLogEntriesSettings(), clientContext); + this.listLogEntriesCallable = + callableFactory.createUnaryCallable( + listLogEntriesTransportSettings, settings.listLogEntriesSettings(), clientContext); + this.listLogEntriesPagedCallable = + callableFactory.createPagedCallable( + listLogEntriesTransportSettings, settings.listLogEntriesSettings(), clientContext); + this.listMonitoredResourceDescriptorsCallable = + callableFactory.createUnaryCallable( + listMonitoredResourceDescriptorsTransportSettings, + settings.listMonitoredResourceDescriptorsSettings(), + clientContext); + this.listMonitoredResourceDescriptorsPagedCallable = + callableFactory.createPagedCallable( + listMonitoredResourceDescriptorsTransportSettings, + settings.listMonitoredResourceDescriptorsSettings(), + clientContext); + this.listLogsCallable = + callableFactory.createUnaryCallable( + listLogsTransportSettings, settings.listLogsSettings(), clientContext); + this.listLogsPagedCallable = + callableFactory.createPagedCallable( + listLogsTransportSettings, settings.listLogsSettings(), clientContext); + + this.backgroundResources = + new BackgroundResourceAggregation(clientContext.getBackgroundResources()); + } + + public GrpcOperationsStub getOperationsStub() { + return operationsStub; + } + + public UnaryCallable deleteLogCallable() { + return deleteLogCallable; + } + + public UnaryCallable writeLogEntriesCallable() { + return writeLogEntriesCallable; + } + + public UnaryCallable listLogEntriesCallable() { + return listLogEntriesCallable; + } + + public UnaryCallable + listLogEntriesPagedCallable() { + return listLogEntriesPagedCallable; + } + + public UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> + listMonitoredResourceDescriptorsCallable() { + return listMonitoredResourceDescriptorsCallable; + } + + public UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsPagedResponse> + listMonitoredResourceDescriptorsPagedCallable() { + return listMonitoredResourceDescriptorsPagedCallable; + } + + public UnaryCallable listLogsCallable() { + return listLogsCallable; + } + + public UnaryCallable listLogsPagedCallable() { + return listLogsPagedCallable; + } + + @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/test/integration/goldens/logging/GrpcMetricsServiceV2CallableFactory.java b/test/integration/goldens/logging/GrpcMetricsServiceV2CallableFactory.java new file mode 100644 index 0000000000..f75129947e --- /dev/null +++ b/test/integration/goldens/logging/GrpcMetricsServiceV2CallableFactory.java @@ -0,0 +1,113 @@ +/* + * 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.logging.v2.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 MetricsServiceV2 service API. + * + *

This class is for advanced usage. + */ +@Generated("by gapic-generator") +public class GrpcMetricsServiceV2CallableFactory 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/test/integration/goldens/logging/GrpcMetricsServiceV2Stub.java b/test/integration/goldens/logging/GrpcMetricsServiceV2Stub.java new file mode 100644 index 0000000000..c0c882c2d0 --- /dev/null +++ b/test/integration/goldens/logging/GrpcMetricsServiceV2Stub.java @@ -0,0 +1,293 @@ +/* + * 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.logging.v2.stub; + +import static com.google.logging.v2.MetricsServiceV2Client.ListLogMetricsPagedResponse; + +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.ClientContext; +import com.google.api.gax.rpc.RequestParamsExtractor; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.collect.ImmutableMap; +import com.google.logging.v2.CreateLogMetricRequest; +import com.google.logging.v2.DeleteLogMetricRequest; +import com.google.logging.v2.GetLogMetricRequest; +import com.google.logging.v2.ListLogMetricsRequest; +import com.google.logging.v2.ListLogMetricsResponse; +import com.google.logging.v2.LogMetric; +import com.google.logging.v2.UpdateLogMetricRequest; +import com.google.longrunning.stub.GrpcOperationsStub; +import com.google.protobuf.Empty; +import io.grpc.MethodDescriptor; +import io.grpc.protobuf.ProtoUtils; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * gRPC stub implementation for the MetricsServiceV2 service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public class GrpcMetricsServiceV2Stub extends MetricsServiceV2Stub { + private static final MethodDescriptor + listLogMetricsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.MetricsServiceV2/ListLogMetrics") + .setRequestMarshaller( + ProtoUtils.marshaller(ListLogMetricsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ListLogMetricsResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + getLogMetricMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.MetricsServiceV2/GetLogMetric") + .setRequestMarshaller(ProtoUtils.marshaller(GetLogMetricRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogMetric.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + createLogMetricMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.MetricsServiceV2/CreateLogMetric") + .setRequestMarshaller( + ProtoUtils.marshaller(CreateLogMetricRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogMetric.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + updateLogMetricMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.MetricsServiceV2/UpdateLogMetric") + .setRequestMarshaller( + ProtoUtils.marshaller(UpdateLogMetricRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(LogMetric.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + deleteLogMetricMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.logging.v2.MetricsServiceV2/DeleteLogMetric") + .setRequestMarshaller( + ProtoUtils.marshaller(DeleteLogMetricRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private final UnaryCallable listLogMetricsCallable; + private final UnaryCallable + listLogMetricsPagedCallable; + private final UnaryCallable getLogMetricCallable; + private final UnaryCallable createLogMetricCallable; + private final UnaryCallable updateLogMetricCallable; + private final UnaryCallable deleteLogMetricCallable; + + private final BackgroundResource backgroundResources; + private final GrpcOperationsStub operationsStub; + private final GrpcStubCallableFactory callableFactory; + + public static final GrpcMetricsServiceV2Stub create(MetricsServiceV2StubSettings settings) + throws IOException { + return new GrpcMetricsServiceV2Stub(settings, ClientContext.create(settings)); + } + + public static final GrpcMetricsServiceV2Stub create(ClientContext clientContext) + throws IOException { + return new GrpcMetricsServiceV2Stub( + MetricsServiceV2StubSettings.newBuilder().build(), clientContext); + } + + public static final GrpcMetricsServiceV2Stub create( + ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { + return new GrpcMetricsServiceV2Stub( + MetricsServiceV2StubSettings.newBuilder().build(), clientContext, callableFactory); + } + + protected GrpcMetricsServiceV2Stub( + MetricsServiceV2StubSettings settings, ClientContext clientContext) throws IOException { + this(settings, clientContext, new GrpcMetricsServiceV2CallableFactory()); + } + + protected GrpcMetricsServiceV2Stub( + MetricsServiceV2StubSettings settings, + ClientContext clientContext, + GrpcStubCallableFactory callableFactory) + throws IOException { + this.callableFactory = callableFactory; + this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); + + GrpcCallSettings + listLogMetricsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listLogMetricsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListLogMetricsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getLogMetricTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getLogMetricMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetLogMetricRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("metric_name", String.valueOf(request.getMetricName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings createLogMetricTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(createLogMetricMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(CreateLogMetricRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings updateLogMetricTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(updateLogMetricMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(UpdateLogMetricRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("metric_name", String.valueOf(request.getMetricName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings deleteLogMetricTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(deleteLogMetricMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(DeleteLogMetricRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("metric_name", String.valueOf(request.getMetricName())); + return params.build(); + } + }) + .build(); + + this.listLogMetricsCallable = + callableFactory.createUnaryCallable( + listLogMetricsTransportSettings, settings.listLogMetricsSettings(), clientContext); + this.listLogMetricsPagedCallable = + callableFactory.createPagedCallable( + listLogMetricsTransportSettings, settings.listLogMetricsSettings(), clientContext); + this.getLogMetricCallable = + callableFactory.createUnaryCallable( + getLogMetricTransportSettings, settings.getLogMetricSettings(), clientContext); + this.createLogMetricCallable = + callableFactory.createUnaryCallable( + createLogMetricTransportSettings, settings.createLogMetricSettings(), clientContext); + this.updateLogMetricCallable = + callableFactory.createUnaryCallable( + updateLogMetricTransportSettings, settings.updateLogMetricSettings(), clientContext); + this.deleteLogMetricCallable = + callableFactory.createUnaryCallable( + deleteLogMetricTransportSettings, settings.deleteLogMetricSettings(), clientContext); + + this.backgroundResources = + new BackgroundResourceAggregation(clientContext.getBackgroundResources()); + } + + public GrpcOperationsStub getOperationsStub() { + return operationsStub; + } + + public UnaryCallable listLogMetricsCallable() { + return listLogMetricsCallable; + } + + public UnaryCallable + listLogMetricsPagedCallable() { + return listLogMetricsPagedCallable; + } + + public UnaryCallable getLogMetricCallable() { + return getLogMetricCallable; + } + + public UnaryCallable createLogMetricCallable() { + return createLogMetricCallable; + } + + public UnaryCallable updateLogMetricCallable() { + return updateLogMetricCallable; + } + + public UnaryCallable deleteLogMetricCallable() { + return deleteLogMetricCallable; + } + + @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/test/integration/goldens/logging/LocationName.java b/test/integration/goldens/logging/LocationName.java new file mode 100644 index 0000000000..9074b6586d --- /dev/null +++ b/test/integration/goldens/logging/LocationName.java @@ -0,0 +1,186 @@ +/* + * 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.logging.v2; + +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 LocationName implements ResourceName { + private static final PathTemplate PROJECT_LOCATION = + PathTemplate.createWithoutUrlEncoding("projects/{project}/locations/{location}"); + private volatile Map fieldValuesMap; + private final String project; + private final String location; + + private LocationName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + location = Preconditions.checkNotNull(builder.getLocation()); + } + + public String getProject() { + return project; + } + + public String getLocation() { + return location; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static LocationName of(String project, String location) { + return newBuilder().setProject(project).setLocation(location).build(); + } + + public static String format(String project, String location) { + return newBuilder().setProject(project).setLocation(location).build().toString(); + } + + public static LocationName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + PROJECT_LOCATION.validatedMatch( + formattedString, "LocationName.parse: formattedString not in valid format"); + return of(matchMap.get("project"), matchMap.get("location")); + } + + 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 (LocationName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_LOCATION.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(project)) { + fieldMapBuilder.put("project", project); + } + if (!Objects.isNull(location)) { + fieldMapBuilder.put("location", location); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return PROJECT_LOCATION.instantiate("project", project); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + LocationName that = ((LocationName) o); + return Objects.equals(this.project, that.project) + && Objects.equals(this.location, that.location); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(location); + return h; + } + + /** Builder for projects/{project}/locations/{location}. */ + public static class Builder { + private String project; + private String location; + + private Builder() {} + + public String getProject() { + return project; + } + + public String getLocation() { + return location; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setLocation(String location) { + this.location = location; + return this; + } + + private Builder(LocationName locationName) { + project = locationName.project; + location = locationName.location; + } + + public LocationName build() { + return new LocationName(this); + } + } +} diff --git a/test/integration/goldens/logging/LogBucketName.java b/test/integration/goldens/logging/LogBucketName.java new file mode 100644 index 0000000000..cb94fab601 --- /dev/null +++ b/test/integration/goldens/logging/LogBucketName.java @@ -0,0 +1,540 @@ +/* + * 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.logging.v2; + +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 LogBucketName implements ResourceName { + private static final PathTemplate PROJECT_LOCATION_BUCKET = + PathTemplate.createWithoutUrlEncoding( + "projects/{project}/locations/{location}/buckets/{bucket}"); + private static final PathTemplate ORGANIZATION_LOCATION_BUCKET = + PathTemplate.createWithoutUrlEncoding( + "organizations/{organization}/locations/{location}/buckets/{bucket}"); + private static final PathTemplate FOLDER_LOCATION_BUCKET = + PathTemplate.createWithoutUrlEncoding( + "folders/{folder}/locations/{location}/buckets/{bucket}"); + private static final PathTemplate BILLING_ACCOUNT_LOCATION_BUCKET = + PathTemplate.createWithoutUrlEncoding( + "billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}"); + private volatile Map fieldValuesMap; + private PathTemplate pathTemplate; + private String fixedValue; + private final String project; + private final String location; + private final String bucket; + private final String organization; + private final String folder; + private final String billingAccount; + + private LogBucketName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + location = Preconditions.checkNotNull(builder.getLocation()); + bucket = Preconditions.checkNotNull(builder.getBucket()); + organization = null; + folder = null; + billingAccount = null; + pathTemplate = PROJECT_LOCATION_BUCKET; + } + + private LogBucketName(OrganizationLocationBucketBuilder builder) { + organization = Preconditions.checkNotNull(builder.getOrganization()); + location = Preconditions.checkNotNull(builder.getLocation()); + bucket = Preconditions.checkNotNull(builder.getBucket()); + project = null; + folder = null; + billingAccount = null; + pathTemplate = ORGANIZATION_LOCATION_BUCKET; + } + + private LogBucketName(FolderLocationBucketBuilder builder) { + folder = Preconditions.checkNotNull(builder.getFolder()); + location = Preconditions.checkNotNull(builder.getLocation()); + bucket = Preconditions.checkNotNull(builder.getBucket()); + project = null; + organization = null; + billingAccount = null; + pathTemplate = FOLDER_LOCATION_BUCKET; + } + + private LogBucketName(BillingAccountLocationBucketBuilder builder) { + billingAccount = Preconditions.checkNotNull(builder.getBillingAccount()); + location = Preconditions.checkNotNull(builder.getLocation()); + bucket = Preconditions.checkNotNull(builder.getBucket()); + project = null; + organization = null; + folder = null; + pathTemplate = BILLING_ACCOUNT_LOCATION_BUCKET; + } + + public String getProject() { + return project; + } + + public String getLocation() { + return location; + } + + public String getBucket() { + return bucket; + } + + public String getOrganization() { + return organization; + } + + public String getFolder() { + return folder; + } + + public String getBillingAccount() { + return billingAccount; + } + + 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 newProjectLocationBucketBuilder() { + return new Builder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static OrganizationLocationBucketBuilder newOrganizationLocationBucketBuilder() { + return new OrganizationLocationBucketBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static FolderLocationBucketBuilder newFolderLocationBucketBuilder() { + return new FolderLocationBucketBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static BillingAccountLocationBucketBuilder newBillingAccountLocationBucketBuilder() { + return new BillingAccountLocationBucketBuilder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static LogBucketName of(String project, String location, String bucket) { + return newBuilder().setProject(project).setLocation(location).setBucket(bucket).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogBucketName ofProjectLocationBucketName( + String project, String location, String bucket) { + return newBuilder().setProject(project).setLocation(location).setBucket(bucket).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogBucketName ofOrganizationLocationBucketName( + String organization, String location, String bucket) { + return newOrganizationLocationBucketBuilder() + .setOrganization(organization) + .setLocation(location) + .setBucket(bucket) + .build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogBucketName ofFolderLocationBucketName( + String folder, String location, String bucket) { + return newFolderLocationBucketBuilder() + .setFolder(folder) + .setLocation(location) + .setBucket(bucket) + .build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogBucketName ofBillingAccountLocationBucketName( + String billingAccount, String location, String bucket) { + return newBillingAccountLocationBucketBuilder() + .setBillingAccount(billingAccount) + .setLocation(location) + .setBucket(bucket) + .build(); + } + + public static String format(String project, String location, String bucket) { + return newBuilder() + .setProject(project) + .setLocation(location) + .setBucket(bucket) + .build() + .toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatProjectLocationBucketName( + String project, String location, String bucket) { + return newBuilder() + .setProject(project) + .setLocation(location) + .setBucket(bucket) + .build() + .toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatOrganizationLocationBucketName( + String organization, String location, String bucket) { + return newOrganizationLocationBucketBuilder() + .setOrganization(organization) + .setLocation(location) + .setBucket(bucket) + .build() + .toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatFolderLocationBucketName( + String folder, String location, String bucket) { + return newFolderLocationBucketBuilder() + .setFolder(folder) + .setLocation(location) + .setBucket(bucket) + .build() + .toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatBillingAccountLocationBucketName( + String billingAccount, String location, String bucket) { + return newBillingAccountLocationBucketBuilder() + .setBillingAccount(billingAccount) + .setLocation(location) + .setBucket(bucket) + .build() + .toString(); + } + + public static LogBucketName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + if (PROJECT_LOCATION_BUCKET.matches(formattedString)) { + Map matchMap = PROJECT_LOCATION_BUCKET.match(formattedString); + return ofProjectLocationBucketName( + matchMap.get("project"), matchMap.get("location"), matchMap.get("bucket")); + } else if (ORGANIZATION_LOCATION_BUCKET.matches(formattedString)) { + Map matchMap = ORGANIZATION_LOCATION_BUCKET.match(formattedString); + return ofOrganizationLocationBucketName( + matchMap.get("organization"), matchMap.get("location"), matchMap.get("bucket")); + } else if (FOLDER_LOCATION_BUCKET.matches(formattedString)) { + Map matchMap = FOLDER_LOCATION_BUCKET.match(formattedString); + return ofFolderLocationBucketName( + matchMap.get("folder"), matchMap.get("location"), matchMap.get("bucket")); + } else if (BILLING_ACCOUNT_LOCATION_BUCKET.matches(formattedString)) { + Map matchMap = BILLING_ACCOUNT_LOCATION_BUCKET.match(formattedString); + return ofBillingAccountLocationBucketName( + matchMap.get("billing_account"), matchMap.get("location"), matchMap.get("bucket")); + } + throw new ValidationException("LogBucketName.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 (LogBucketName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_LOCATION_BUCKET.matches(formattedString) + || ORGANIZATION_LOCATION_BUCKET.matches(formattedString) + || FOLDER_LOCATION_BUCKET.matches(formattedString) + || BILLING_ACCOUNT_LOCATION_BUCKET.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(project)) { + fieldMapBuilder.put("project", project); + } + if (!Objects.isNull(location)) { + fieldMapBuilder.put("location", location); + } + if (!Objects.isNull(bucket)) { + fieldMapBuilder.put("bucket", bucket); + } + if (!Objects.isNull(organization)) { + fieldMapBuilder.put("organization", organization); + } + if (!Objects.isNull(folder)) { + fieldMapBuilder.put("folder", folder); + } + if (!Objects.isNull(billingAccount)) { + fieldMapBuilder.put("billing_account", billingAccount); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return !Objects.isNull(fixedValue) ? fixedValue : pathTemplate.instantiate(getFieldValuesMap()); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + LogBucketName that = ((LogBucketName) o); + return Objects.equals(this.project, that.project) + && Objects.equals(this.location, that.location) + && Objects.equals(this.bucket, that.bucket) + && Objects.equals(this.organization, that.organization) + && Objects.equals(this.folder, that.folder) + && Objects.equals(this.billingAccount, that.billingAccount); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(fixedValue); + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(location); + h *= 1000003; + h ^= Objects.hashCode(bucket); + h *= 1000003; + h ^= Objects.hashCode(organization); + h *= 1000003; + h ^= Objects.hashCode(folder); + h *= 1000003; + h ^= Objects.hashCode(billingAccount); + return h; + } + + /** Builder for projects/{project}/locations/{location}/buckets/{bucket}. */ + public static class Builder { + private String project; + private String location; + private String bucket; + + private Builder() {} + + public String getProject() { + return project; + } + + public String getLocation() { + return location; + } + + public String getBucket() { + return bucket; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setLocation(String location) { + this.location = location; + return this; + } + + public Builder setBucket(String bucket) { + this.bucket = bucket; + return this; + } + + private Builder(LogBucketName logBucketName) { + Preconditions.checkArgument( + Objects.equals(logBucketName.pathTemplate, PROJECT_LOCATION_BUCKET), + "toBuilder is only supported when LogBucketName has the pattern of projects/{project}/locations/{location}/buckets/{bucket}"); + project = logBucketName.project; + location = logBucketName.location; + bucket = logBucketName.bucket; + } + + public LogBucketName build() { + return new LogBucketName(this); + } + } + + /** Builder for organizations/{organization}/locations/{location}/buckets/{bucket}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class OrganizationLocationBucketBuilder { + private String organization; + private String location; + private String bucket; + + private OrganizationLocationBucketBuilder() {} + + public String getOrganization() { + return organization; + } + + public String getLocation() { + return location; + } + + public String getBucket() { + return bucket; + } + + public OrganizationLocationBucketBuilder setOrganization(String organization) { + this.organization = organization; + return this; + } + + public OrganizationLocationBucketBuilder setLocation(String location) { + this.location = location; + return this; + } + + public OrganizationLocationBucketBuilder setBucket(String bucket) { + this.bucket = bucket; + return this; + } + + public LogBucketName build() { + return new LogBucketName(this); + } + } + + /** Builder for folders/{folder}/locations/{location}/buckets/{bucket}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class FolderLocationBucketBuilder { + private String folder; + private String location; + private String bucket; + + private FolderLocationBucketBuilder() {} + + public String getFolder() { + return folder; + } + + public String getLocation() { + return location; + } + + public String getBucket() { + return bucket; + } + + public FolderLocationBucketBuilder setFolder(String folder) { + this.folder = folder; + return this; + } + + public FolderLocationBucketBuilder setLocation(String location) { + this.location = location; + return this; + } + + public FolderLocationBucketBuilder setBucket(String bucket) { + this.bucket = bucket; + return this; + } + + public LogBucketName build() { + return new LogBucketName(this); + } + } + + /** Builder for billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class BillingAccountLocationBucketBuilder { + private String billingAccount; + private String location; + private String bucket; + + private BillingAccountLocationBucketBuilder() {} + + public String getBillingAccount() { + return billingAccount; + } + + public String getLocation() { + return location; + } + + public String getBucket() { + return bucket; + } + + public BillingAccountLocationBucketBuilder setBillingAccount(String billingAccount) { + this.billingAccount = billingAccount; + return this; + } + + public BillingAccountLocationBucketBuilder setLocation(String location) { + this.location = location; + return this; + } + + public BillingAccountLocationBucketBuilder setBucket(String bucket) { + this.bucket = bucket; + return this; + } + + public LogBucketName build() { + return new LogBucketName(this); + } + } +} diff --git a/test/integration/goldens/logging/LogExclusionName.java b/test/integration/goldens/logging/LogExclusionName.java new file mode 100644 index 0000000000..8c0bc46049 --- /dev/null +++ b/test/integration/goldens/logging/LogExclusionName.java @@ -0,0 +1,449 @@ +/* + * 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.logging.v2; + +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 LogExclusionName implements ResourceName { + private static final PathTemplate PROJECT_EXCLUSION = + PathTemplate.createWithoutUrlEncoding("projects/{project}/exclusions/{exclusion}"); + private static final PathTemplate ORGANIZATION_EXCLUSION = + PathTemplate.createWithoutUrlEncoding("organizations/{organization}/exclusions/{exclusion}"); + private static final PathTemplate FOLDER_EXCLUSION = + PathTemplate.createWithoutUrlEncoding("folders/{folder}/exclusions/{exclusion}"); + private static final PathTemplate BILLING_ACCOUNT_EXCLUSION = + PathTemplate.createWithoutUrlEncoding( + "billingAccounts/{billing_account}/exclusions/{exclusion}"); + private volatile Map fieldValuesMap; + private PathTemplate pathTemplate; + private String fixedValue; + private final String project; + private final String exclusion; + private final String organization; + private final String folder; + private final String billingAccount; + + private LogExclusionName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + exclusion = Preconditions.checkNotNull(builder.getExclusion()); + organization = null; + folder = null; + billingAccount = null; + pathTemplate = PROJECT_EXCLUSION; + } + + private LogExclusionName(OrganizationExclusionBuilder builder) { + organization = Preconditions.checkNotNull(builder.getOrganization()); + exclusion = Preconditions.checkNotNull(builder.getExclusion()); + project = null; + folder = null; + billingAccount = null; + pathTemplate = ORGANIZATION_EXCLUSION; + } + + private LogExclusionName(FolderExclusionBuilder builder) { + folder = Preconditions.checkNotNull(builder.getFolder()); + exclusion = Preconditions.checkNotNull(builder.getExclusion()); + project = null; + organization = null; + billingAccount = null; + pathTemplate = FOLDER_EXCLUSION; + } + + private LogExclusionName(BillingAccountExclusionBuilder builder) { + billingAccount = Preconditions.checkNotNull(builder.getBillingAccount()); + exclusion = Preconditions.checkNotNull(builder.getExclusion()); + project = null; + organization = null; + folder = null; + pathTemplate = BILLING_ACCOUNT_EXCLUSION; + } + + public String getProject() { + return project; + } + + public String getExclusion() { + return exclusion; + } + + public String getOrganization() { + return organization; + } + + public String getFolder() { + return folder; + } + + public String getBillingAccount() { + return billingAccount; + } + + 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 newProjectExclusionBuilder() { + return new Builder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static OrganizationExclusionBuilder newOrganizationExclusionBuilder() { + return new OrganizationExclusionBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static FolderExclusionBuilder newFolderExclusionBuilder() { + return new FolderExclusionBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static BillingAccountExclusionBuilder newBillingAccountExclusionBuilder() { + return new BillingAccountExclusionBuilder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static LogExclusionName of(String project, String exclusion) { + return newBuilder().setProject(project).setExclusion(exclusion).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogExclusionName ofProjectExclusionName(String project, String exclusion) { + return newBuilder().setProject(project).setExclusion(exclusion).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogExclusionName ofOrganizationExclusionName( + String organization, String exclusion) { + return newOrganizationExclusionBuilder() + .setOrganization(organization) + .setExclusion(exclusion) + .build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogExclusionName ofFolderExclusionName(String folder, String exclusion) { + return newFolderExclusionBuilder().setFolder(folder).setExclusion(exclusion).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogExclusionName ofBillingAccountExclusionName( + String billingAccount, String exclusion) { + return newBillingAccountExclusionBuilder() + .setBillingAccount(billingAccount) + .setExclusion(exclusion) + .build(); + } + + public static String format(String project, String exclusion) { + return newBuilder().setProject(project).setExclusion(exclusion).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatProjectExclusionName(String project, String exclusion) { + return newBuilder().setProject(project).setExclusion(exclusion).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatOrganizationExclusionName(String organization, String exclusion) { + return newOrganizationExclusionBuilder() + .setOrganization(organization) + .setExclusion(exclusion) + .build() + .toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatFolderExclusionName(String folder, String exclusion) { + return newFolderExclusionBuilder().setFolder(folder).setExclusion(exclusion).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatBillingAccountExclusionName(String billingAccount, String exclusion) { + return newBillingAccountExclusionBuilder() + .setBillingAccount(billingAccount) + .setExclusion(exclusion) + .build() + .toString(); + } + + public static LogExclusionName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + if (PROJECT_EXCLUSION.matches(formattedString)) { + Map matchMap = PROJECT_EXCLUSION.match(formattedString); + return ofProjectExclusionName(matchMap.get("project"), matchMap.get("exclusion")); + } else if (ORGANIZATION_EXCLUSION.matches(formattedString)) { + Map matchMap = ORGANIZATION_EXCLUSION.match(formattedString); + return ofOrganizationExclusionName(matchMap.get("organization"), matchMap.get("exclusion")); + } else if (FOLDER_EXCLUSION.matches(formattedString)) { + Map matchMap = FOLDER_EXCLUSION.match(formattedString); + return ofFolderExclusionName(matchMap.get("folder"), matchMap.get("exclusion")); + } else if (BILLING_ACCOUNT_EXCLUSION.matches(formattedString)) { + Map matchMap = BILLING_ACCOUNT_EXCLUSION.match(formattedString); + return ofBillingAccountExclusionName( + matchMap.get("billing_account"), matchMap.get("exclusion")); + } + throw new ValidationException("LogExclusionName.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 (LogExclusionName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_EXCLUSION.matches(formattedString) + || ORGANIZATION_EXCLUSION.matches(formattedString) + || FOLDER_EXCLUSION.matches(formattedString) + || BILLING_ACCOUNT_EXCLUSION.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(project)) { + fieldMapBuilder.put("project", project); + } + if (!Objects.isNull(exclusion)) { + fieldMapBuilder.put("exclusion", exclusion); + } + if (!Objects.isNull(organization)) { + fieldMapBuilder.put("organization", organization); + } + if (!Objects.isNull(folder)) { + fieldMapBuilder.put("folder", folder); + } + if (!Objects.isNull(billingAccount)) { + fieldMapBuilder.put("billing_account", billingAccount); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return !Objects.isNull(fixedValue) ? fixedValue : pathTemplate.instantiate(getFieldValuesMap()); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + LogExclusionName that = ((LogExclusionName) o); + return Objects.equals(this.project, that.project) + && Objects.equals(this.exclusion, that.exclusion) + && Objects.equals(this.organization, that.organization) + && Objects.equals(this.folder, that.folder) + && Objects.equals(this.billingAccount, that.billingAccount); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(fixedValue); + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(exclusion); + h *= 1000003; + h ^= Objects.hashCode(organization); + h *= 1000003; + h ^= Objects.hashCode(folder); + h *= 1000003; + h ^= Objects.hashCode(billingAccount); + return h; + } + + /** Builder for projects/{project}/exclusions/{exclusion}. */ + public static class Builder { + private String project; + private String exclusion; + + private Builder() {} + + public String getProject() { + return project; + } + + public String getExclusion() { + return exclusion; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setExclusion(String exclusion) { + this.exclusion = exclusion; + return this; + } + + private Builder(LogExclusionName logExclusionName) { + Preconditions.checkArgument( + Objects.equals(logExclusionName.pathTemplate, PROJECT_EXCLUSION), + "toBuilder is only supported when LogExclusionName has the pattern of projects/{project}/exclusions/{exclusion}"); + project = logExclusionName.project; + exclusion = logExclusionName.exclusion; + } + + public LogExclusionName build() { + return new LogExclusionName(this); + } + } + + /** Builder for organizations/{organization}/exclusions/{exclusion}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class OrganizationExclusionBuilder { + private String organization; + private String exclusion; + + private OrganizationExclusionBuilder() {} + + public String getOrganization() { + return organization; + } + + public String getExclusion() { + return exclusion; + } + + public OrganizationExclusionBuilder setOrganization(String organization) { + this.organization = organization; + return this; + } + + public OrganizationExclusionBuilder setExclusion(String exclusion) { + this.exclusion = exclusion; + return this; + } + + public LogExclusionName build() { + return new LogExclusionName(this); + } + } + + /** Builder for folders/{folder}/exclusions/{exclusion}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class FolderExclusionBuilder { + private String folder; + private String exclusion; + + private FolderExclusionBuilder() {} + + public String getFolder() { + return folder; + } + + public String getExclusion() { + return exclusion; + } + + public FolderExclusionBuilder setFolder(String folder) { + this.folder = folder; + return this; + } + + public FolderExclusionBuilder setExclusion(String exclusion) { + this.exclusion = exclusion; + return this; + } + + public LogExclusionName build() { + return new LogExclusionName(this); + } + } + + /** Builder for billingAccounts/{billing_account}/exclusions/{exclusion}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class BillingAccountExclusionBuilder { + private String billingAccount; + private String exclusion; + + private BillingAccountExclusionBuilder() {} + + public String getBillingAccount() { + return billingAccount; + } + + public String getExclusion() { + return exclusion; + } + + public BillingAccountExclusionBuilder setBillingAccount(String billingAccount) { + this.billingAccount = billingAccount; + return this; + } + + public BillingAccountExclusionBuilder setExclusion(String exclusion) { + this.exclusion = exclusion; + return this; + } + + public LogExclusionName build() { + return new LogExclusionName(this); + } + } +} diff --git a/test/integration/goldens/logging/LogMetricName.java b/test/integration/goldens/logging/LogMetricName.java new file mode 100644 index 0000000000..104ecc3266 --- /dev/null +++ b/test/integration/goldens/logging/LogMetricName.java @@ -0,0 +1,185 @@ +/* + * 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.logging.v2; + +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 LogMetricName implements ResourceName { + private static final PathTemplate PROJECT_METRIC = + PathTemplate.createWithoutUrlEncoding("projects/{project}/metrics/{metric}"); + private volatile Map fieldValuesMap; + private final String project; + private final String metric; + + private LogMetricName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + metric = Preconditions.checkNotNull(builder.getMetric()); + } + + public String getProject() { + return project; + } + + public String getMetric() { + return metric; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static LogMetricName of(String project, String metric) { + return newBuilder().setProject(project).setMetric(metric).build(); + } + + public static String format(String project, String metric) { + return newBuilder().setProject(project).setMetric(metric).build().toString(); + } + + public static LogMetricName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + PROJECT_METRIC.validatedMatch( + formattedString, "LogMetricName.parse: formattedString not in valid format"); + return of(matchMap.get("project"), matchMap.get("metric")); + } + + 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 (LogMetricName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_METRIC.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(project)) { + fieldMapBuilder.put("project", project); + } + if (!Objects.isNull(metric)) { + fieldMapBuilder.put("metric", metric); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return PROJECT_METRIC.instantiate("project", project); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + LogMetricName that = ((LogMetricName) o); + return Objects.equals(this.project, that.project) && Objects.equals(this.metric, that.metric); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(metric); + return h; + } + + /** Builder for projects/{project}/metrics/{metric}. */ + public static class Builder { + private String project; + private String metric; + + private Builder() {} + + public String getProject() { + return project; + } + + public String getMetric() { + return metric; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setMetric(String metric) { + this.metric = metric; + return this; + } + + private Builder(LogMetricName logMetricName) { + project = logMetricName.project; + metric = logMetricName.metric; + } + + public LogMetricName build() { + return new LogMetricName(this); + } + } +} diff --git a/test/integration/goldens/logging/LogName.java b/test/integration/goldens/logging/LogName.java new file mode 100644 index 0000000000..b4f4cea34e --- /dev/null +++ b/test/integration/goldens/logging/LogName.java @@ -0,0 +1,435 @@ +/* + * 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.logging.v2; + +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 LogName implements ResourceName { + private static final PathTemplate PROJECT_LOG = + PathTemplate.createWithoutUrlEncoding("projects/{project}/logs/{log}"); + private static final PathTemplate ORGANIZATION_LOG = + PathTemplate.createWithoutUrlEncoding("organizations/{organization}/logs/{log}"); + private static final PathTemplate FOLDER_LOG = + PathTemplate.createWithoutUrlEncoding("folders/{folder}/logs/{log}"); + private static final PathTemplate BILLING_ACCOUNT_LOG = + PathTemplate.createWithoutUrlEncoding("billingAccounts/{billing_account}/logs/{log}"); + private volatile Map fieldValuesMap; + private PathTemplate pathTemplate; + private String fixedValue; + private final String project; + private final String log; + private final String organization; + private final String folder; + private final String billingAccount; + + private LogName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + log = Preconditions.checkNotNull(builder.getLog()); + organization = null; + folder = null; + billingAccount = null; + pathTemplate = PROJECT_LOG; + } + + private LogName(OrganizationLogBuilder builder) { + organization = Preconditions.checkNotNull(builder.getOrganization()); + log = Preconditions.checkNotNull(builder.getLog()); + project = null; + folder = null; + billingAccount = null; + pathTemplate = ORGANIZATION_LOG; + } + + private LogName(FolderLogBuilder builder) { + folder = Preconditions.checkNotNull(builder.getFolder()); + log = Preconditions.checkNotNull(builder.getLog()); + project = null; + organization = null; + billingAccount = null; + pathTemplate = FOLDER_LOG; + } + + private LogName(BillingAccountLogBuilder builder) { + billingAccount = Preconditions.checkNotNull(builder.getBillingAccount()); + log = Preconditions.checkNotNull(builder.getLog()); + project = null; + organization = null; + folder = null; + pathTemplate = BILLING_ACCOUNT_LOG; + } + + public String getProject() { + return project; + } + + public String getLog() { + return log; + } + + public String getOrganization() { + return organization; + } + + public String getFolder() { + return folder; + } + + public String getBillingAccount() { + return billingAccount; + } + + 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 newProjectLogBuilder() { + return new Builder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static OrganizationLogBuilder newOrganizationLogBuilder() { + return new OrganizationLogBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static FolderLogBuilder newFolderLogBuilder() { + return new FolderLogBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static BillingAccountLogBuilder newBillingAccountLogBuilder() { + return new BillingAccountLogBuilder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static LogName of(String project, String log) { + return newBuilder().setProject(project).setLog(log).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogName ofProjectLogName(String project, String log) { + return newBuilder().setProject(project).setLog(log).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogName ofOrganizationLogName(String organization, String log) { + return newOrganizationLogBuilder().setOrganization(organization).setLog(log).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogName ofFolderLogName(String folder, String log) { + return newFolderLogBuilder().setFolder(folder).setLog(log).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogName ofBillingAccountLogName(String billingAccount, String log) { + return newBillingAccountLogBuilder().setBillingAccount(billingAccount).setLog(log).build(); + } + + public static String format(String project, String log) { + return newBuilder().setProject(project).setLog(log).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatProjectLogName(String project, String log) { + return newBuilder().setProject(project).setLog(log).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatOrganizationLogName(String organization, String log) { + return newOrganizationLogBuilder().setOrganization(organization).setLog(log).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatFolderLogName(String folder, String log) { + return newFolderLogBuilder().setFolder(folder).setLog(log).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatBillingAccountLogName(String billingAccount, String log) { + return newBillingAccountLogBuilder() + .setBillingAccount(billingAccount) + .setLog(log) + .build() + .toString(); + } + + public static LogName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + if (PROJECT_LOG.matches(formattedString)) { + Map matchMap = PROJECT_LOG.match(formattedString); + return ofProjectLogName(matchMap.get("project"), matchMap.get("log")); + } else if (ORGANIZATION_LOG.matches(formattedString)) { + Map matchMap = ORGANIZATION_LOG.match(formattedString); + return ofOrganizationLogName(matchMap.get("organization"), matchMap.get("log")); + } else if (FOLDER_LOG.matches(formattedString)) { + Map matchMap = FOLDER_LOG.match(formattedString); + return ofFolderLogName(matchMap.get("folder"), matchMap.get("log")); + } else if (BILLING_ACCOUNT_LOG.matches(formattedString)) { + Map matchMap = BILLING_ACCOUNT_LOG.match(formattedString); + return ofBillingAccountLogName(matchMap.get("billing_account"), matchMap.get("log")); + } + throw new ValidationException("LogName.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 (LogName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_LOG.matches(formattedString) + || ORGANIZATION_LOG.matches(formattedString) + || FOLDER_LOG.matches(formattedString) + || BILLING_ACCOUNT_LOG.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(project)) { + fieldMapBuilder.put("project", project); + } + if (!Objects.isNull(log)) { + fieldMapBuilder.put("log", log); + } + if (!Objects.isNull(organization)) { + fieldMapBuilder.put("organization", organization); + } + if (!Objects.isNull(folder)) { + fieldMapBuilder.put("folder", folder); + } + if (!Objects.isNull(billingAccount)) { + fieldMapBuilder.put("billing_account", billingAccount); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return !Objects.isNull(fixedValue) ? fixedValue : pathTemplate.instantiate(getFieldValuesMap()); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + LogName that = ((LogName) o); + return Objects.equals(this.project, that.project) + && Objects.equals(this.log, that.log) + && Objects.equals(this.organization, that.organization) + && Objects.equals(this.folder, that.folder) + && Objects.equals(this.billingAccount, that.billingAccount); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(fixedValue); + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(log); + h *= 1000003; + h ^= Objects.hashCode(organization); + h *= 1000003; + h ^= Objects.hashCode(folder); + h *= 1000003; + h ^= Objects.hashCode(billingAccount); + return h; + } + + /** Builder for projects/{project}/logs/{log}. */ + public static class Builder { + private String project; + private String log; + + private Builder() {} + + public String getProject() { + return project; + } + + public String getLog() { + return log; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setLog(String log) { + this.log = log; + return this; + } + + private Builder(LogName logName) { + Preconditions.checkArgument( + Objects.equals(logName.pathTemplate, PROJECT_LOG), + "toBuilder is only supported when LogName has the pattern of projects/{project}/logs/{log}"); + project = logName.project; + log = logName.log; + } + + public LogName build() { + return new LogName(this); + } + } + + /** Builder for organizations/{organization}/logs/{log}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class OrganizationLogBuilder { + private String organization; + private String log; + + private OrganizationLogBuilder() {} + + public String getOrganization() { + return organization; + } + + public String getLog() { + return log; + } + + public OrganizationLogBuilder setOrganization(String organization) { + this.organization = organization; + return this; + } + + public OrganizationLogBuilder setLog(String log) { + this.log = log; + return this; + } + + public LogName build() { + return new LogName(this); + } + } + + /** Builder for folders/{folder}/logs/{log}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class FolderLogBuilder { + private String folder; + private String log; + + private FolderLogBuilder() {} + + public String getFolder() { + return folder; + } + + public String getLog() { + return log; + } + + public FolderLogBuilder setFolder(String folder) { + this.folder = folder; + return this; + } + + public FolderLogBuilder setLog(String log) { + this.log = log; + return this; + } + + public LogName build() { + return new LogName(this); + } + } + + /** Builder for billingAccounts/{billing_account}/logs/{log}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class BillingAccountLogBuilder { + private String billingAccount; + private String log; + + private BillingAccountLogBuilder() {} + + public String getBillingAccount() { + return billingAccount; + } + + public String getLog() { + return log; + } + + public BillingAccountLogBuilder setBillingAccount(String billingAccount) { + this.billingAccount = billingAccount; + return this; + } + + public BillingAccountLogBuilder setLog(String log) { + this.log = log; + return this; + } + + public LogName build() { + return new LogName(this); + } + } +} diff --git a/test/integration/goldens/logging/LogSinkName.java b/test/integration/goldens/logging/LogSinkName.java new file mode 100644 index 0000000000..b2211390dc --- /dev/null +++ b/test/integration/goldens/logging/LogSinkName.java @@ -0,0 +1,439 @@ +/* + * 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.logging.v2; + +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 LogSinkName implements ResourceName { + private static final PathTemplate PROJECT_SINK = + PathTemplate.createWithoutUrlEncoding("projects/{project}/sinks/{sink}"); + private static final PathTemplate ORGANIZATION_SINK = + PathTemplate.createWithoutUrlEncoding("organizations/{organization}/sinks/{sink}"); + private static final PathTemplate FOLDER_SINK = + PathTemplate.createWithoutUrlEncoding("folders/{folder}/sinks/{sink}"); + private static final PathTemplate BILLING_ACCOUNT_SINK = + PathTemplate.createWithoutUrlEncoding("billingAccounts/{billing_account}/sinks/{sink}"); + private volatile Map fieldValuesMap; + private PathTemplate pathTemplate; + private String fixedValue; + private final String project; + private final String sink; + private final String organization; + private final String folder; + private final String billingAccount; + + private LogSinkName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + sink = Preconditions.checkNotNull(builder.getSink()); + organization = null; + folder = null; + billingAccount = null; + pathTemplate = PROJECT_SINK; + } + + private LogSinkName(OrganizationSinkBuilder builder) { + organization = Preconditions.checkNotNull(builder.getOrganization()); + sink = Preconditions.checkNotNull(builder.getSink()); + project = null; + folder = null; + billingAccount = null; + pathTemplate = ORGANIZATION_SINK; + } + + private LogSinkName(FolderSinkBuilder builder) { + folder = Preconditions.checkNotNull(builder.getFolder()); + sink = Preconditions.checkNotNull(builder.getSink()); + project = null; + organization = null; + billingAccount = null; + pathTemplate = FOLDER_SINK; + } + + private LogSinkName(BillingAccountSinkBuilder builder) { + billingAccount = Preconditions.checkNotNull(builder.getBillingAccount()); + sink = Preconditions.checkNotNull(builder.getSink()); + project = null; + organization = null; + folder = null; + pathTemplate = BILLING_ACCOUNT_SINK; + } + + public String getProject() { + return project; + } + + public String getSink() { + return sink; + } + + public String getOrganization() { + return organization; + } + + public String getFolder() { + return folder; + } + + public String getBillingAccount() { + return billingAccount; + } + + 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 newProjectSinkBuilder() { + return new Builder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static OrganizationSinkBuilder newOrganizationSinkBuilder() { + return new OrganizationSinkBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static FolderSinkBuilder newFolderSinkBuilder() { + return new FolderSinkBuilder(); + } + + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static BillingAccountSinkBuilder newBillingAccountSinkBuilder() { + return new BillingAccountSinkBuilder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static LogSinkName of(String project, String sink) { + return newBuilder().setProject(project).setSink(sink).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogSinkName ofProjectSinkName(String project, String sink) { + return newBuilder().setProject(project).setSink(sink).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogSinkName ofOrganizationSinkName(String organization, String sink) { + return newOrganizationSinkBuilder().setOrganization(organization).setSink(sink).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogSinkName ofFolderSinkName(String folder, String sink) { + return newFolderSinkBuilder().setFolder(folder).setSink(sink).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static LogSinkName ofBillingAccountSinkName(String billingAccount, String sink) { + return newBillingAccountSinkBuilder().setBillingAccount(billingAccount).setSink(sink).build(); + } + + public static String format(String project, String sink) { + return newBuilder().setProject(project).setSink(sink).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatProjectSinkName(String project, String sink) { + return newBuilder().setProject(project).setSink(sink).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatOrganizationSinkName(String organization, String sink) { + return newOrganizationSinkBuilder() + .setOrganization(organization) + .setSink(sink) + .build() + .toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatFolderSinkName(String folder, String sink) { + return newFolderSinkBuilder().setFolder(folder).setSink(sink).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatBillingAccountSinkName(String billingAccount, String sink) { + return newBillingAccountSinkBuilder() + .setBillingAccount(billingAccount) + .setSink(sink) + .build() + .toString(); + } + + public static LogSinkName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + if (PROJECT_SINK.matches(formattedString)) { + Map matchMap = PROJECT_SINK.match(formattedString); + return ofProjectSinkName(matchMap.get("project"), matchMap.get("sink")); + } else if (ORGANIZATION_SINK.matches(formattedString)) { + Map matchMap = ORGANIZATION_SINK.match(formattedString); + return ofOrganizationSinkName(matchMap.get("organization"), matchMap.get("sink")); + } else if (FOLDER_SINK.matches(formattedString)) { + Map matchMap = FOLDER_SINK.match(formattedString); + return ofFolderSinkName(matchMap.get("folder"), matchMap.get("sink")); + } else if (BILLING_ACCOUNT_SINK.matches(formattedString)) { + Map matchMap = BILLING_ACCOUNT_SINK.match(formattedString); + return ofBillingAccountSinkName(matchMap.get("billing_account"), matchMap.get("sink")); + } + throw new ValidationException("LogSinkName.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 (LogSinkName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_SINK.matches(formattedString) + || ORGANIZATION_SINK.matches(formattedString) + || FOLDER_SINK.matches(formattedString) + || BILLING_ACCOUNT_SINK.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(project)) { + fieldMapBuilder.put("project", project); + } + if (!Objects.isNull(sink)) { + fieldMapBuilder.put("sink", sink); + } + if (!Objects.isNull(organization)) { + fieldMapBuilder.put("organization", organization); + } + if (!Objects.isNull(folder)) { + fieldMapBuilder.put("folder", folder); + } + if (!Objects.isNull(billingAccount)) { + fieldMapBuilder.put("billing_account", billingAccount); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return !Objects.isNull(fixedValue) ? fixedValue : pathTemplate.instantiate(getFieldValuesMap()); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + LogSinkName that = ((LogSinkName) o); + return Objects.equals(this.project, that.project) + && Objects.equals(this.sink, that.sink) + && Objects.equals(this.organization, that.organization) + && Objects.equals(this.folder, that.folder) + && Objects.equals(this.billingAccount, that.billingAccount); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(fixedValue); + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(sink); + h *= 1000003; + h ^= Objects.hashCode(organization); + h *= 1000003; + h ^= Objects.hashCode(folder); + h *= 1000003; + h ^= Objects.hashCode(billingAccount); + return h; + } + + /** Builder for projects/{project}/sinks/{sink}. */ + public static class Builder { + private String project; + private String sink; + + private Builder() {} + + public String getProject() { + return project; + } + + public String getSink() { + return sink; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setSink(String sink) { + this.sink = sink; + return this; + } + + private Builder(LogSinkName logSinkName) { + Preconditions.checkArgument( + Objects.equals(logSinkName.pathTemplate, PROJECT_SINK), + "toBuilder is only supported when LogSinkName has the pattern of projects/{project}/sinks/{sink}"); + project = logSinkName.project; + sink = logSinkName.sink; + } + + public LogSinkName build() { + return new LogSinkName(this); + } + } + + /** Builder for organizations/{organization}/sinks/{sink}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class OrganizationSinkBuilder { + private String organization; + private String sink; + + private OrganizationSinkBuilder() {} + + public String getOrganization() { + return organization; + } + + public String getSink() { + return sink; + } + + public OrganizationSinkBuilder setOrganization(String organization) { + this.organization = organization; + return this; + } + + public OrganizationSinkBuilder setSink(String sink) { + this.sink = sink; + return this; + } + + public LogSinkName build() { + return new LogSinkName(this); + } + } + + /** Builder for folders/{folder}/sinks/{sink}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class FolderSinkBuilder { + private String folder; + private String sink; + + private FolderSinkBuilder() {} + + public String getFolder() { + return folder; + } + + public String getSink() { + return sink; + } + + public FolderSinkBuilder setFolder(String folder) { + this.folder = folder; + return this; + } + + public FolderSinkBuilder setSink(String sink) { + this.sink = sink; + return this; + } + + public LogSinkName build() { + return new LogSinkName(this); + } + } + + /** Builder for billingAccounts/{billing_account}/sinks/{sink}. */ + @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") + public static class BillingAccountSinkBuilder { + private String billingAccount; + private String sink; + + private BillingAccountSinkBuilder() {} + + public String getBillingAccount() { + return billingAccount; + } + + public String getSink() { + return sink; + } + + public BillingAccountSinkBuilder setBillingAccount(String billingAccount) { + this.billingAccount = billingAccount; + return this; + } + + public BillingAccountSinkBuilder setSink(String sink) { + this.sink = sink; + return this; + } + + public LogSinkName build() { + return new LogSinkName(this); + } + } +} diff --git a/test/integration/goldens/logging/LoggingServiceV2Client.java b/test/integration/goldens/logging/LoggingServiceV2Client.java new file mode 100644 index 0000000000..2bbf50ba65 --- /dev/null +++ b/test/integration/goldens/logging/LoggingServiceV2Client.java @@ -0,0 +1,888 @@ +/* + * 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.logging.v2; + +import com.google.api.MonitoredResource; +import com.google.api.MonitoredResourceDescriptor; +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.paging.AbstractFixedSizeCollection; +import com.google.api.gax.paging.AbstractPage; +import com.google.api.gax.paging.AbstractPagedListResponse; +import com.google.api.gax.rpc.PageContext; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.logging.v2.stub.LoggingServiceV2Stub; +import com.google.logging.v2.stub.LoggingServiceV2StubSettings; +import com.google.protobuf.Empty; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Service Description: Service for ingesting and querying logs. + * + *

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 LoggingServiceV2Settings to + * create(). For example: + * + *

To customize credentials: + * + *

To customize the endpoint: + */ +@BetaApi +@Generated("by gapic-generator") +public class LoggingServiceV2Client implements BackgroundResource { + private final LoggingServiceV2Settings settings; + private final LoggingServiceV2Stub stub; + + /** Constructs an instance of EchoClient with default settings. */ + public static final LoggingServiceV2Client create() throws IOException { + return create(LoggingServiceV2Settings.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 LoggingServiceV2Client create(LoggingServiceV2Settings settings) + throws IOException { + return new LoggingServiceV2Client(settings); + } + + /** + * Constructs an instance of EchoClient, using the given stub for making calls. This is for + * advanced usage - prefer using create(LoggingServiceV2Settings). + */ + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public static final LoggingServiceV2Client create(LoggingServiceV2Stub stub) { + return new LoggingServiceV2Client(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 LoggingServiceV2Client(LoggingServiceV2Settings settings) throws IOException { + this.settings = settings; + this.stub = ((LoggingServiceV2StubSettings) settings.getStubSettings()).createStub(); + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + protected LoggingServiceV2Client(LoggingServiceV2Stub stub) { + this.settings = null; + this.stub = stub; + } + + public final LoggingServiceV2Settings getSettings() { + return settings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public LoggingServiceV2Stub getStub() { + return stub; + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries + * written shortly before the delete operation might not be deleted. Entries received after the + * delete operation with a timestamp before the operation will be deleted. + * + *

Sample code: + * + * @param log_name Required. The resource name of the log to delete: + * "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" + * `[LOG_ID]` must be URL-encoded. For example, `"projects/my-project-id/logs/syslog"`, + * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. For more + * information about log names, see [LogEntry][google.logging.v2.LogEntry]. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Empty deleteLog(LogName logName) { + DeleteLogRequest request = + DeleteLogRequest.newBuilder() + .setLogName(Objects.isNull(logName) ? null : logName.toString()) + .build(); + return deleteLog(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries + * written shortly before the delete operation might not be deleted. Entries received after the + * delete operation with a timestamp before the operation will be deleted. + * + *

Sample code: + * + * @param log_name Required. The resource name of the log to delete: + * "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" + * `[LOG_ID]` must be URL-encoded. For example, `"projects/my-project-id/logs/syslog"`, + * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. For more + * information about log names, see [LogEntry][google.logging.v2.LogEntry]. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Empty deleteLog(String logName) { + DeleteLogRequest request = DeleteLogRequest.newBuilder().setLogName(logName).build(); + return deleteLog(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries + * written shortly before the delete operation might not be deleted. Entries received after the + * delete operation with a timestamp before the operation will be deleted. + * + *

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 Empty deleteLog(DeleteLogRequest request) { + return deleteLogCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries + * written shortly before the delete operation might not be deleted. Entries received after the + * delete operation with a timestamp before the operation will be deleted. + * + *

Sample code: + */ + public final UnaryCallable deleteLogCallable() { + return stub.deleteLogCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Writes log entries to Logging. This API method is the only way to send log entries to Logging. + * This method is used, directly or indirectly, by the Logging agent (fluentd) and all logging + * libraries configured to use Logging. A single request may contain log entries for a maximum of + * 1000 different resources (projects, organizations, billing accounts or folders) + * + *

Sample code: + * + * @param log_name Optional. A default log resource name that is assigned to all log entries in + * `entries` that do not specify a value for `log_name`: "projects/[PROJECT_ID]/logs/[LOG_ID]" + * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" + * `[LOG_ID]` must be URL-encoded. For example: "projects/my-project-id/logs/syslog" + * "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity" The + * permission `logging.logEntries.create` is needed on each project, organization, billing + * account, or folder that is receiving new log entries, whether the resource is specified in + * `logName` or in an individual log entry. + * @param resource Optional. A default monitored resource object that is assigned to all log + * entries in `entries` that do not specify a value for `resource`. Example: { "type": + * "gce_instance", "labels": { "zone": "us-central1-a", "instance_id": "00000000000000000000" + * }} See [LogEntry][google.logging.v2.LogEntry]. + * @param labels Optional. Default labels that are added to the `labels` field of all log entries + * in `entries`. If a log entry already has a label with the same key as a label in this + * parameter, then the log entry's label is not changed. See + * [LogEntry][google.logging.v2.LogEntry]. + * @param entries Required. The log entries to send to Logging. The order of log entries in this + * list does not matter. Values supplied in this method's `log_name`, `resource`, and `labels` + * fields are copied into those log entries in this list that do not include values for their + * corresponding fields. For more information, see the [LogEntry][google.logging.v2.LogEntry] + * type. If the `timestamp` or `insert_id` fields are missing in log entries, then this method + * supplies the current time or a unique identifier, respectively. The supplied values are + * chosen so that, among the log entries that did not supply their own values, the entries + * earlier in the list will sort before the entries later in the list. See the `entries.list` + * method. Log entries with timestamps that are more than the [logs retention + * period](https://cloud.google.com/logging/quota-policy) in the past or more than 24 hours in + * the future will not be available when calling `entries.list`. However, those log entries + * can still be [exported with + * LogSinks](https://cloud.google.com/logging/docs/api/tasks/exporting-logs). To improve + * throughput and to avoid exceeding the [quota + * limit](https://cloud.google.com/logging/quota-policy) for calls to `entries.write`, you + * should try to include several log entries in this list, rather than calling this method for + * each individual log entry. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final WriteLogEntriesResponse writeLogEntries( + LogName logName, + MonitoredResource resource, + Map labels, + List entries) { + WriteLogEntriesRequest request = + WriteLogEntriesRequest.newBuilder() + .setLogName(Objects.isNull(logName) ? null : logName.toString()) + .setResource(resource) + .putAllLabels(labels) + .addAllEntries(entries) + .build(); + return writeLogEntries(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Writes log entries to Logging. This API method is the only way to send log entries to Logging. + * This method is used, directly or indirectly, by the Logging agent (fluentd) and all logging + * libraries configured to use Logging. A single request may contain log entries for a maximum of + * 1000 different resources (projects, organizations, billing accounts or folders) + * + *

Sample code: + * + * @param log_name Optional. A default log resource name that is assigned to all log entries in + * `entries` that do not specify a value for `log_name`: "projects/[PROJECT_ID]/logs/[LOG_ID]" + * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" + * `[LOG_ID]` must be URL-encoded. For example: "projects/my-project-id/logs/syslog" + * "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity" The + * permission `logging.logEntries.create` is needed on each project, organization, billing + * account, or folder that is receiving new log entries, whether the resource is specified in + * `logName` or in an individual log entry. + * @param resource Optional. A default monitored resource object that is assigned to all log + * entries in `entries` that do not specify a value for `resource`. Example: { "type": + * "gce_instance", "labels": { "zone": "us-central1-a", "instance_id": "00000000000000000000" + * }} See [LogEntry][google.logging.v2.LogEntry]. + * @param labels Optional. Default labels that are added to the `labels` field of all log entries + * in `entries`. If a log entry already has a label with the same key as a label in this + * parameter, then the log entry's label is not changed. See + * [LogEntry][google.logging.v2.LogEntry]. + * @param entries Required. The log entries to send to Logging. The order of log entries in this + * list does not matter. Values supplied in this method's `log_name`, `resource`, and `labels` + * fields are copied into those log entries in this list that do not include values for their + * corresponding fields. For more information, see the [LogEntry][google.logging.v2.LogEntry] + * type. If the `timestamp` or `insert_id` fields are missing in log entries, then this method + * supplies the current time or a unique identifier, respectively. The supplied values are + * chosen so that, among the log entries that did not supply their own values, the entries + * earlier in the list will sort before the entries later in the list. See the `entries.list` + * method. Log entries with timestamps that are more than the [logs retention + * period](https://cloud.google.com/logging/quota-policy) in the past or more than 24 hours in + * the future will not be available when calling `entries.list`. However, those log entries + * can still be [exported with + * LogSinks](https://cloud.google.com/logging/docs/api/tasks/exporting-logs). To improve + * throughput and to avoid exceeding the [quota + * limit](https://cloud.google.com/logging/quota-policy) for calls to `entries.write`, you + * should try to include several log entries in this list, rather than calling this method for + * each individual log entry. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final WriteLogEntriesResponse writeLogEntries( + String logName, + MonitoredResource resource, + Map labels, + List entries) { + WriteLogEntriesRequest request = + WriteLogEntriesRequest.newBuilder() + .setLogName(logName) + .setResource(resource) + .putAllLabels(labels) + .addAllEntries(entries) + .build(); + return writeLogEntries(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Writes log entries to Logging. This API method is the only way to send log entries to Logging. + * This method is used, directly or indirectly, by the Logging agent (fluentd) and all logging + * libraries configured to use Logging. A single request may contain log entries for a maximum of + * 1000 different resources (projects, organizations, billing accounts or folders) + * + *

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 WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest request) { + return writeLogEntriesCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Writes log entries to Logging. This API method is the only way to send log entries to Logging. + * This method is used, directly or indirectly, by the Logging agent (fluentd) and all logging + * libraries configured to use Logging. A single request may contain log entries for a maximum of + * 1000 different resources (projects, organizations, billing accounts or folders) + * + *

Sample code: + */ + public final UnaryCallable + writeLogEntriesCallable() { + return stub.writeLogEntriesCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists log entries. Use this method to retrieve log entries that originated from a + * project/folder/organization/billing account. For ways to export log entries, see [Exporting + * Logs](https://cloud.google.com/logging/docs/export). + * + *

Sample code: + * + * @param resource_names Required. Names of one or more parent resources from which to retrieve + * log entries: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Projects listed in the + * `project_ids` field are added to this list. + * @param filter Optional. A filter that chooses which log entries to return. See [Advanced Logs + * Queries](https://cloud.google.com/logging/docs/view/advanced-queries). Only log entries + * that match the filter are returned. An empty filter matches all log entries in the + * resources listed in `resource_names`. Referencing a parent resource that is not listed in + * `resource_names` will cause the filter to return no results. The maximum length of the + * filter is 20000 characters. + * @param order_by Optional. How the results should be sorted. Presently, the only permitted + * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first option returns + * entries in order of increasing values of `LogEntry.timestamp` (oldest first), and the + * second option returns entries in order of decreasing timestamps (newest first). Entries + * with equal timestamps are returned in order of their `insert_id` values. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListLogEntriesPagedResponse listLogEntries( + List resourceNames, String filter, String orderBy) { + ListLogEntriesRequest request = + ListLogEntriesRequest.newBuilder() + .addAllResourceNames(resourceNames) + .setFilter(filter) + .setOrderBy(orderBy) + .build(); + return listLogEntries(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists log entries. Use this method to retrieve log entries that originated from a + * project/folder/organization/billing account. For ways to export log entries, see [Exporting + * Logs](https://cloud.google.com/logging/docs/export). + * + *

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 ListLogEntriesPagedResponse listLogEntries(ListLogEntriesRequest request) { + return listLogEntriesPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists log entries. Use this method to retrieve log entries that originated from a + * project/folder/organization/billing account. For ways to export log entries, see [Exporting + * Logs](https://cloud.google.com/logging/docs/export). + * + *

Sample code: + */ + public final UnaryCallable + listLogEntriesPagedCallable() { + return stub.listLogEntriesPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists log entries. Use this method to retrieve log entries that originated from a + * project/folder/organization/billing account. For ways to export log entries, see [Exporting + * Logs](https://cloud.google.com/logging/docs/export). + * + *

Sample code: + */ + public final UnaryCallable + listLogEntriesCallable() { + return stub.listLogEntriesCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the descriptors for monitored resource types used by Logging. + * + *

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 ListMonitoredResourceDescriptorsPagedResponse listMonitoredResourceDescriptors( + ListMonitoredResourceDescriptorsRequest request) { + return listMonitoredResourceDescriptorsPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the descriptors for monitored resource types used by Logging. + * + *

Sample code: + */ + public final UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsPagedResponse> + listMonitoredResourceDescriptorsPagedCallable() { + return stub.listMonitoredResourceDescriptorsPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the descriptors for monitored resource types used by Logging. + * + *

Sample code: + */ + public final UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> + listMonitoredResourceDescriptorsCallable() { + return stub.listMonitoredResourceDescriptorsCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have + * entries are listed. + * + *

Sample code: + * + * @param parent Required. The resource name that owns the logs: "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListLogsPagedResponse listLogs(BillingAccountName parent) { + ListLogsRequest request = + ListLogsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listLogs(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have + * entries are listed. + * + *

Sample code: + * + * @param parent Required. The resource name that owns the logs: "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListLogsPagedResponse listLogs(FolderName parent) { + ListLogsRequest request = + ListLogsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listLogs(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have + * entries are listed. + * + *

Sample code: + * + * @param parent Required. The resource name that owns the logs: "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListLogsPagedResponse listLogs(OrganizationName parent) { + ListLogsRequest request = + ListLogsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listLogs(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have + * entries are listed. + * + *

Sample code: + * + * @param parent Required. The resource name that owns the logs: "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListLogsPagedResponse listLogs(ProjectName parent) { + ListLogsRequest request = + ListLogsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listLogs(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have + * entries are listed. + * + *

Sample code: + * + * @param parent Required. The resource name that owns the logs: "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListLogsPagedResponse listLogs(String parent) { + ListLogsRequest request = ListLogsRequest.newBuilder().setParent(parent).build(); + return listLogs(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have + * entries are listed. + * + *

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 ListLogsPagedResponse listLogs(ListLogsRequest request) { + return listLogsPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have + * entries are listed. + * + *

Sample code: + */ + public final UnaryCallable listLogsPagedCallable() { + return stub.listLogsPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have + * entries are listed. + * + *

Sample code: + */ + public final UnaryCallable listLogsCallable() { + return stub.listLogsCallable(); + } + + @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 ListLogEntriesPagedResponse + extends AbstractPagedListResponse< + ListLogEntriesRequest, + ListLogEntriesResponse, + LogEntry, + ListLogEntriesPage, + ListLogEntriesFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListLogEntriesPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListLogEntriesPagedResponse apply(ListLogEntriesPage input) { + return new ListLogEntriesPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListLogEntriesPagedResponse(ListLogEntriesPage page) { + super(page, ListLogEntriesFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListLogEntriesPage + extends AbstractPage< + ListLogEntriesRequest, ListLogEntriesResponse, LogEntry, ListLogEntriesPage> { + + private ListLogEntriesPage( + PageContext context, + ListLogEntriesResponse response) { + super(context, response); + } + + private static ListLogEntriesPage createEmptyPage() { + return new ListLogEntriesPage(null, null); + } + + @Override + protected ListLogEntriesPage createPage( + PageContext context, + ListLogEntriesResponse response) { + return new ListLogEntriesPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListLogEntriesFixedSizeCollection + extends AbstractFixedSizeCollection< + ListLogEntriesRequest, + ListLogEntriesResponse, + LogEntry, + ListLogEntriesPage, + ListLogEntriesFixedSizeCollection> { + + private ListLogEntriesFixedSizeCollection(List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListLogEntriesFixedSizeCollection createEmptyCollection() { + return new ListLogEntriesFixedSizeCollection(null, 0); + } + + @Override + protected ListLogEntriesFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListLogEntriesFixedSizeCollection(pages, collectionSize); + } + } + + public static class ListMonitoredResourceDescriptorsPagedResponse + extends AbstractPagedListResponse< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor, + ListMonitoredResourceDescriptorsPage, + ListMonitoredResourceDescriptorsFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor> + context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListMonitoredResourceDescriptorsPage.createEmptyPage() + .createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction< + ListMonitoredResourceDescriptorsPage, + ListMonitoredResourceDescriptorsPagedResponse>() { + @Override + public ListMonitoredResourceDescriptorsPagedResponse apply( + ListMonitoredResourceDescriptorsPage input) { + return new ListMonitoredResourceDescriptorsPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListMonitoredResourceDescriptorsPagedResponse( + ListMonitoredResourceDescriptorsPage page) { + super(page, ListMonitoredResourceDescriptorsFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListMonitoredResourceDescriptorsPage + extends AbstractPage< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor, + ListMonitoredResourceDescriptorsPage> { + + private ListMonitoredResourceDescriptorsPage( + PageContext< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor> + context, + ListMonitoredResourceDescriptorsResponse response) { + super(context, response); + } + + private static ListMonitoredResourceDescriptorsPage createEmptyPage() { + return new ListMonitoredResourceDescriptorsPage(null, null); + } + + @Override + protected ListMonitoredResourceDescriptorsPage createPage( + PageContext< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor> + context, + ListMonitoredResourceDescriptorsResponse response) { + return new ListMonitoredResourceDescriptorsPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor> + context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListMonitoredResourceDescriptorsFixedSizeCollection + extends AbstractFixedSizeCollection< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor, + ListMonitoredResourceDescriptorsPage, + ListMonitoredResourceDescriptorsFixedSizeCollection> { + + private ListMonitoredResourceDescriptorsFixedSizeCollection( + List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListMonitoredResourceDescriptorsFixedSizeCollection createEmptyCollection() { + return new ListMonitoredResourceDescriptorsFixedSizeCollection(null, 0); + } + + @Override + protected ListMonitoredResourceDescriptorsFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListMonitoredResourceDescriptorsFixedSizeCollection(pages, collectionSize); + } + } + + public static class ListLogsPagedResponse + extends AbstractPagedListResponse< + ListLogsRequest, ListLogsResponse, String, ListLogsPage, ListLogsFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListLogsPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListLogsPagedResponse apply(ListLogsPage input) { + return new ListLogsPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListLogsPagedResponse(ListLogsPage page) { + super(page, ListLogsFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListLogsPage + extends AbstractPage { + + private ListLogsPage( + PageContext context, ListLogsResponse response) { + super(context, response); + } + + private static ListLogsPage createEmptyPage() { + return new ListLogsPage(null, null); + } + + @Override + protected ListLogsPage createPage( + PageContext context, ListLogsResponse response) { + return new ListLogsPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListLogsFixedSizeCollection + extends AbstractFixedSizeCollection< + ListLogsRequest, ListLogsResponse, String, ListLogsPage, ListLogsFixedSizeCollection> { + + private ListLogsFixedSizeCollection(List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListLogsFixedSizeCollection createEmptyCollection() { + return new ListLogsFixedSizeCollection(null, 0); + } + + @Override + protected ListLogsFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListLogsFixedSizeCollection(pages, collectionSize); + } + } +} diff --git a/test/integration/goldens/logging/LoggingServiceV2Settings.java b/test/integration/goldens/logging/LoggingServiceV2Settings.java new file mode 100644 index 0000000000..83dc356803 --- /dev/null +++ b/test/integration/goldens/logging/LoggingServiceV2Settings.java @@ -0,0 +1,231 @@ +/* + * 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.logging.v2; + +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.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.PagedCallSettings; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.logging.v2.stub.LoggingServiceV2StubSettings; +import com.google.protobuf.Empty; +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 LoggingServiceV2Client}. + * + *

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: + */ +@Generated("by gapic-generator-java") +public class LoggingServiceV2Settings extends ClientSettings { + + /** Returns the object with the settings used for calls to deleteLog. */ + public UnaryCallSettings deleteLogSettings() { + return ((LoggingServiceV2StubSettings) getStubSettings()).deleteLogSettings(); + } + + /** Returns the object with the settings used for calls to writeLogEntries. */ + public UnaryCallSettings + writeLogEntriesSettings() { + return ((LoggingServiceV2StubSettings) getStubSettings()).writeLogEntriesSettings(); + } + + /** Returns the object with the settings used for calls to listLogEntries. */ + public PagedCallSettings< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> + listLogEntriesSettings() { + return ((LoggingServiceV2StubSettings) getStubSettings()).listLogEntriesSettings(); + } + + /** Returns the object with the settings used for calls to listMonitoredResourceDescriptors. */ + public PagedCallSettings< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse> + listMonitoredResourceDescriptorsSettings() { + return ((LoggingServiceV2StubSettings) getStubSettings()) + .listMonitoredResourceDescriptorsSettings(); + } + + /** Returns the object with the settings used for calls to listLogs. */ + public PagedCallSettings + listLogsSettings() { + return ((LoggingServiceV2StubSettings) getStubSettings()).listLogsSettings(); + } + + public static final LoggingServiceV2Settings create(LoggingServiceV2StubSettings stub) + throws IOException { + return new LoggingServiceV2Settings.Builder(stub.toBuilder()).build(); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return LoggingServiceV2StubSettings.defaultExecutorProviderBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return LoggingServiceV2StubSettings.getDefaultEndpoint(); + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return LoggingServiceV2StubSettings.getDefaultServiceScopes(); + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return LoggingServiceV2StubSettings.defaultCredentialsProviderBuilder(); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return LoggingServiceV2StubSettings.defaultGrpcTransportProviderBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return LoggingServiceV2StubSettings.defaultTransportChannelProvider(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return LoggingServiceV2StubSettings.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 LoggingServiceV2Settings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + } + + /** Builder for LoggingServiceV2Settings. */ + public static class Builder extends ClientSettings.Builder { + + protected Builder() throws IOException { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(LoggingServiceV2StubSettings.newBuilder(clientContext)); + } + + protected Builder(LoggingServiceV2Settings settings) { + super(settings.getStubSettings().toBuilder()); + } + + protected Builder(LoggingServiceV2StubSettings.Builder stubSettings) { + super(stubSettings); + } + + private static Builder createDefault() { + return new Builder(LoggingServiceV2StubSettings.newBuilder()); + } + + public LoggingServiceV2StubSettings.Builder getStubSettingsBuilder() { + return ((LoggingServiceV2StubSettings.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 deleteLog. */ + public UnaryCallSettings.Builder deleteLogSettings() { + return getStubSettingsBuilder().deleteLogSettings(); + } + + /** Returns the builder for the settings used for calls to writeLogEntries. */ + public UnaryCallSettings.Builder + writeLogEntriesSettings() { + return getStubSettingsBuilder().writeLogEntriesSettings(); + } + + /** Returns the builder for the settings used for calls to listLogEntries. */ + public PagedCallSettings.Builder< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> + listLogEntriesSettings() { + return getStubSettingsBuilder().listLogEntriesSettings(); + } + + /** Returns the builder for the settings used for calls to listMonitoredResourceDescriptors. */ + public PagedCallSettings.Builder< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse> + listMonitoredResourceDescriptorsSettings() { + return getStubSettingsBuilder().listMonitoredResourceDescriptorsSettings(); + } + + /** Returns the builder for the settings used for calls to listLogs. */ + public PagedCallSettings.Builder + listLogsSettings() { + return getStubSettingsBuilder().listLogsSettings(); + } + + @Override + public LoggingServiceV2Settings build() throws IOException { + return new LoggingServiceV2Settings(this); + } + } +} diff --git a/test/integration/goldens/logging/LoggingServiceV2Stub.java b/test/integration/goldens/logging/LoggingServiceV2Stub.java new file mode 100644 index 0000000000..5eef9cae5e --- /dev/null +++ b/test/integration/goldens/logging/LoggingServiceV2Stub.java @@ -0,0 +1,87 @@ +/* + * 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.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.gax.core.BackgroundResource; +import com.google.api.gax.rpc.UnaryCallable; +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.WriteLogEntriesRequest; +import com.google.logging.v2.WriteLogEntriesResponse; +import com.google.protobuf.Empty; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Base stub class for the LoggingServiceV2 service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator") +public abstract class LoggingServiceV2Stub implements BackgroundResource { + + public UnaryCallable deleteLogCallable() { + throw new UnsupportedOperationException("Not implemented: deleteLogCallable()"); + } + + public UnaryCallable writeLogEntriesCallable() { + throw new UnsupportedOperationException("Not implemented: writeLogEntriesCallable()"); + } + + public UnaryCallable + listLogEntriesPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listLogEntriesPagedCallable()"); + } + + public UnaryCallable listLogEntriesCallable() { + throw new UnsupportedOperationException("Not implemented: listLogEntriesCallable()"); + } + + public UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsPagedResponse> + listMonitoredResourceDescriptorsPagedCallable() { + throw new UnsupportedOperationException( + "Not implemented: listMonitoredResourceDescriptorsPagedCallable()"); + } + + public UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> + listMonitoredResourceDescriptorsCallable() { + throw new UnsupportedOperationException( + "Not implemented: listMonitoredResourceDescriptorsCallable()"); + } + + public UnaryCallable listLogsPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listLogsPagedCallable()"); + } + + public UnaryCallable listLogsCallable() { + throw new UnsupportedOperationException("Not implemented: listLogsCallable()"); + } + + @Override + public abstract void close(); +} diff --git a/test/integration/goldens/logging/LoggingServiceV2StubSettings.java b/test/integration/goldens/logging/LoggingServiceV2StubSettings.java new file mode 100644 index 0000000000..7e6456b3d4 --- /dev/null +++ b/test/integration/goldens/logging/LoggingServiceV2StubSettings.java @@ -0,0 +1,598 @@ +/* + * 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.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.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.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.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 UnaryCallSettings + 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.isNull(payload.getEntriesList()) + ? ImmutableList.of() + : payload.getEntriesList(); + } + }; + + 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.isNull(payload.getResourceDescriptorsList()) + ? ImmutableList.of() + : payload.getResourceDescriptorsList(); + } + }; + + 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.isNull(payload.getLogNamesList()) + ? ImmutableList.of() + : payload.getLogNamesList(); + } + }; + + 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); + } + }; + + /** 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 UnaryCallSettings + 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 UnaryCallSettings.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 = UnaryCallSettings.newUnaryCallSettingsBuilder(); + 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() + .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 UnaryCallSettings.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/test/integration/goldens/logging/MetricsServiceV2Client.java b/test/integration/goldens/logging/MetricsServiceV2Client.java new file mode 100644 index 0000000000..9341c256f0 --- /dev/null +++ b/test/integration/goldens/logging/MetricsServiceV2Client.java @@ -0,0 +1,545 @@ +/* + * 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.logging.v2; + +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.paging.AbstractFixedSizeCollection; +import com.google.api.gax.paging.AbstractPage; +import com.google.api.gax.paging.AbstractPagedListResponse; +import com.google.api.gax.rpc.PageContext; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.logging.v2.stub.MetricsServiceV2Stub; +import com.google.logging.v2.stub.MetricsServiceV2StubSettings; +import com.google.protobuf.Empty; +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. +/** + * Service Description: Service for configuring logs-based metrics. + * + *

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 MetricsServiceV2Settings to + * create(). For example: + * + *

To customize credentials: + * + *

To customize the endpoint: + */ +@BetaApi +@Generated("by gapic-generator") +public class MetricsServiceV2Client implements BackgroundResource { + private final MetricsServiceV2Settings settings; + private final MetricsServiceV2Stub stub; + + /** Constructs an instance of EchoClient with default settings. */ + public static final MetricsServiceV2Client create() throws IOException { + return create(MetricsServiceV2Settings.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 MetricsServiceV2Client create(MetricsServiceV2Settings settings) + throws IOException { + return new MetricsServiceV2Client(settings); + } + + /** + * Constructs an instance of EchoClient, using the given stub for making calls. This is for + * advanced usage - prefer using create(MetricsServiceV2Settings). + */ + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public static final MetricsServiceV2Client create(MetricsServiceV2Stub stub) { + return new MetricsServiceV2Client(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 MetricsServiceV2Client(MetricsServiceV2Settings settings) throws IOException { + this.settings = settings; + this.stub = ((MetricsServiceV2StubSettings) settings.getStubSettings()).createStub(); + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + protected MetricsServiceV2Client(MetricsServiceV2Stub stub) { + this.settings = null; + this.stub = stub; + } + + public final MetricsServiceV2Settings getSettings() { + return settings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public MetricsServiceV2Stub getStub() { + return stub; + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists logs-based metrics. + * + *

Sample code: + * + * @param parent Required. The name of the project containing the metrics: "projects/[PROJECT_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListLogMetricsPagedResponse listLogMetrics(ProjectName parent) { + ListLogMetricsRequest request = + ListLogMetricsRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .build(); + return listLogMetrics(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists logs-based metrics. + * + *

Sample code: + * + * @param parent Required. The name of the project containing the metrics: "projects/[PROJECT_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListLogMetricsPagedResponse listLogMetrics(String parent) { + ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(parent).build(); + return listLogMetrics(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists logs-based metrics. + * + *

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 ListLogMetricsPagedResponse listLogMetrics(ListLogMetricsRequest request) { + return listLogMetricsPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists logs-based metrics. + * + *

Sample code: + */ + public final UnaryCallable + listLogMetricsPagedCallable() { + return stub.listLogMetricsPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists logs-based metrics. + * + *

Sample code: + */ + public final UnaryCallable + listLogMetricsCallable() { + return stub.listLogMetricsCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a logs-based metric. + * + *

Sample code: + * + * @param metric_name Required. The resource name of the desired metric: + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogMetric getLogMetric(LogMetricName metricName) { + GetLogMetricRequest request = + GetLogMetricRequest.newBuilder() + .setMetricName(Objects.isNull(metricName) ? null : metricName.toString()) + .build(); + return getLogMetric(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a logs-based metric. + * + *

Sample code: + * + * @param metric_name Required. The resource name of the desired metric: + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogMetric getLogMetric(String metricName) { + GetLogMetricRequest request = + GetLogMetricRequest.newBuilder().setMetricName(metricName).build(); + return getLogMetric(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a logs-based metric. + * + *

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 LogMetric getLogMetric(GetLogMetricRequest request) { + return getLogMetricCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a logs-based metric. + * + *

Sample code: + */ + public final UnaryCallable getLogMetricCallable() { + return stub.getLogMetricCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a logs-based metric. + * + *

Sample code: + * + * @param parent Required. The resource name of the project in which to create the metric: + * "projects/[PROJECT_ID]" The new metric must be provided in the request. + * @param metric Required. The new logs-based metric, which must not have an identifier that + * already exists. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogMetric createLogMetric(ProjectName parent, LogMetric metric) { + CreateLogMetricRequest request = + CreateLogMetricRequest.newBuilder() + .setParent(Objects.isNull(parent) ? null : parent.toString()) + .setMetric(metric) + .build(); + return createLogMetric(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a logs-based metric. + * + *

Sample code: + * + * @param parent Required. The resource name of the project in which to create the metric: + * "projects/[PROJECT_ID]" The new metric must be provided in the request. + * @param metric Required. The new logs-based metric, which must not have an identifier that + * already exists. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogMetric createLogMetric(String parent, LogMetric metric) { + CreateLogMetricRequest request = + CreateLogMetricRequest.newBuilder().setParent(parent).setMetric(metric).build(); + return createLogMetric(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a logs-based metric. + * + *

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 LogMetric createLogMetric(CreateLogMetricRequest request) { + return createLogMetricCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a logs-based metric. + * + *

Sample code: + */ + public final UnaryCallable createLogMetricCallable() { + return stub.createLogMetricCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates or updates a logs-based metric. + * + *

Sample code: + * + * @param metric_name Required. The resource name of the metric to update: + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" The updated metric must be provided in the + * request and it's `name` field must be the same as `[METRIC_ID]` If the metric does not + * exist in `[PROJECT_ID]`, then a new metric is created. + * @param metric Required. The updated metric. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogMetric updateLogMetric(LogMetricName metricName, LogMetric metric) { + UpdateLogMetricRequest request = + UpdateLogMetricRequest.newBuilder() + .setMetricName(Objects.isNull(metricName) ? null : metricName.toString()) + .setMetric(metric) + .build(); + return updateLogMetric(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates or updates a logs-based metric. + * + *

Sample code: + * + * @param metric_name Required. The resource name of the metric to update: + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" The updated metric must be provided in the + * request and it's `name` field must be the same as `[METRIC_ID]` If the metric does not + * exist in `[PROJECT_ID]`, then a new metric is created. + * @param metric Required. The updated metric. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final LogMetric updateLogMetric(String metricName, LogMetric metric) { + UpdateLogMetricRequest request = + UpdateLogMetricRequest.newBuilder().setMetricName(metricName).setMetric(metric).build(); + return updateLogMetric(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates or updates a logs-based metric. + * + *

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 LogMetric updateLogMetric(UpdateLogMetricRequest request) { + return updateLogMetricCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates or updates a logs-based metric. + * + *

Sample code: + */ + public final UnaryCallable updateLogMetricCallable() { + return stub.updateLogMetricCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a logs-based metric. + * + *

Sample code: + * + * @param metric_name Required. The resource name of the metric to delete: + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Empty deleteLogMetric(LogMetricName metricName) { + DeleteLogMetricRequest request = + DeleteLogMetricRequest.newBuilder() + .setMetricName(Objects.isNull(metricName) ? null : metricName.toString()) + .build(); + return deleteLogMetric(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a logs-based metric. + * + *

Sample code: + * + * @param metric_name Required. The resource name of the metric to delete: + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Empty deleteLogMetric(String metricName) { + DeleteLogMetricRequest request = + DeleteLogMetricRequest.newBuilder().setMetricName(metricName).build(); + return deleteLogMetric(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a logs-based metric. + * + *

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 Empty deleteLogMetric(DeleteLogMetricRequest request) { + return deleteLogMetricCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a logs-based metric. + * + *

Sample code: + */ + public final UnaryCallable deleteLogMetricCallable() { + return stub.deleteLogMetricCallable(); + } + + @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 ListLogMetricsPagedResponse + extends AbstractPagedListResponse< + ListLogMetricsRequest, + ListLogMetricsResponse, + LogMetric, + ListLogMetricsPage, + ListLogMetricsFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListLogMetricsPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListLogMetricsPagedResponse apply(ListLogMetricsPage input) { + return new ListLogMetricsPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListLogMetricsPagedResponse(ListLogMetricsPage page) { + super(page, ListLogMetricsFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListLogMetricsPage + extends AbstractPage< + ListLogMetricsRequest, ListLogMetricsResponse, LogMetric, ListLogMetricsPage> { + + private ListLogMetricsPage( + PageContext context, + ListLogMetricsResponse response) { + super(context, response); + } + + private static ListLogMetricsPage createEmptyPage() { + return new ListLogMetricsPage(null, null); + } + + @Override + protected ListLogMetricsPage createPage( + PageContext context, + ListLogMetricsResponse response) { + return new ListLogMetricsPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListLogMetricsFixedSizeCollection + extends AbstractFixedSizeCollection< + ListLogMetricsRequest, + ListLogMetricsResponse, + LogMetric, + ListLogMetricsPage, + ListLogMetricsFixedSizeCollection> { + + private ListLogMetricsFixedSizeCollection(List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListLogMetricsFixedSizeCollection createEmptyCollection() { + return new ListLogMetricsFixedSizeCollection(null, 0); + } + + @Override + protected ListLogMetricsFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListLogMetricsFixedSizeCollection(pages, collectionSize); + } + } +} diff --git a/test/integration/goldens/logging/MetricsServiceV2Settings.java b/test/integration/goldens/logging/MetricsServiceV2Settings.java new file mode 100644 index 0000000000..e9c0451fcb --- /dev/null +++ b/test/integration/goldens/logging/MetricsServiceV2Settings.java @@ -0,0 +1,216 @@ +/* + * 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.logging.v2; + +import static com.google.logging.v2.MetricsServiceV2Client.ListLogMetricsPagedResponse; + +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.PagedCallSettings; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.logging.v2.stub.MetricsServiceV2StubSettings; +import com.google.protobuf.Empty; +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 MetricsServiceV2Client}. + * + *

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 listLogMetrics to 30 seconds: + */ +@Generated("by gapic-generator-java") +public class MetricsServiceV2Settings extends ClientSettings { + + /** Returns the object with the settings used for calls to listLogMetrics. */ + public PagedCallSettings< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> + listLogMetricsSettings() { + return ((MetricsServiceV2StubSettings) getStubSettings()).listLogMetricsSettings(); + } + + /** Returns the object with the settings used for calls to getLogMetric. */ + public UnaryCallSettings getLogMetricSettings() { + return ((MetricsServiceV2StubSettings) getStubSettings()).getLogMetricSettings(); + } + + /** Returns the object with the settings used for calls to createLogMetric. */ + public UnaryCallSettings createLogMetricSettings() { + return ((MetricsServiceV2StubSettings) getStubSettings()).createLogMetricSettings(); + } + + /** Returns the object with the settings used for calls to updateLogMetric. */ + public UnaryCallSettings updateLogMetricSettings() { + return ((MetricsServiceV2StubSettings) getStubSettings()).updateLogMetricSettings(); + } + + /** Returns the object with the settings used for calls to deleteLogMetric. */ + public UnaryCallSettings deleteLogMetricSettings() { + return ((MetricsServiceV2StubSettings) getStubSettings()).deleteLogMetricSettings(); + } + + public static final MetricsServiceV2Settings create(MetricsServiceV2StubSettings stub) + throws IOException { + return new MetricsServiceV2Settings.Builder(stub.toBuilder()).build(); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return MetricsServiceV2StubSettings.defaultExecutorProviderBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return MetricsServiceV2StubSettings.getDefaultEndpoint(); + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return MetricsServiceV2StubSettings.getDefaultServiceScopes(); + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return MetricsServiceV2StubSettings.defaultCredentialsProviderBuilder(); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return MetricsServiceV2StubSettings.defaultGrpcTransportProviderBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return MetricsServiceV2StubSettings.defaultTransportChannelProvider(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return MetricsServiceV2StubSettings.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 MetricsServiceV2Settings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + } + + /** Builder for MetricsServiceV2Settings. */ + public static class Builder extends ClientSettings.Builder { + + protected Builder() throws IOException { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(MetricsServiceV2StubSettings.newBuilder(clientContext)); + } + + protected Builder(MetricsServiceV2Settings settings) { + super(settings.getStubSettings().toBuilder()); + } + + protected Builder(MetricsServiceV2StubSettings.Builder stubSettings) { + super(stubSettings); + } + + private static Builder createDefault() { + return new Builder(MetricsServiceV2StubSettings.newBuilder()); + } + + public MetricsServiceV2StubSettings.Builder getStubSettingsBuilder() { + return ((MetricsServiceV2StubSettings.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 listLogMetrics. */ + public PagedCallSettings.Builder< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> + listLogMetricsSettings() { + return getStubSettingsBuilder().listLogMetricsSettings(); + } + + /** Returns the builder for the settings used for calls to getLogMetric. */ + public UnaryCallSettings.Builder getLogMetricSettings() { + return getStubSettingsBuilder().getLogMetricSettings(); + } + + /** Returns the builder for the settings used for calls to createLogMetric. */ + public UnaryCallSettings.Builder createLogMetricSettings() { + return getStubSettingsBuilder().createLogMetricSettings(); + } + + /** Returns the builder for the settings used for calls to updateLogMetric. */ + public UnaryCallSettings.Builder updateLogMetricSettings() { + return getStubSettingsBuilder().updateLogMetricSettings(); + } + + /** Returns the builder for the settings used for calls to deleteLogMetric. */ + public UnaryCallSettings.Builder deleteLogMetricSettings() { + return getStubSettingsBuilder().deleteLogMetricSettings(); + } + + @Override + public MetricsServiceV2Settings build() throws IOException { + return new MetricsServiceV2Settings(this); + } + } +} diff --git a/test/integration/goldens/logging/MetricsServiceV2Stub.java b/test/integration/goldens/logging/MetricsServiceV2Stub.java new file mode 100644 index 0000000000..c70df1c420 --- /dev/null +++ b/test/integration/goldens/logging/MetricsServiceV2Stub.java @@ -0,0 +1,69 @@ +/* + * 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.logging.v2.stub; + +import static com.google.logging.v2.MetricsServiceV2Client.ListLogMetricsPagedResponse; + +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.logging.v2.CreateLogMetricRequest; +import com.google.logging.v2.DeleteLogMetricRequest; +import com.google.logging.v2.GetLogMetricRequest; +import com.google.logging.v2.ListLogMetricsRequest; +import com.google.logging.v2.ListLogMetricsResponse; +import com.google.logging.v2.LogMetric; +import com.google.logging.v2.UpdateLogMetricRequest; +import com.google.protobuf.Empty; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Base stub class for the MetricsServiceV2 service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator") +public abstract class MetricsServiceV2Stub implements BackgroundResource { + + public UnaryCallable + listLogMetricsPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listLogMetricsPagedCallable()"); + } + + public UnaryCallable listLogMetricsCallable() { + throw new UnsupportedOperationException("Not implemented: listLogMetricsCallable()"); + } + + public UnaryCallable getLogMetricCallable() { + throw new UnsupportedOperationException("Not implemented: getLogMetricCallable()"); + } + + public UnaryCallable createLogMetricCallable() { + throw new UnsupportedOperationException("Not implemented: createLogMetricCallable()"); + } + + public UnaryCallable updateLogMetricCallable() { + throw new UnsupportedOperationException("Not implemented: updateLogMetricCallable()"); + } + + public UnaryCallable deleteLogMetricCallable() { + throw new UnsupportedOperationException("Not implemented: deleteLogMetricCallable()"); + } + + @Override + public abstract void close(); +} diff --git a/test/integration/goldens/logging/MetricsServiceV2StubSettings.java b/test/integration/goldens/logging/MetricsServiceV2StubSettings.java new file mode 100644 index 0000000000..2d0a8aedbc --- /dev/null +++ b/test/integration/goldens/logging/MetricsServiceV2StubSettings.java @@ -0,0 +1,442 @@ +/* + * 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.logging.v2.stub; + +import static com.google.logging.v2.MetricsServiceV2Client.ListLogMetricsPagedResponse; + +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.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.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.CreateLogMetricRequest; +import com.google.logging.v2.DeleteLogMetricRequest; +import com.google.logging.v2.GetLogMetricRequest; +import com.google.logging.v2.ListLogMetricsRequest; +import com.google.logging.v2.ListLogMetricsResponse; +import com.google.logging.v2.LogMetric; +import com.google.logging.v2.UpdateLogMetricRequest; +import com.google.protobuf.Empty; +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 MetricsServiceV2Stub}. + * + *

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 listLogMetrics to 30 seconds: + */ +@BetaApi +@Generated("by gapic-generator-java") +public class MetricsServiceV2StubSettings 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 PagedCallSettings< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> + listLogMetricsSettings; + private final UnaryCallSettings getLogMetricSettings; + private final UnaryCallSettings createLogMetricSettings; + private final UnaryCallSettings updateLogMetricSettings; + private final UnaryCallSettings deleteLogMetricSettings; + + private static final PagedListDescriptor + LIST_LOG_METRICS_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListLogMetricsRequest injectToken(ListLogMetricsRequest payload, String token) { + return ListLogMetricsRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListLogMetricsRequest injectPageSize( + ListLogMetricsRequest payload, int pageSize) { + return ListLogMetricsRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListLogMetricsRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListLogMetricsResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListLogMetricsResponse payload) { + return Objects.isNull(payload.getMetricsList()) + ? ImmutableList.of() + : payload.getMetricsList(); + } + }; + + private static final PagedListResponseFactory< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> + LIST_LOG_METRICS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListLogMetricsRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, LIST_LOG_METRICS_PAGE_STR_DESC, request, context); + return ListLogMetricsPagedResponse.createAsync(pageContext, futureResponse); + } + }; + + /** Returns the object with the settings used for calls to listLogMetrics. */ + public PagedCallSettings< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> + listLogMetricsSettings() { + return listLogMetricsSettings; + } + + /** Returns the object with the settings used for calls to getLogMetric. */ + public UnaryCallSettings getLogMetricSettings() { + return getLogMetricSettings; + } + + /** Returns the object with the settings used for calls to createLogMetric. */ + public UnaryCallSettings createLogMetricSettings() { + return createLogMetricSettings; + } + + /** Returns the object with the settings used for calls to updateLogMetric. */ + public UnaryCallSettings updateLogMetricSettings() { + return updateLogMetricSettings; + } + + /** Returns the object with the settings used for calls to deleteLogMetric. */ + public UnaryCallSettings deleteLogMetricSettings() { + return deleteLogMetricSettings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public MetricsServiceV2Stub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(GrpcTransportChannel.getGrpcTransportName())) { + return GrpcMetricsServiceV2Stub.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(MetricsServiceV2StubSettings.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 MetricsServiceV2StubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + + listLogMetricsSettings = settingsBuilder.listLogMetricsSettings().build(); + getLogMetricSettings = settingsBuilder.getLogMetricSettings().build(); + createLogMetricSettings = settingsBuilder.createLogMetricSettings().build(); + updateLogMetricSettings = settingsBuilder.updateLogMetricSettings().build(); + deleteLogMetricSettings = settingsBuilder.deleteLogMetricSettings().build(); + } + + /** Builder for MetricsServiceV2StubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final PagedCallSettings.Builder< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> + listLogMetricsSettings; + private final UnaryCallSettings.Builder getLogMetricSettings; + private final UnaryCallSettings.Builder + createLogMetricSettings; + private final UnaryCallSettings.Builder + updateLogMetricSettings; + private final UnaryCallSettings.Builder deleteLogMetricSettings; + private static final ImmutableMap> + RETRYABLE_CODE_DEFINITIONS; + + static { + ImmutableMap.Builder> definitions = + ImmutableMap.builder(); + definitions.put( + "retry_policy_5_codes", + ImmutableSet.copyOf( + Lists.newArrayList( + StatusCode.Code.DEADLINE_EXCEEDED, + StatusCode.Code.INTERNAL, + StatusCode.Code.UNAVAILABLE))); + 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(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_5_params", settings); + settings = + RetrySettings.newBuilder() + .setInitialRpcTimeout(Duration.ofMillis(60000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(60000L)) + .setTotalTimeout(Duration.ofMillis(60000L)) + .build(); + definitions.put("no_retry_0_params", settings); + RETRY_PARAM_DEFINITIONS = definitions.build(); + } + + protected Builder() { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(clientContext); + + listLogMetricsSettings = PagedCallSettings.newBuilder(LIST_LOG_METRICS_PAGE_STR_FACT); + getLogMetricSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + createLogMetricSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + updateLogMetricSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + deleteLogMetricSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + listLogMetricsSettings, + getLogMetricSettings, + createLogMetricSettings, + updateLogMetricSettings, + deleteLogMetricSettings); + initDefaults(this); + } + + protected Builder(MetricsServiceV2StubSettings settings) { + super(settings); + + listLogMetricsSettings = settings.listLogMetricsSettings.toBuilder(); + getLogMetricSettings = settings.getLogMetricSettings.toBuilder(); + createLogMetricSettings = settings.createLogMetricSettings.toBuilder(); + updateLogMetricSettings = settings.updateLogMetricSettings.toBuilder(); + deleteLogMetricSettings = settings.deleteLogMetricSettings.toBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + listLogMetricsSettings, + getLogMetricSettings, + createLogMetricSettings, + updateLogMetricSettings, + deleteLogMetricSettings); + } + + 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 + .listLogMetricsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .getLogMetricSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .createLogMetricSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); + + builder + .updateLogMetricSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .deleteLogMetricSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_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 listLogMetrics. */ + public PagedCallSettings.Builder< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> + listLogMetricsSettings() { + return listLogMetricsSettings; + } + + /** Returns the builder for the settings used for calls to getLogMetric. */ + public UnaryCallSettings.Builder getLogMetricSettings() { + return getLogMetricSettings; + } + + /** Returns the builder for the settings used for calls to createLogMetric. */ + public UnaryCallSettings.Builder createLogMetricSettings() { + return createLogMetricSettings; + } + + /** Returns the builder for the settings used for calls to updateLogMetric. */ + public UnaryCallSettings.Builder updateLogMetricSettings() { + return updateLogMetricSettings; + } + + /** Returns the builder for the settings used for calls to deleteLogMetric. */ + public UnaryCallSettings.Builder deleteLogMetricSettings() { + return deleteLogMetricSettings; + } + + @Override + public MetricsServiceV2StubSettings build() throws IOException { + return new MetricsServiceV2StubSettings(this); + } + } +} diff --git a/test/integration/goldens/logging/OrganizationLocationName.java b/test/integration/goldens/logging/OrganizationLocationName.java new file mode 100644 index 0000000000..08dbc40fd5 --- /dev/null +++ b/test/integration/goldens/logging/OrganizationLocationName.java @@ -0,0 +1,186 @@ +/* + * 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.logging.v2; + +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 OrganizationLocationName implements ResourceName { + private static final PathTemplate ORGANIZATION_LOCATION = + PathTemplate.createWithoutUrlEncoding("organizations/{organization}/locations/{location}"); + private volatile Map fieldValuesMap; + private final String organization; + private final String location; + + private OrganizationLocationName(Builder builder) { + organization = Preconditions.checkNotNull(builder.getOrganization()); + location = Preconditions.checkNotNull(builder.getLocation()); + } + + public String getOrganization() { + return organization; + } + + public String getLocation() { + return location; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static OrganizationLocationName of(String organization, String location) { + return newBuilder().setOrganization(organization).setLocation(location).build(); + } + + public static String format(String organization, String location) { + return newBuilder().setOrganization(organization).setLocation(location).build().toString(); + } + + public static OrganizationLocationName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + ORGANIZATION_LOCATION.validatedMatch( + formattedString, "OrganizationLocationName.parse: formattedString not in valid format"); + return of(matchMap.get("organization"), matchMap.get("location")); + } + + 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 (OrganizationLocationName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return ORGANIZATION_LOCATION.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(organization)) { + fieldMapBuilder.put("organization", organization); + } + if (!Objects.isNull(location)) { + fieldMapBuilder.put("location", location); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return ORGANIZATION_LOCATION.instantiate("organization", organization); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + OrganizationLocationName that = ((OrganizationLocationName) o); + return Objects.equals(this.organization, that.organization) + && Objects.equals(this.location, that.location); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(organization); + h *= 1000003; + h ^= Objects.hashCode(location); + return h; + } + + /** Builder for organizations/{organization}/locations/{location}. */ + public static class Builder { + private String organization; + private String location; + + private Builder() {} + + public String getOrganization() { + return organization; + } + + public String getLocation() { + return location; + } + + public Builder setOrganization(String organization) { + this.organization = organization; + return this; + } + + public Builder setLocation(String location) { + this.location = location; + return this; + } + + private Builder(OrganizationLocationName organizationLocationName) { + organization = organizationLocationName.organization; + location = organizationLocationName.location; + } + + public OrganizationLocationName build() { + return new OrganizationLocationName(this); + } + } +} diff --git a/test/integration/goldens/logging/OrganizationName.java b/test/integration/goldens/logging/OrganizationName.java new file mode 100644 index 0000000000..a8860f3e9c --- /dev/null +++ b/test/integration/goldens/logging/OrganizationName.java @@ -0,0 +1,163 @@ +/* + * 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.logging.v2; + +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 OrganizationName implements ResourceName { + private static final PathTemplate ORGANIZATION = + PathTemplate.createWithoutUrlEncoding("organizations/{organization}"); + private volatile Map fieldValuesMap; + private final String organization; + + private OrganizationName(Builder builder) { + organization = Preconditions.checkNotNull(builder.getOrganization()); + } + + public String getOrganization() { + return organization; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static OrganizationName of(String organization) { + return newBuilder().setOrganization(organization).build(); + } + + public static String format(String organization) { + return newBuilder().setOrganization(organization).build().toString(); + } + + public static OrganizationName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + ORGANIZATION.validatedMatch( + formattedString, "OrganizationName.parse: formattedString not in valid format"); + return of(matchMap.get("organization")); + } + + 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 (OrganizationName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return ORGANIZATION.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(organization)) { + fieldMapBuilder.put("organization", organization); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return ORGANIZATION.instantiate("organization", organization); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + OrganizationName that = ((OrganizationName) o); + return Objects.equals(this.organization, that.organization); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(organization); + return h; + } + + /** Builder for organizations/{organization}. */ + public static class Builder { + private String organization; + + private Builder() {} + + public String getOrganization() { + return organization; + } + + public Builder setOrganization(String organization) { + this.organization = organization; + return this; + } + + private Builder(OrganizationName organizationName) { + organization = organizationName.organization; + } + + public OrganizationName build() { + return new OrganizationName(this); + } + } +} diff --git a/test/integration/goldens/logging/ProjectName.java b/test/integration/goldens/logging/ProjectName.java new file mode 100644 index 0000000000..2003259874 --- /dev/null +++ b/test/integration/goldens/logging/ProjectName.java @@ -0,0 +1,163 @@ +/* + * 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.logging.v2; + +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 ProjectName implements ResourceName { + private static final PathTemplate PROJECT = + PathTemplate.createWithoutUrlEncoding("projects/{project}"); + private volatile Map fieldValuesMap; + private final String project; + + private ProjectName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + } + + public String getProject() { + return project; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static ProjectName of(String project) { + return newBuilder().setProject(project).build(); + } + + public static String format(String project) { + return newBuilder().setProject(project).build().toString(); + } + + public static ProjectName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + PROJECT.validatedMatch( + formattedString, "ProjectName.parse: formattedString not in valid format"); + return of(matchMap.get("project")); + } + + 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 (ProjectName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(project)) { + fieldMapBuilder.put("project", project); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return PROJECT.instantiate("project", project); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + ProjectName that = ((ProjectName) o); + return Objects.equals(this.project, that.project); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(project); + return h; + } + + /** Builder for projects/{project}. */ + public static class Builder { + private String project; + + private Builder() {} + + public String getProject() { + return project; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + private Builder(ProjectName projectName) { + project = projectName.project; + } + + public ProjectName build() { + return new ProjectName(this); + } + } +} diff --git a/test/integration/goldens/logging/package-info.java b/test/integration/goldens/logging/package-info.java new file mode 100644 index 0000000000..f42783ea3f --- /dev/null +++ b/test/integration/goldens/logging/package-info.java @@ -0,0 +1,43 @@ +/* + * 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. + */ + +/** + * A client to Cloud Logging API + * + *

The interfaces provided are listed below, along with usage samples. + * + *

======================= LoggingServiceV2Client ======================= + * + *

Service Description: Service for ingesting and querying logs. + * + *

Sample for LoggingServiceV2Client: + * + *

======================= ConfigServiceV2Client ======================= + * + *

Service Description: Service for configuring sinks used to route log entries. + * + *

Sample for ConfigServiceV2Client: + * + *

======================= MetricsServiceV2Client ======================= + * + *

Service Description: Service for configuring logs-based metrics. + * + *

Sample for MetricsServiceV2Client: + */ +@Generated("by gapic-generator-java") +package com.google.logging.v2; + +import javax.annotation.Generated; From 9df3a5bf13fe555d328e64c1c7e35f49670b3c0b Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 18:05:41 -0700 Subject: [PATCH 15/26] fix: fix asset_java_gapic build --- test/integration/BUILD.bazel | 1 + 1 file changed, 1 insertion(+) diff --git a/test/integration/BUILD.bazel b/test/integration/BUILD.bazel index c1275aab13..c159d127e2 100644 --- a/test/integration/BUILD.bazel +++ b/test/integration/BUILD.bazel @@ -52,6 +52,7 @@ java_gapic_library( "@com_google_googleapis//google/iam/v1:iam_java_grpc", ], deps = [ + "@com_google_googleapis//google/cloud/asset/v1:asset_java_proto", "@com_google_googleapis//google/iam/v1:iam_java_proto", "@com_google_googleapis//google/identity/accesscontextmanager/v1:accesscontextmanager_proto", ], From 96f86767818a451edcdd07d8fe2d266ce73b4343 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 18:20:31 -0700 Subject: [PATCH 16/26] fix: fix test src packaging, update integration goldens --- rules_java_gapic/java_gapic.bzl | 2 +- .../goldens/asset/AssetServiceClientTest.java | 30 +- .../logging/ConfigServiceV2ClientTest.java | 2003 +++++++++++++++++ .../logging/LoggingServiceV2ClientTest.java | 575 +++++ .../logging/MetricsServiceV2ClientTest.java | 504 +++++ .../goldens/logging/MockConfigServiceV2.java | 59 + .../logging/MockConfigServiceV2Impl.java | 281 +++ .../goldens/logging/MockLoggingServiceV2.java | 59 + .../logging/MockLoggingServiceV2Impl.java | 135 ++ .../goldens/logging/MockMetricsServiceV2.java | 59 + .../logging/MockMetricsServiceV2Impl.java | 136 ++ .../goldens/redis/CloudRedisClientTest.java | 44 +- 12 files changed, 3850 insertions(+), 37 deletions(-) create mode 100644 test/integration/goldens/logging/ConfigServiceV2ClientTest.java create mode 100644 test/integration/goldens/logging/LoggingServiceV2ClientTest.java create mode 100644 test/integration/goldens/logging/MetricsServiceV2ClientTest.java create mode 100644 test/integration/goldens/logging/MockConfigServiceV2.java create mode 100644 test/integration/goldens/logging/MockConfigServiceV2Impl.java create mode 100644 test/integration/goldens/logging/MockLoggingServiceV2.java create mode 100644 test/integration/goldens/logging/MockLoggingServiceV2Impl.java create mode 100644 test/integration/goldens/logging/MockMetricsServiceV2.java create mode 100644 test/integration/goldens/logging/MockMetricsServiceV2Impl.java diff --git a/rules_java_gapic/java_gapic.bzl b/rules_java_gapic/java_gapic.bzl index 2bbcd1f0b4..aaf83c62e6 100644 --- a/rules_java_gapic/java_gapic.bzl +++ b/rules_java_gapic/java_gapic.bzl @@ -36,7 +36,7 @@ def _java_gapic_postprocess_srcjar_impl(ctx): zip -r $WORKING_DIR/{output_srcjar_name}.srcjar ./ cd $WORKING_DIR/{output_dir_path}/proto/src/main/java zip -r $WORKING_DIR/{output_srcjar_name}-resource-name.srcjar ./ - cd $WORKING_DIR/{output_dir_path}/proto/src/test/java + cd $WORKING_DIR/{output_dir_path}/src/test/java zip -r $WORKING_DIR/{output_srcjar_name}-tests.srcjar ./ cd $WORKING_DIR mv {output_srcjar_name}.srcjar {output_main} diff --git a/test/integration/goldens/asset/AssetServiceClientTest.java b/test/integration/goldens/asset/AssetServiceClientTest.java index 3dc55843af..7c5ab77c2d 100644 --- a/test/integration/goldens/asset/AssetServiceClientTest.java +++ b/test/integration/goldens/asset/AssetServiceClientTest.java @@ -103,7 +103,7 @@ public void exportAssetsTest() throws Exception { ExportAssetsRequest request = ExportAssetsRequest.newBuilder() .setParent(FeedName.ofProjectFeedName("[PROJECT]", "[FEED]").toString()) - .addAllAssetTypes(new ArrayList<>()) + .addAllAssetTypes(new ArrayList()) .setOutputConfig(OutputConfig.newBuilder().build()) .build(); @@ -134,7 +134,7 @@ public void exportAssetsExceptionTest() throws Exception { ExportAssetsRequest request = ExportAssetsRequest.newBuilder() .setParent(FeedName.ofProjectFeedName("[PROJECT]", "[FEED]").toString()) - .addAllAssetTypes(new ArrayList<>()) + .addAllAssetTypes(new ArrayList()) .setOutputConfig(OutputConfig.newBuilder().build()) .build(); client.exportAssetsAsync(request).get(); @@ -149,13 +149,15 @@ public void exportAssetsExceptionTest() throws Exception { @Test public void batchGetAssetsHistoryTest() throws Exception { BatchGetAssetsHistoryResponse expectedResponse = - BatchGetAssetsHistoryResponse.newBuilder().addAllAssets(new ArrayList<>()).build(); + BatchGetAssetsHistoryResponse.newBuilder() + .addAllAssets(new ArrayList()) + .build(); mockAssetService.addResponse(expectedResponse); BatchGetAssetsHistoryRequest request = BatchGetAssetsHistoryRequest.newBuilder() .setParent(FeedName.ofProjectFeedName("[PROJECT]", "[FEED]").toString()) - .addAllAssetNames(new ArrayList<>()) + .addAllAssetNames(new ArrayList()) .setReadTimeWindow(TimeWindow.newBuilder().build()) .build(); @@ -186,7 +188,7 @@ public void batchGetAssetsHistoryExceptionTest() throws Exception { BatchGetAssetsHistoryRequest request = BatchGetAssetsHistoryRequest.newBuilder() .setParent(FeedName.ofProjectFeedName("[PROJECT]", "[FEED]").toString()) - .addAllAssetNames(new ArrayList<>()) + .addAllAssetNames(new ArrayList()) .setReadTimeWindow(TimeWindow.newBuilder().build()) .build(); client.batchGetAssetsHistory(request); @@ -201,8 +203,8 @@ public void createFeedTest() throws Exception { Feed expectedResponse = Feed.newBuilder() .setName(FeedName.ofProjectFeedName("[PROJECT]", "[FEED]").toString()) - .addAllAssetNames(new ArrayList<>()) - .addAllAssetTypes(new ArrayList<>()) + .addAllAssetNames(new ArrayList()) + .addAllAssetTypes(new ArrayList()) .setFeedOutputConfig(FeedOutputConfig.newBuilder().build()) .build(); mockAssetService.addResponse(expectedResponse); @@ -242,8 +244,8 @@ public void getFeedTest() throws Exception { Feed expectedResponse = Feed.newBuilder() .setName(FeedName.ofProjectFeedName("[PROJECT]", "[FEED]").toString()) - .addAllAssetNames(new ArrayList<>()) - .addAllAssetTypes(new ArrayList<>()) + .addAllAssetNames(new ArrayList()) + .addAllAssetTypes(new ArrayList()) .setFeedOutputConfig(FeedOutputConfig.newBuilder().build()) .build(); mockAssetService.addResponse(expectedResponse); @@ -283,8 +285,8 @@ public void getFeedTest2() throws Exception { Feed expectedResponse = Feed.newBuilder() .setName(FeedName.ofProjectFeedName("[PROJECT]", "[FEED]").toString()) - .addAllAssetNames(new ArrayList<>()) - .addAllAssetTypes(new ArrayList<>()) + .addAllAssetNames(new ArrayList()) + .addAllAssetTypes(new ArrayList()) .setFeedOutputConfig(FeedOutputConfig.newBuilder().build()) .build(); mockAssetService.addResponse(expectedResponse); @@ -322,7 +324,7 @@ public void getFeedExceptionTest2() throws Exception { @Test public void listFeedsTest() throws Exception { ListFeedsResponse expectedResponse = - ListFeedsResponse.newBuilder().addAllFeeds(new ArrayList<>()).build(); + ListFeedsResponse.newBuilder().addAllFeeds(new ArrayList()).build(); mockAssetService.addResponse(expectedResponse); String parent = "parent-995424086"; @@ -360,8 +362,8 @@ public void updateFeedTest() throws Exception { Feed expectedResponse = Feed.newBuilder() .setName(FeedName.ofProjectFeedName("[PROJECT]", "[FEED]").toString()) - .addAllAssetNames(new ArrayList<>()) - .addAllAssetTypes(new ArrayList<>()) + .addAllAssetNames(new ArrayList()) + .addAllAssetTypes(new ArrayList()) .setFeedOutputConfig(FeedOutputConfig.newBuilder().build()) .build(); mockAssetService.addResponse(expectedResponse); diff --git a/test/integration/goldens/logging/ConfigServiceV2ClientTest.java b/test/integration/goldens/logging/ConfigServiceV2ClientTest.java new file mode 100644 index 0000000000..3643a06e7d --- /dev/null +++ b/test/integration/goldens/logging/ConfigServiceV2ClientTest.java @@ -0,0 +1,2003 @@ +/* + * 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.logging.v2; + +import static com.google.logging.v2.ConfigServiceV2Client.ListBucketsPagedResponse; +import static com.google.logging.v2.ConfigServiceV2Client.ListExclusionsPagedResponse; +import static com.google.logging.v2.ConfigServiceV2Client.ListSinksPagedResponse; + +import com.google.api.gax.core.NoCredentialsProvider; +import com.google.api.gax.grpc.GaxGrpcProperties; +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 com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.InvalidArgumentException; +import com.google.common.collect.Lists; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.Empty; +import com.google.protobuf.FieldMask; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import javax.annotation.Generated; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +@Generated("by gapic-generator-java") +public class ConfigServiceV2ClientTest { + private static MockServiceHelper mockServiceHelper; + private ConfigServiceV2Client client; + private LocalChannelProvider channelProvider; + private static MockConfigServiceV2 mockConfigServiceV2; + + @BeforeClass + public static void startStaticServer() { + mockConfigServiceV2 = new MockConfigServiceV2(); + mockServiceHelper = + new MockServiceHelper( + UUID.randomUUID().toString(), Arrays.asList(mockConfigServiceV2)); + mockServiceHelper.start(); + } + + @AfterClass + public static void stopServer() { + mockServiceHelper.stop(); + } + + @Before + public void setUp() throws IOException { + mockServiceHelper.reset(); + channelProvider = mockServiceHelper.createChannelProvider(); + ConfigServiceV2Settings settings = + ConfigServiceV2Settings.newBuilder() + .setTransportChannelProvider(channelProvider) + .setCredentialsProvider(NoCredentialsProvider.create()) + .build(); + client = ConfigServiceV2Client.create(settings); + } + + @After + public void tearDown() throws Exception { + client.close(); + } + + @Test + public void listBucketsTest() throws Exception { + LogBucket responsesElement = LogBucket.newBuilder().build(); + ListBucketsResponse expectedResponse = + ListBucketsResponse.newBuilder() + .setNextPageToken("") + .addAllBuckets(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + BillingAccountLocationName parent = + BillingAccountLocationName.of("[BILLING_ACCOUNT]", "[LOCATION]"); + + ListBucketsPagedResponse pagedListResponse = client.listBuckets(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getBucketsList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListBucketsRequest actualRequest = ((ListBucketsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listBucketsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + BillingAccountLocationName parent = + BillingAccountLocationName.of("[BILLING_ACCOUNT]", "[LOCATION]"); + client.listBuckets(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listBucketsTest2() throws Exception { + LogBucket responsesElement = LogBucket.newBuilder().build(); + ListBucketsResponse expectedResponse = + ListBucketsResponse.newBuilder() + .setNextPageToken("") + .addAllBuckets(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + FolderLocationName parent = FolderLocationName.of("[FOLDER]", "[LOCATION]"); + + ListBucketsPagedResponse pagedListResponse = client.listBuckets(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getBucketsList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListBucketsRequest actualRequest = ((ListBucketsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listBucketsExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + FolderLocationName parent = FolderLocationName.of("[FOLDER]", "[LOCATION]"); + client.listBuckets(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listBucketsTest3() throws Exception { + LogBucket responsesElement = LogBucket.newBuilder().build(); + ListBucketsResponse expectedResponse = + ListBucketsResponse.newBuilder() + .setNextPageToken("") + .addAllBuckets(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); + + ListBucketsPagedResponse pagedListResponse = client.listBuckets(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getBucketsList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListBucketsRequest actualRequest = ((ListBucketsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listBucketsExceptionTest3() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); + client.listBuckets(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listBucketsTest4() throws Exception { + LogBucket responsesElement = LogBucket.newBuilder().build(); + ListBucketsResponse expectedResponse = + ListBucketsResponse.newBuilder() + .setNextPageToken("") + .addAllBuckets(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + OrganizationLocationName parent = OrganizationLocationName.of("[ORGANIZATION]", "[LOCATION]"); + + ListBucketsPagedResponse pagedListResponse = client.listBuckets(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getBucketsList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListBucketsRequest actualRequest = ((ListBucketsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listBucketsExceptionTest4() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + OrganizationLocationName parent = OrganizationLocationName.of("[ORGANIZATION]", "[LOCATION]"); + client.listBuckets(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listBucketsTest5() throws Exception { + LogBucket responsesElement = LogBucket.newBuilder().build(); + ListBucketsResponse expectedResponse = + ListBucketsResponse.newBuilder() + .setNextPageToken("") + .addAllBuckets(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String parent = "parent-995424086"; + + ListBucketsPagedResponse pagedListResponse = client.listBuckets(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getBucketsList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListBucketsRequest actualRequest = ((ListBucketsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listBucketsExceptionTest5() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String parent = "parent-995424086"; + client.listBuckets(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getBucketTest() throws Exception { + LogBucket expectedResponse = + LogBucket.newBuilder() + .setName( + LogBucketName.ofProjectLocationBucketName("[PROJECT]", "[LOCATION]", "[BUCKET]") + .toString()) + .setDescription("description-1724546052") + .setRetentionDays(1544391896) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + GetBucketRequest request = + GetBucketRequest.newBuilder() + .setName( + LogBucketName.ofProjectLocationBucketName("[PROJECT]", "[LOCATION]", "[BUCKET]") + .toString()) + .build(); + + LogBucket actualResponse = client.getBucket(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetBucketRequest actualRequest = ((GetBucketRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getName(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getBucketExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + GetBucketRequest request = + GetBucketRequest.newBuilder() + .setName( + LogBucketName.ofProjectLocationBucketName("[PROJECT]", "[LOCATION]", "[BUCKET]") + .toString()) + .build(); + client.getBucket(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateBucketTest() throws Exception { + LogBucket expectedResponse = + LogBucket.newBuilder() + .setName( + LogBucketName.ofProjectLocationBucketName("[PROJECT]", "[LOCATION]", "[BUCKET]") + .toString()) + .setDescription("description-1724546052") + .setRetentionDays(1544391896) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + UpdateBucketRequest request = + UpdateBucketRequest.newBuilder() + .setName( + LogBucketName.ofProjectLocationBucketName("[PROJECT]", "[LOCATION]", "[BUCKET]") + .toString()) + .setBucket(LogBucket.newBuilder().build()) + .build(); + + LogBucket actualResponse = client.updateBucket(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateBucketRequest actualRequest = ((UpdateBucketRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getName(), actualRequest.getName()); + Assert.assertEquals(request.getBucket(), actualRequest.getBucket()); + Assert.assertEquals(request.getUpdateMask(), actualRequest.getUpdateMask()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateBucketExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + UpdateBucketRequest request = + UpdateBucketRequest.newBuilder() + .setName( + LogBucketName.ofProjectLocationBucketName("[PROJECT]", "[LOCATION]", "[BUCKET]") + .toString()) + .setBucket(LogBucket.newBuilder().build()) + .build(); + client.updateBucket(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSinksTest() throws Exception { + LogSink responsesElement = LogSink.newBuilder().build(); + ListSinksResponse expectedResponse = + ListSinksResponse.newBuilder() + .setNextPageToken("") + .addAllSinks(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + BillingAccountName parent = BillingAccountName.of("[BILLING_ACCOUNT]"); + + ListSinksPagedResponse pagedListResponse = client.listSinks(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSinksList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSinksRequest actualRequest = ((ListSinksRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSinksExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + BillingAccountName parent = BillingAccountName.of("[BILLING_ACCOUNT]"); + client.listSinks(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSinksTest2() throws Exception { + LogSink responsesElement = LogSink.newBuilder().build(); + ListSinksResponse expectedResponse = + ListSinksResponse.newBuilder() + .setNextPageToken("") + .addAllSinks(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + FolderName parent = FolderName.of("[FOLDER]"); + + ListSinksPagedResponse pagedListResponse = client.listSinks(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSinksList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSinksRequest actualRequest = ((ListSinksRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSinksExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + FolderName parent = FolderName.of("[FOLDER]"); + client.listSinks(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSinksTest3() throws Exception { + LogSink responsesElement = LogSink.newBuilder().build(); + ListSinksResponse expectedResponse = + ListSinksResponse.newBuilder() + .setNextPageToken("") + .addAllSinks(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); + + ListSinksPagedResponse pagedListResponse = client.listSinks(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSinksList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSinksRequest actualRequest = ((ListSinksRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSinksExceptionTest3() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); + client.listSinks(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSinksTest4() throws Exception { + LogSink responsesElement = LogSink.newBuilder().build(); + ListSinksResponse expectedResponse = + ListSinksResponse.newBuilder() + .setNextPageToken("") + .addAllSinks(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + ProjectName parent = ProjectName.of("[PROJECT]"); + + ListSinksPagedResponse pagedListResponse = client.listSinks(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSinksList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSinksRequest actualRequest = ((ListSinksRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSinksExceptionTest4() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + ProjectName parent = ProjectName.of("[PROJECT]"); + client.listSinks(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSinksTest5() throws Exception { + LogSink responsesElement = LogSink.newBuilder().build(); + ListSinksResponse expectedResponse = + ListSinksResponse.newBuilder() + .setNextPageToken("") + .addAllSinks(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String parent = "parent-995424086"; + + ListSinksPagedResponse pagedListResponse = client.listSinks(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSinksList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSinksRequest actualRequest = ((ListSinksRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSinksExceptionTest5() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String parent = "parent-995424086"; + client.listSinks(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getSinkTest() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + LogSinkName sinkName = LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]"); + + LogSink actualResponse = client.getSink(sinkName); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetSinkRequest actualRequest = ((GetSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(sinkName.toString(), actualRequest.getSinkName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getSinkExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + LogSinkName sinkName = LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]"); + client.getSink(sinkName); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getSinkTest2() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String sinkName = "sink_name-1391757129"; + + LogSink actualResponse = client.getSink(sinkName); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetSinkRequest actualRequest = ((GetSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(sinkName, actualRequest.getSinkName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getSinkExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String sinkName = "sink_name-1391757129"; + client.getSink(sinkName); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSinkTest() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + BillingAccountName parent = BillingAccountName.of("[BILLING_ACCOUNT]"); + LogSink sink = LogSink.newBuilder().build(); + + LogSink actualResponse = client.createSink(parent, sink); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSinkRequest actualRequest = ((CreateSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(sink, actualRequest.getSink()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSinkExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + BillingAccountName parent = BillingAccountName.of("[BILLING_ACCOUNT]"); + LogSink sink = LogSink.newBuilder().build(); + client.createSink(parent, sink); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSinkTest2() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + FolderName parent = FolderName.of("[FOLDER]"); + LogSink sink = LogSink.newBuilder().build(); + + LogSink actualResponse = client.createSink(parent, sink); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSinkRequest actualRequest = ((CreateSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(sink, actualRequest.getSink()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSinkExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + FolderName parent = FolderName.of("[FOLDER]"); + LogSink sink = LogSink.newBuilder().build(); + client.createSink(parent, sink); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSinkTest3() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); + LogSink sink = LogSink.newBuilder().build(); + + LogSink actualResponse = client.createSink(parent, sink); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSinkRequest actualRequest = ((CreateSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(sink, actualRequest.getSink()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSinkExceptionTest3() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); + LogSink sink = LogSink.newBuilder().build(); + client.createSink(parent, sink); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSinkTest4() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + ProjectName parent = ProjectName.of("[PROJECT]"); + LogSink sink = LogSink.newBuilder().build(); + + LogSink actualResponse = client.createSink(parent, sink); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSinkRequest actualRequest = ((CreateSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(sink, actualRequest.getSink()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSinkExceptionTest4() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + ProjectName parent = ProjectName.of("[PROJECT]"); + LogSink sink = LogSink.newBuilder().build(); + client.createSink(parent, sink); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSinkTest5() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String parent = "parent-995424086"; + LogSink sink = LogSink.newBuilder().build(); + + LogSink actualResponse = client.createSink(parent, sink); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSinkRequest actualRequest = ((CreateSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertEquals(sink, actualRequest.getSink()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSinkExceptionTest5() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String parent = "parent-995424086"; + LogSink sink = LogSink.newBuilder().build(); + client.createSink(parent, sink); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateSinkTest() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + LogSinkName sinkName = LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]"); + LogSink sink = LogSink.newBuilder().build(); + + LogSink actualResponse = client.updateSink(sinkName, sink); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateSinkRequest actualRequest = ((UpdateSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(sinkName.toString(), actualRequest.getSinkName()); + Assert.assertEquals(sink, actualRequest.getSink()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateSinkExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + LogSinkName sinkName = LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]"); + LogSink sink = LogSink.newBuilder().build(); + client.updateSink(sinkName, sink); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateSinkTest2() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String sinkName = "sink_name-1391757129"; + LogSink sink = LogSink.newBuilder().build(); + + LogSink actualResponse = client.updateSink(sinkName, sink); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateSinkRequest actualRequest = ((UpdateSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(sinkName, actualRequest.getSinkName()); + Assert.assertEquals(sink, actualRequest.getSink()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateSinkExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String sinkName = "sink_name-1391757129"; + LogSink sink = LogSink.newBuilder().build(); + client.updateSink(sinkName, sink); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateSinkTest3() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + LogSinkName sinkName = LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]"); + LogSink sink = LogSink.newBuilder().build(); + FieldMask updateMask = FieldMask.newBuilder().build(); + + LogSink actualResponse = client.updateSink(sinkName, sink, updateMask); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateSinkRequest actualRequest = ((UpdateSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(sinkName.toString(), actualRequest.getSinkName()); + Assert.assertEquals(sink, actualRequest.getSink()); + Assert.assertEquals(updateMask, actualRequest.getUpdateMask()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateSinkExceptionTest3() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + LogSinkName sinkName = LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]"); + LogSink sink = LogSink.newBuilder().build(); + FieldMask updateMask = FieldMask.newBuilder().build(); + client.updateSink(sinkName, sink, updateMask); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateSinkTest4() throws Exception { + LogSink expectedResponse = + LogSink.newBuilder() + .setName(LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]").toString()) + .setDestination("destination-1429847026") + .setFilter("filter-1274492040") + .setDescription("description-1724546052") + .setDisabled(true) + .setWriterIdentity("writer_identity775638794") + .setIncludeChildren(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String sinkName = "sink_name-1391757129"; + LogSink sink = LogSink.newBuilder().build(); + FieldMask updateMask = FieldMask.newBuilder().build(); + + LogSink actualResponse = client.updateSink(sinkName, sink, updateMask); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateSinkRequest actualRequest = ((UpdateSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(sinkName, actualRequest.getSinkName()); + Assert.assertEquals(sink, actualRequest.getSink()); + Assert.assertEquals(updateMask, actualRequest.getUpdateMask()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateSinkExceptionTest4() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String sinkName = "sink_name-1391757129"; + LogSink sink = LogSink.newBuilder().build(); + FieldMask updateMask = FieldMask.newBuilder().build(); + client.updateSink(sinkName, sink, updateMask); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteSinkTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockConfigServiceV2.addResponse(expectedResponse); + + LogSinkName sinkName = LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]"); + + Empty actualResponse = client.deleteSink(sinkName); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteSinkRequest actualRequest = ((DeleteSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(sinkName.toString(), actualRequest.getSinkName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteSinkExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + LogSinkName sinkName = LogSinkName.ofProjectSinkName("[PROJECT]", "[SINK]"); + client.deleteSink(sinkName); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteSinkTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String sinkName = "sink_name-1391757129"; + + Empty actualResponse = client.deleteSink(sinkName); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteSinkRequest actualRequest = ((DeleteSinkRequest) actualRequests.get(0)); + + Assert.assertEquals(sinkName, actualRequest.getSinkName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteSinkExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String sinkName = "sink_name-1391757129"; + client.deleteSink(sinkName); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listExclusionsTest() throws Exception { + LogExclusion responsesElement = LogExclusion.newBuilder().build(); + ListExclusionsResponse expectedResponse = + ListExclusionsResponse.newBuilder() + .setNextPageToken("") + .addAllExclusions(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + BillingAccountName parent = BillingAccountName.of("[BILLING_ACCOUNT]"); + + ListExclusionsPagedResponse pagedListResponse = client.listExclusions(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getExclusionsList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListExclusionsRequest actualRequest = ((ListExclusionsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listExclusionsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + BillingAccountName parent = BillingAccountName.of("[BILLING_ACCOUNT]"); + client.listExclusions(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listExclusionsTest2() throws Exception { + LogExclusion responsesElement = LogExclusion.newBuilder().build(); + ListExclusionsResponse expectedResponse = + ListExclusionsResponse.newBuilder() + .setNextPageToken("") + .addAllExclusions(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + FolderName parent = FolderName.of("[FOLDER]"); + + ListExclusionsPagedResponse pagedListResponse = client.listExclusions(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getExclusionsList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListExclusionsRequest actualRequest = ((ListExclusionsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listExclusionsExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + FolderName parent = FolderName.of("[FOLDER]"); + client.listExclusions(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listExclusionsTest3() throws Exception { + LogExclusion responsesElement = LogExclusion.newBuilder().build(); + ListExclusionsResponse expectedResponse = + ListExclusionsResponse.newBuilder() + .setNextPageToken("") + .addAllExclusions(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); + + ListExclusionsPagedResponse pagedListResponse = client.listExclusions(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getExclusionsList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListExclusionsRequest actualRequest = ((ListExclusionsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listExclusionsExceptionTest3() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); + client.listExclusions(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listExclusionsTest4() throws Exception { + LogExclusion responsesElement = LogExclusion.newBuilder().build(); + ListExclusionsResponse expectedResponse = + ListExclusionsResponse.newBuilder() + .setNextPageToken("") + .addAllExclusions(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + ProjectName parent = ProjectName.of("[PROJECT]"); + + ListExclusionsPagedResponse pagedListResponse = client.listExclusions(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getExclusionsList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListExclusionsRequest actualRequest = ((ListExclusionsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listExclusionsExceptionTest4() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + ProjectName parent = ProjectName.of("[PROJECT]"); + client.listExclusions(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listExclusionsTest5() throws Exception { + LogExclusion responsesElement = LogExclusion.newBuilder().build(); + ListExclusionsResponse expectedResponse = + ListExclusionsResponse.newBuilder() + .setNextPageToken("") + .addAllExclusions(Arrays.asList(responsesElement)) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String parent = "parent-995424086"; + + ListExclusionsPagedResponse pagedListResponse = client.listExclusions(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getExclusionsList().get(0), resources.get(0)); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListExclusionsRequest actualRequest = ((ListExclusionsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listExclusionsExceptionTest5() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String parent = "parent-995424086"; + client.listExclusions(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getExclusionTest() throws Exception { + LogExclusion expectedResponse = + LogExclusion.newBuilder() + .setName(LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setDisabled(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + LogExclusionName name = LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]"); + + LogExclusion actualResponse = client.getExclusion(name); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetExclusionRequest actualRequest = ((GetExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getExclusionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + LogExclusionName name = LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]"); + client.getExclusion(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getExclusionTest2() throws Exception { + LogExclusion expectedResponse = + LogExclusion.newBuilder() + .setName(LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setDisabled(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String name = "name3373707"; + + LogExclusion actualResponse = client.getExclusion(name); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetExclusionRequest actualRequest = ((GetExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getExclusionExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String name = "name3373707"; + client.getExclusion(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createExclusionTest() throws Exception { + LogExclusion expectedResponse = + LogExclusion.newBuilder() + .setName(LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setDisabled(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + BillingAccountName parent = BillingAccountName.of("[BILLING_ACCOUNT]"); + LogExclusion exclusion = LogExclusion.newBuilder().build(); + + LogExclusion actualResponse = client.createExclusion(parent, exclusion); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateExclusionRequest actualRequest = ((CreateExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(exclusion, actualRequest.getExclusion()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createExclusionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + BillingAccountName parent = BillingAccountName.of("[BILLING_ACCOUNT]"); + LogExclusion exclusion = LogExclusion.newBuilder().build(); + client.createExclusion(parent, exclusion); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createExclusionTest2() throws Exception { + LogExclusion expectedResponse = + LogExclusion.newBuilder() + .setName(LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setDisabled(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + FolderName parent = FolderName.of("[FOLDER]"); + LogExclusion exclusion = LogExclusion.newBuilder().build(); + + LogExclusion actualResponse = client.createExclusion(parent, exclusion); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateExclusionRequest actualRequest = ((CreateExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(exclusion, actualRequest.getExclusion()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createExclusionExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + FolderName parent = FolderName.of("[FOLDER]"); + LogExclusion exclusion = LogExclusion.newBuilder().build(); + client.createExclusion(parent, exclusion); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createExclusionTest3() throws Exception { + LogExclusion expectedResponse = + LogExclusion.newBuilder() + .setName(LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setDisabled(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); + LogExclusion exclusion = LogExclusion.newBuilder().build(); + + LogExclusion actualResponse = client.createExclusion(parent, exclusion); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateExclusionRequest actualRequest = ((CreateExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(exclusion, actualRequest.getExclusion()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createExclusionExceptionTest3() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); + LogExclusion exclusion = LogExclusion.newBuilder().build(); + client.createExclusion(parent, exclusion); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createExclusionTest4() throws Exception { + LogExclusion expectedResponse = + LogExclusion.newBuilder() + .setName(LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setDisabled(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + ProjectName parent = ProjectName.of("[PROJECT]"); + LogExclusion exclusion = LogExclusion.newBuilder().build(); + + LogExclusion actualResponse = client.createExclusion(parent, exclusion); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateExclusionRequest actualRequest = ((CreateExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(exclusion, actualRequest.getExclusion()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createExclusionExceptionTest4() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + ProjectName parent = ProjectName.of("[PROJECT]"); + LogExclusion exclusion = LogExclusion.newBuilder().build(); + client.createExclusion(parent, exclusion); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createExclusionTest5() throws Exception { + LogExclusion expectedResponse = + LogExclusion.newBuilder() + .setName(LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setDisabled(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String parent = "parent-995424086"; + LogExclusion exclusion = LogExclusion.newBuilder().build(); + + LogExclusion actualResponse = client.createExclusion(parent, exclusion); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateExclusionRequest actualRequest = ((CreateExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertEquals(exclusion, actualRequest.getExclusion()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createExclusionExceptionTest5() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String parent = "parent-995424086"; + LogExclusion exclusion = LogExclusion.newBuilder().build(); + client.createExclusion(parent, exclusion); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateExclusionTest() throws Exception { + LogExclusion expectedResponse = + LogExclusion.newBuilder() + .setName(LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setDisabled(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + LogExclusionName name = LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]"); + LogExclusion exclusion = LogExclusion.newBuilder().build(); + FieldMask updateMask = FieldMask.newBuilder().build(); + + LogExclusion actualResponse = client.updateExclusion(name, exclusion, updateMask); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateExclusionRequest actualRequest = ((UpdateExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertEquals(exclusion, actualRequest.getExclusion()); + Assert.assertEquals(updateMask, actualRequest.getUpdateMask()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateExclusionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + LogExclusionName name = LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]"); + LogExclusion exclusion = LogExclusion.newBuilder().build(); + FieldMask updateMask = FieldMask.newBuilder().build(); + client.updateExclusion(name, exclusion, updateMask); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateExclusionTest2() throws Exception { + LogExclusion expectedResponse = + LogExclusion.newBuilder() + .setName(LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setDisabled(true) + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String name = "name3373707"; + LogExclusion exclusion = LogExclusion.newBuilder().build(); + FieldMask updateMask = FieldMask.newBuilder().build(); + + LogExclusion actualResponse = client.updateExclusion(name, exclusion, updateMask); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateExclusionRequest actualRequest = ((UpdateExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertEquals(exclusion, actualRequest.getExclusion()); + Assert.assertEquals(updateMask, actualRequest.getUpdateMask()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateExclusionExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String name = "name3373707"; + LogExclusion exclusion = LogExclusion.newBuilder().build(); + FieldMask updateMask = FieldMask.newBuilder().build(); + client.updateExclusion(name, exclusion, updateMask); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteExclusionTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockConfigServiceV2.addResponse(expectedResponse); + + LogExclusionName name = LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]"); + + Empty actualResponse = client.deleteExclusion(name); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteExclusionRequest actualRequest = ((DeleteExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteExclusionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + LogExclusionName name = LogExclusionName.ofProjectExclusionName("[PROJECT]", "[EXCLUSION]"); + client.deleteExclusion(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteExclusionTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockConfigServiceV2.addResponse(expectedResponse); + + String name = "name3373707"; + + Empty actualResponse = client.deleteExclusion(name); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteExclusionRequest actualRequest = ((DeleteExclusionRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteExclusionExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + String name = "name3373707"; + client.deleteExclusion(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getCmekSettingsTest() throws Exception { + CmekSettings expectedResponse = + CmekSettings.newBuilder() + .setName(CmekSettingsName.ofProjectName("[PROJECT]").toString()) + .setKmsKeyName("kms_key_name2094986649") + .setServiceAccountId("service_account_id-111486921") + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + GetCmekSettingsRequest request = + GetCmekSettingsRequest.newBuilder() + .setName(CmekSettingsName.ofProjectName("[PROJECT]").toString()) + .build(); + + CmekSettings actualResponse = client.getCmekSettings(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetCmekSettingsRequest actualRequest = ((GetCmekSettingsRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getName(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getCmekSettingsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + GetCmekSettingsRequest request = + GetCmekSettingsRequest.newBuilder() + .setName(CmekSettingsName.ofProjectName("[PROJECT]").toString()) + .build(); + client.getCmekSettings(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateCmekSettingsTest() throws Exception { + CmekSettings expectedResponse = + CmekSettings.newBuilder() + .setName(CmekSettingsName.ofProjectName("[PROJECT]").toString()) + .setKmsKeyName("kms_key_name2094986649") + .setServiceAccountId("service_account_id-111486921") + .build(); + mockConfigServiceV2.addResponse(expectedResponse); + + UpdateCmekSettingsRequest request = + UpdateCmekSettingsRequest.newBuilder() + .setName("name3373707") + .setCmekSettings(CmekSettings.newBuilder().build()) + .build(); + + CmekSettings actualResponse = client.updateCmekSettings(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockConfigServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateCmekSettingsRequest actualRequest = ((UpdateCmekSettingsRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getName(), actualRequest.getName()); + Assert.assertEquals(request.getCmekSettings(), actualRequest.getCmekSettings()); + Assert.assertEquals(request.getUpdateMask(), actualRequest.getUpdateMask()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateCmekSettingsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockConfigServiceV2.addException(exception); + + try { + UpdateCmekSettingsRequest request = + UpdateCmekSettingsRequest.newBuilder() + .setName("name3373707") + .setCmekSettings(CmekSettings.newBuilder().build()) + .build(); + client.updateCmekSettings(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } +} diff --git a/test/integration/goldens/logging/LoggingServiceV2ClientTest.java b/test/integration/goldens/logging/LoggingServiceV2ClientTest.java new file mode 100644 index 0000000000..a3a8022c52 --- /dev/null +++ b/test/integration/goldens/logging/LoggingServiceV2ClientTest.java @@ -0,0 +1,575 @@ +/* + * 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.logging.v2; + +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.MonitoredResource; +import com.google.api.MonitoredResourceDescriptor; +import com.google.api.gax.core.NoCredentialsProvider; +import com.google.api.gax.grpc.GaxGrpcProperties; +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 com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.InvalidArgumentException; +import com.google.common.collect.Lists; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.Empty; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.annotation.Generated; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +@Generated("by gapic-generator-java") +public class LoggingServiceV2ClientTest { + private static MockServiceHelper mockServiceHelper; + private static MockLoggingServiceV2 mockLoggingServiceV2; + private LoggingServiceV2Client client; + private LocalChannelProvider channelProvider; + + @BeforeClass + public static void startStaticServer() { + mockLoggingServiceV2 = new MockLoggingServiceV2(); + mockServiceHelper = + new MockServiceHelper( + UUID.randomUUID().toString(), Arrays.asList(mockLoggingServiceV2)); + mockServiceHelper.start(); + } + + @AfterClass + public static void stopServer() { + mockServiceHelper.stop(); + } + + @Before + public void setUp() throws IOException { + mockServiceHelper.reset(); + channelProvider = mockServiceHelper.createChannelProvider(); + LoggingServiceV2Settings settings = + LoggingServiceV2Settings.newBuilder() + .setTransportChannelProvider(channelProvider) + .setCredentialsProvider(NoCredentialsProvider.create()) + .build(); + client = LoggingServiceV2Client.create(settings); + } + + @After + public void tearDown() throws Exception { + client.close(); + } + + @Test + public void deleteLogTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + LogName logName = LogName.ofProjectLogName("[PROJECT]", "[LOG]"); + + Empty actualResponse = client.deleteLog(logName); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteLogRequest actualRequest = ((DeleteLogRequest) actualRequests.get(0)); + + Assert.assertEquals(logName.toString(), actualRequest.getLogName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteLogExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + LogName logName = LogName.ofProjectLogName("[PROJECT]", "[LOG]"); + client.deleteLog(logName); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteLogTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + String logName = "log_name2013526694"; + + Empty actualResponse = client.deleteLog(logName); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteLogRequest actualRequest = ((DeleteLogRequest) actualRequests.get(0)); + + Assert.assertEquals(logName, actualRequest.getLogName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteLogExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + String logName = "log_name2013526694"; + client.deleteLog(logName); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void writeLogEntriesTest() throws Exception { + WriteLogEntriesResponse expectedResponse = WriteLogEntriesResponse.newBuilder().build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + LogName logName = LogName.ofProjectLogName("[PROJECT]", "[LOG]"); + MonitoredResource resource = MonitoredResource.newBuilder().build(); + Map labels = new HashMap<>(); + List entries = new ArrayList<>(); + + WriteLogEntriesResponse actualResponse = + client.writeLogEntries(logName, resource, labels, entries); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + WriteLogEntriesRequest actualRequest = ((WriteLogEntriesRequest) actualRequests.get(0)); + + Assert.assertEquals(logName.toString(), actualRequest.getLogName()); + Assert.assertEquals(resource, actualRequest.getResource()); + Assert.assertEquals(labels, actualRequest.getLabelsMap()); + Assert.assertEquals(entries, actualRequest.getEntriesList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void writeLogEntriesExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + LogName logName = LogName.ofProjectLogName("[PROJECT]", "[LOG]"); + MonitoredResource resource = MonitoredResource.newBuilder().build(); + Map labels = new HashMap<>(); + List entries = new ArrayList<>(); + client.writeLogEntries(logName, resource, labels, entries); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void writeLogEntriesTest2() throws Exception { + WriteLogEntriesResponse expectedResponse = WriteLogEntriesResponse.newBuilder().build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + String logName = "log_name2013526694"; + MonitoredResource resource = MonitoredResource.newBuilder().build(); + Map labels = new HashMap<>(); + List entries = new ArrayList<>(); + + WriteLogEntriesResponse actualResponse = + client.writeLogEntries(logName, resource, labels, entries); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + WriteLogEntriesRequest actualRequest = ((WriteLogEntriesRequest) actualRequests.get(0)); + + Assert.assertEquals(logName, actualRequest.getLogName()); + Assert.assertEquals(resource, actualRequest.getResource()); + Assert.assertEquals(labels, actualRequest.getLabelsMap()); + Assert.assertEquals(entries, actualRequest.getEntriesList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void writeLogEntriesExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + String logName = "log_name2013526694"; + MonitoredResource resource = MonitoredResource.newBuilder().build(); + Map labels = new HashMap<>(); + List entries = new ArrayList<>(); + client.writeLogEntries(logName, resource, labels, entries); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listLogEntriesTest() throws Exception { + LogEntry responsesElement = LogEntry.newBuilder().build(); + ListLogEntriesResponse expectedResponse = + ListLogEntriesResponse.newBuilder() + .setNextPageToken("") + .addAllEntries(Arrays.asList(responsesElement)) + .build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + List resourceNames = new ArrayList<>(); + String filter = "filter-1274492040"; + String orderBy = "order_by1234304744"; + + ListLogEntriesPagedResponse pagedListResponse = + client.listLogEntries(resourceNames, filter, orderBy); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getEntriesList().get(0), resources.get(0)); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListLogEntriesRequest actualRequest = ((ListLogEntriesRequest) actualRequests.get(0)); + + Assert.assertEquals(resourceNames, actualRequest.getResourceNamesList()); + Assert.assertEquals(filter, actualRequest.getFilter()); + Assert.assertEquals(orderBy, actualRequest.getOrderBy()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listLogEntriesExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + List resourceNames = new ArrayList<>(); + String filter = "filter-1274492040"; + String orderBy = "order_by1234304744"; + client.listLogEntries(resourceNames, filter, orderBy); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listMonitoredResourceDescriptorsTest() throws Exception { + MonitoredResourceDescriptor responsesElement = MonitoredResourceDescriptor.newBuilder().build(); + ListMonitoredResourceDescriptorsResponse expectedResponse = + ListMonitoredResourceDescriptorsResponse.newBuilder() + .setNextPageToken("") + .addAllResourceDescriptors(Arrays.asList(responsesElement)) + .build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + ListMonitoredResourceDescriptorsRequest request = + ListMonitoredResourceDescriptorsRequest.newBuilder() + .setPageSize(883849137) + .setPageToken("page_token1630607433") + .build(); + + ListMonitoredResourceDescriptorsPagedResponse pagedListResponse = + client.listMonitoredResourceDescriptors(request); + + List resources = + Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getResourceDescriptorsList().get(0), resources.get(0)); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListMonitoredResourceDescriptorsRequest actualRequest = + ((ListMonitoredResourceDescriptorsRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getPageSize(), actualRequest.getPageSize()); + Assert.assertEquals(request.getPageToken(), actualRequest.getPageToken()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listMonitoredResourceDescriptorsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + ListMonitoredResourceDescriptorsRequest request = + ListMonitoredResourceDescriptorsRequest.newBuilder() + .setPageSize(883849137) + .setPageToken("page_token1630607433") + .build(); + client.listMonitoredResourceDescriptors(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listLogsTest() throws Exception { + String responsesElement = "responsesElement-318365110"; + ListLogsResponse expectedResponse = + ListLogsResponse.newBuilder() + .setNextPageToken("") + .addAllLogNames(Arrays.asList(responsesElement)) + .build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + BillingAccountName parent = BillingAccountName.of("[BILLING_ACCOUNT]"); + + ListLogsPagedResponse pagedListResponse = client.listLogs(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getLogNamesList().get(0), resources.get(0)); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListLogsRequest actualRequest = ((ListLogsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listLogsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + BillingAccountName parent = BillingAccountName.of("[BILLING_ACCOUNT]"); + client.listLogs(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listLogsTest2() throws Exception { + String responsesElement = "responsesElement-318365110"; + ListLogsResponse expectedResponse = + ListLogsResponse.newBuilder() + .setNextPageToken("") + .addAllLogNames(Arrays.asList(responsesElement)) + .build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + FolderName parent = FolderName.of("[FOLDER]"); + + ListLogsPagedResponse pagedListResponse = client.listLogs(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getLogNamesList().get(0), resources.get(0)); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListLogsRequest actualRequest = ((ListLogsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listLogsExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + FolderName parent = FolderName.of("[FOLDER]"); + client.listLogs(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listLogsTest3() throws Exception { + String responsesElement = "responsesElement-318365110"; + ListLogsResponse expectedResponse = + ListLogsResponse.newBuilder() + .setNextPageToken("") + .addAllLogNames(Arrays.asList(responsesElement)) + .build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); + + ListLogsPagedResponse pagedListResponse = client.listLogs(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getLogNamesList().get(0), resources.get(0)); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListLogsRequest actualRequest = ((ListLogsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listLogsExceptionTest3() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); + client.listLogs(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listLogsTest4() throws Exception { + String responsesElement = "responsesElement-318365110"; + ListLogsResponse expectedResponse = + ListLogsResponse.newBuilder() + .setNextPageToken("") + .addAllLogNames(Arrays.asList(responsesElement)) + .build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + ProjectName parent = ProjectName.of("[PROJECT]"); + + ListLogsPagedResponse pagedListResponse = client.listLogs(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getLogNamesList().get(0), resources.get(0)); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListLogsRequest actualRequest = ((ListLogsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listLogsExceptionTest4() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + ProjectName parent = ProjectName.of("[PROJECT]"); + client.listLogs(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listLogsTest5() throws Exception { + String responsesElement = "responsesElement-318365110"; + ListLogsResponse expectedResponse = + ListLogsResponse.newBuilder() + .setNextPageToken("") + .addAllLogNames(Arrays.asList(responsesElement)) + .build(); + mockLoggingServiceV2.addResponse(expectedResponse); + + String parent = "parent-995424086"; + + ListLogsPagedResponse pagedListResponse = client.listLogs(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getLogNamesList().get(0), resources.get(0)); + + List actualRequests = mockLoggingServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListLogsRequest actualRequest = ((ListLogsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listLogsExceptionTest5() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockLoggingServiceV2.addException(exception); + + try { + String parent = "parent-995424086"; + client.listLogs(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } +} diff --git a/test/integration/goldens/logging/MetricsServiceV2ClientTest.java b/test/integration/goldens/logging/MetricsServiceV2ClientTest.java new file mode 100644 index 0000000000..a8dd5fa867 --- /dev/null +++ b/test/integration/goldens/logging/MetricsServiceV2ClientTest.java @@ -0,0 +1,504 @@ +/* + * 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.logging.v2; + +import static com.google.logging.v2.MetricsServiceV2Client.ListLogMetricsPagedResponse; + +import com.google.api.gax.core.NoCredentialsProvider; +import com.google.api.gax.grpc.GaxGrpcProperties; +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 com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.InvalidArgumentException; +import com.google.common.collect.Lists; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.Empty; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; +import javax.annotation.Generated; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +@Generated("by gapic-generator-java") +public class MetricsServiceV2ClientTest { + private static MockServiceHelper mockServiceHelper; + private MetricsServiceV2Client client; + private static MockMetricsServiceV2 mockMetricsServiceV2; + private LocalChannelProvider channelProvider; + + @BeforeClass + public static void startStaticServer() { + mockMetricsServiceV2 = new MockMetricsServiceV2(); + mockServiceHelper = + new MockServiceHelper( + UUID.randomUUID().toString(), Arrays.asList(mockMetricsServiceV2)); + mockServiceHelper.start(); + } + + @AfterClass + public static void stopServer() { + mockServiceHelper.stop(); + } + + @Before + public void setUp() throws IOException { + mockServiceHelper.reset(); + channelProvider = mockServiceHelper.createChannelProvider(); + MetricsServiceV2Settings settings = + MetricsServiceV2Settings.newBuilder() + .setTransportChannelProvider(channelProvider) + .setCredentialsProvider(NoCredentialsProvider.create()) + .build(); + client = MetricsServiceV2Client.create(settings); + } + + @After + public void tearDown() throws Exception { + client.close(); + } + + @Test + public void listLogMetricsTest() throws Exception { + LogMetric responsesElement = LogMetric.newBuilder().build(); + ListLogMetricsResponse expectedResponse = + ListLogMetricsResponse.newBuilder() + .setNextPageToken("") + .addAllMetrics(Arrays.asList(responsesElement)) + .build(); + mockMetricsServiceV2.addResponse(expectedResponse); + + ProjectName parent = ProjectName.of("[PROJECT]"); + + ListLogMetricsPagedResponse pagedListResponse = client.listLogMetrics(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getMetricsList().get(0), resources.get(0)); + + List actualRequests = mockMetricsServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListLogMetricsRequest actualRequest = ((ListLogMetricsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listLogMetricsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockMetricsServiceV2.addException(exception); + + try { + ProjectName parent = ProjectName.of("[PROJECT]"); + client.listLogMetrics(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listLogMetricsTest2() throws Exception { + LogMetric responsesElement = LogMetric.newBuilder().build(); + ListLogMetricsResponse expectedResponse = + ListLogMetricsResponse.newBuilder() + .setNextPageToken("") + .addAllMetrics(Arrays.asList(responsesElement)) + .build(); + mockMetricsServiceV2.addResponse(expectedResponse); + + String parent = "parent-995424086"; + + ListLogMetricsPagedResponse pagedListResponse = client.listLogMetrics(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getMetricsList().get(0), resources.get(0)); + + List actualRequests = mockMetricsServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListLogMetricsRequest actualRequest = ((ListLogMetricsRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listLogMetricsExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockMetricsServiceV2.addException(exception); + + try { + String parent = "parent-995424086"; + client.listLogMetrics(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getLogMetricTest() throws Exception { + LogMetric expectedResponse = + LogMetric.newBuilder() + .setName(LogMetricName.of("[PROJECT]", "[METRIC]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setValueExtractor("value_extractor2047672534") + .putAllLabelExtractors(new HashMap()) + .build(); + mockMetricsServiceV2.addResponse(expectedResponse); + + LogMetricName metricName = LogMetricName.of("[PROJECT]", "[METRIC]"); + + LogMetric actualResponse = client.getLogMetric(metricName); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockMetricsServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetLogMetricRequest actualRequest = ((GetLogMetricRequest) actualRequests.get(0)); + + Assert.assertEquals(metricName.toString(), actualRequest.getMetricName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getLogMetricExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockMetricsServiceV2.addException(exception); + + try { + LogMetricName metricName = LogMetricName.of("[PROJECT]", "[METRIC]"); + client.getLogMetric(metricName); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getLogMetricTest2() throws Exception { + LogMetric expectedResponse = + LogMetric.newBuilder() + .setName(LogMetricName.of("[PROJECT]", "[METRIC]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setValueExtractor("value_extractor2047672534") + .putAllLabelExtractors(new HashMap()) + .build(); + mockMetricsServiceV2.addResponse(expectedResponse); + + String metricName = "metric_name-1737602118"; + + LogMetric actualResponse = client.getLogMetric(metricName); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockMetricsServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetLogMetricRequest actualRequest = ((GetLogMetricRequest) actualRequests.get(0)); + + Assert.assertEquals(metricName, actualRequest.getMetricName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getLogMetricExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockMetricsServiceV2.addException(exception); + + try { + String metricName = "metric_name-1737602118"; + client.getLogMetric(metricName); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createLogMetricTest() throws Exception { + LogMetric expectedResponse = + LogMetric.newBuilder() + .setName(LogMetricName.of("[PROJECT]", "[METRIC]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setValueExtractor("value_extractor2047672534") + .putAllLabelExtractors(new HashMap()) + .build(); + mockMetricsServiceV2.addResponse(expectedResponse); + + ProjectName parent = ProjectName.of("[PROJECT]"); + LogMetric metric = LogMetric.newBuilder().build(); + + LogMetric actualResponse = client.createLogMetric(parent, metric); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockMetricsServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateLogMetricRequest actualRequest = ((CreateLogMetricRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(metric, actualRequest.getMetric()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createLogMetricExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockMetricsServiceV2.addException(exception); + + try { + ProjectName parent = ProjectName.of("[PROJECT]"); + LogMetric metric = LogMetric.newBuilder().build(); + client.createLogMetric(parent, metric); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createLogMetricTest2() throws Exception { + LogMetric expectedResponse = + LogMetric.newBuilder() + .setName(LogMetricName.of("[PROJECT]", "[METRIC]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setValueExtractor("value_extractor2047672534") + .putAllLabelExtractors(new HashMap()) + .build(); + mockMetricsServiceV2.addResponse(expectedResponse); + + String parent = "parent-995424086"; + LogMetric metric = LogMetric.newBuilder().build(); + + LogMetric actualResponse = client.createLogMetric(parent, metric); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockMetricsServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateLogMetricRequest actualRequest = ((CreateLogMetricRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertEquals(metric, actualRequest.getMetric()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createLogMetricExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockMetricsServiceV2.addException(exception); + + try { + String parent = "parent-995424086"; + LogMetric metric = LogMetric.newBuilder().build(); + client.createLogMetric(parent, metric); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateLogMetricTest() throws Exception { + LogMetric expectedResponse = + LogMetric.newBuilder() + .setName(LogMetricName.of("[PROJECT]", "[METRIC]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setValueExtractor("value_extractor2047672534") + .putAllLabelExtractors(new HashMap()) + .build(); + mockMetricsServiceV2.addResponse(expectedResponse); + + LogMetricName metricName = LogMetricName.of("[PROJECT]", "[METRIC]"); + LogMetric metric = LogMetric.newBuilder().build(); + + LogMetric actualResponse = client.updateLogMetric(metricName, metric); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockMetricsServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateLogMetricRequest actualRequest = ((UpdateLogMetricRequest) actualRequests.get(0)); + + Assert.assertEquals(metricName.toString(), actualRequest.getMetricName()); + Assert.assertEquals(metric, actualRequest.getMetric()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateLogMetricExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockMetricsServiceV2.addException(exception); + + try { + LogMetricName metricName = LogMetricName.of("[PROJECT]", "[METRIC]"); + LogMetric metric = LogMetric.newBuilder().build(); + client.updateLogMetric(metricName, metric); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateLogMetricTest2() throws Exception { + LogMetric expectedResponse = + LogMetric.newBuilder() + .setName(LogMetricName.of("[PROJECT]", "[METRIC]").toString()) + .setDescription("description-1724546052") + .setFilter("filter-1274492040") + .setValueExtractor("value_extractor2047672534") + .putAllLabelExtractors(new HashMap()) + .build(); + mockMetricsServiceV2.addResponse(expectedResponse); + + String metricName = "metric_name-1737602118"; + LogMetric metric = LogMetric.newBuilder().build(); + + LogMetric actualResponse = client.updateLogMetric(metricName, metric); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockMetricsServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateLogMetricRequest actualRequest = ((UpdateLogMetricRequest) actualRequests.get(0)); + + Assert.assertEquals(metricName, actualRequest.getMetricName()); + Assert.assertEquals(metric, actualRequest.getMetric()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateLogMetricExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockMetricsServiceV2.addException(exception); + + try { + String metricName = "metric_name-1737602118"; + LogMetric metric = LogMetric.newBuilder().build(); + client.updateLogMetric(metricName, metric); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteLogMetricTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockMetricsServiceV2.addResponse(expectedResponse); + + LogMetricName metricName = LogMetricName.of("[PROJECT]", "[METRIC]"); + + Empty actualResponse = client.deleteLogMetric(metricName); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockMetricsServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteLogMetricRequest actualRequest = ((DeleteLogMetricRequest) actualRequests.get(0)); + + Assert.assertEquals(metricName.toString(), actualRequest.getMetricName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteLogMetricExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockMetricsServiceV2.addException(exception); + + try { + LogMetricName metricName = LogMetricName.of("[PROJECT]", "[METRIC]"); + client.deleteLogMetric(metricName); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteLogMetricTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockMetricsServiceV2.addResponse(expectedResponse); + + String metricName = "metric_name-1737602118"; + + Empty actualResponse = client.deleteLogMetric(metricName); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockMetricsServiceV2.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteLogMetricRequest actualRequest = ((DeleteLogMetricRequest) actualRequests.get(0)); + + Assert.assertEquals(metricName, actualRequest.getMetricName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteLogMetricExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockMetricsServiceV2.addException(exception); + + try { + String metricName = "metric_name-1737602118"; + client.deleteLogMetric(metricName); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } +} diff --git a/test/integration/goldens/logging/MockConfigServiceV2.java b/test/integration/goldens/logging/MockConfigServiceV2.java new file mode 100644 index 0000000000..8ce4ce6170 --- /dev/null +++ b/test/integration/goldens/logging/MockConfigServiceV2.java @@ -0,0 +1,59 @@ +/* + * 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.logging.v2; + +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 MockConfigServiceV2 implements MockGrpcService { + private final MockConfigServiceV2Impl serviceImpl; + + public MockConfigServiceV2() { + serviceImpl = new MockConfigServiceV2Impl(); + } + + @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/test/integration/goldens/logging/MockConfigServiceV2Impl.java b/test/integration/goldens/logging/MockConfigServiceV2Impl.java new file mode 100644 index 0000000000..d414b55b49 --- /dev/null +++ b/test/integration/goldens/logging/MockConfigServiceV2Impl.java @@ -0,0 +1,281 @@ +/* + * 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.logging.v2; + +import com.google.api.core.BetaApi; +import com.google.logging.v2.ConfigServiceV2Grpc.ConfigServiceV2ImplBase; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.Empty; +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 MockConfigServiceV2Impl extends ConfigServiceV2ImplBase { + private List requests; + private Queue responses; + + public MockConfigServiceV2Impl() { + requests = new ArrayList<>(); + responses = new LinkedList<>(); + } + + public List getRequests() { + return requests; + } + + public void addResponse(AbstractMessage response) { + responses.add(response); + } + + public void setResponses(List responses) { + this.responses = new LinkedList(responses); + } + + public void addException(Exception exception) { + responses.add(exception); + } + + public void reset() { + requests = new ArrayList<>(); + responses = new LinkedList<>(); + } + + @Override + public void listBuckets( + ListBucketsRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof ListBucketsResponse) { + requests.add(request); + responseObserver.onNext(((ListBucketsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void getBucket(GetBucketRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogBucket) { + requests.add(request); + responseObserver.onNext(((LogBucket) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void updateBucket( + UpdateBucketRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogBucket) { + requests.add(request); + responseObserver.onNext(((LogBucket) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void listSinks( + ListSinksRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof ListSinksResponse) { + requests.add(request); + responseObserver.onNext(((ListSinksResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void getSink(GetSinkRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogSink) { + requests.add(request); + responseObserver.onNext(((LogSink) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void createSink(CreateSinkRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogSink) { + requests.add(request); + responseObserver.onNext(((LogSink) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void updateSink(UpdateSinkRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogSink) { + requests.add(request); + responseObserver.onNext(((LogSink) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void deleteSink(DeleteSinkRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof Empty) { + requests.add(request); + responseObserver.onNext(((Empty) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void listExclusions( + ListExclusionsRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof ListExclusionsResponse) { + requests.add(request); + responseObserver.onNext(((ListExclusionsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void getExclusion( + GetExclusionRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogExclusion) { + requests.add(request); + responseObserver.onNext(((LogExclusion) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void createExclusion( + CreateExclusionRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogExclusion) { + requests.add(request); + responseObserver.onNext(((LogExclusion) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void updateExclusion( + UpdateExclusionRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogExclusion) { + requests.add(request); + responseObserver.onNext(((LogExclusion) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void deleteExclusion( + DeleteExclusionRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof Empty) { + requests.add(request); + responseObserver.onNext(((Empty) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void getCmekSettings( + GetCmekSettingsRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof CmekSettings) { + requests.add(request); + responseObserver.onNext(((CmekSettings) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void updateCmekSettings( + UpdateCmekSettingsRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof CmekSettings) { + requests.add(request); + responseObserver.onNext(((CmekSettings) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } +} diff --git a/test/integration/goldens/logging/MockLoggingServiceV2.java b/test/integration/goldens/logging/MockLoggingServiceV2.java new file mode 100644 index 0000000000..ac83c2a646 --- /dev/null +++ b/test/integration/goldens/logging/MockLoggingServiceV2.java @@ -0,0 +1,59 @@ +/* + * 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.logging.v2; + +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 MockLoggingServiceV2 implements MockGrpcService { + private final MockLoggingServiceV2Impl serviceImpl; + + public MockLoggingServiceV2() { + serviceImpl = new MockLoggingServiceV2Impl(); + } + + @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/test/integration/goldens/logging/MockLoggingServiceV2Impl.java b/test/integration/goldens/logging/MockLoggingServiceV2Impl.java new file mode 100644 index 0000000000..4068b7d7f4 --- /dev/null +++ b/test/integration/goldens/logging/MockLoggingServiceV2Impl.java @@ -0,0 +1,135 @@ +/* + * 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.logging.v2; + +import com.google.api.core.BetaApi; +import com.google.logging.v2.LoggingServiceV2Grpc.LoggingServiceV2ImplBase; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.Empty; +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 MockLoggingServiceV2Impl extends LoggingServiceV2ImplBase { + private List requests; + private Queue responses; + + public MockLoggingServiceV2Impl() { + requests = new ArrayList<>(); + responses = new LinkedList<>(); + } + + public List getRequests() { + return requests; + } + + public void addResponse(AbstractMessage response) { + responses.add(response); + } + + public void setResponses(List responses) { + this.responses = new LinkedList(responses); + } + + public void addException(Exception exception) { + responses.add(exception); + } + + public void reset() { + requests = new ArrayList<>(); + responses = new LinkedList<>(); + } + + @Override + public void deleteLog(DeleteLogRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof Empty) { + requests.add(request); + responseObserver.onNext(((Empty) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void writeLogEntries( + WriteLogEntriesRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof WriteLogEntriesResponse) { + requests.add(request); + responseObserver.onNext(((WriteLogEntriesResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void listLogEntries( + ListLogEntriesRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof ListLogEntriesResponse) { + requests.add(request); + responseObserver.onNext(((ListLogEntriesResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void listMonitoredResourceDescriptors( + ListMonitoredResourceDescriptorsRequest request, + StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof ListMonitoredResourceDescriptorsResponse) { + requests.add(request); + responseObserver.onNext(((ListMonitoredResourceDescriptorsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void listLogs(ListLogsRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof ListLogsResponse) { + requests.add(request); + responseObserver.onNext(((ListLogsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } +} diff --git a/test/integration/goldens/logging/MockMetricsServiceV2.java b/test/integration/goldens/logging/MockMetricsServiceV2.java new file mode 100644 index 0000000000..f172c4faf8 --- /dev/null +++ b/test/integration/goldens/logging/MockMetricsServiceV2.java @@ -0,0 +1,59 @@ +/* + * 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.logging.v2; + +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 MockMetricsServiceV2 implements MockGrpcService { + private final MockMetricsServiceV2Impl serviceImpl; + + public MockMetricsServiceV2() { + serviceImpl = new MockMetricsServiceV2Impl(); + } + + @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/test/integration/goldens/logging/MockMetricsServiceV2Impl.java b/test/integration/goldens/logging/MockMetricsServiceV2Impl.java new file mode 100644 index 0000000000..b371b623f1 --- /dev/null +++ b/test/integration/goldens/logging/MockMetricsServiceV2Impl.java @@ -0,0 +1,136 @@ +/* + * 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.logging.v2; + +import com.google.api.core.BetaApi; +import com.google.logging.v2.MetricsServiceV2Grpc.MetricsServiceV2ImplBase; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.Empty; +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 MockMetricsServiceV2Impl extends MetricsServiceV2ImplBase { + private List requests; + private Queue responses; + + public MockMetricsServiceV2Impl() { + requests = new ArrayList<>(); + responses = new LinkedList<>(); + } + + public List getRequests() { + return requests; + } + + public void addResponse(AbstractMessage response) { + responses.add(response); + } + + public void setResponses(List responses) { + this.responses = new LinkedList(responses); + } + + public void addException(Exception exception) { + responses.add(exception); + } + + public void reset() { + requests = new ArrayList<>(); + responses = new LinkedList<>(); + } + + @Override + public void listLogMetrics( + ListLogMetricsRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof ListLogMetricsResponse) { + requests.add(request); + responseObserver.onNext(((ListLogMetricsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void getLogMetric( + GetLogMetricRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogMetric) { + requests.add(request); + responseObserver.onNext(((LogMetric) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void createLogMetric( + CreateLogMetricRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogMetric) { + requests.add(request); + responseObserver.onNext(((LogMetric) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void updateLogMetric( + UpdateLogMetricRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof LogMetric) { + requests.add(request); + responseObserver.onNext(((LogMetric) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void deleteLogMetric( + DeleteLogMetricRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof Empty) { + requests.add(request); + responseObserver.onNext(((Empty) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } +} diff --git a/test/integration/goldens/redis/CloudRedisClientTest.java b/test/integration/goldens/redis/CloudRedisClientTest.java index 6e37f465ec..6261e6a2f6 100644 --- a/test/integration/goldens/redis/CloudRedisClientTest.java +++ b/test/integration/goldens/redis/CloudRedisClientTest.java @@ -179,7 +179,7 @@ public void getInstanceTest() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -188,7 +188,7 @@ public void getInstanceTest() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") @@ -231,7 +231,7 @@ public void getInstanceTest2() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -240,7 +240,7 @@ public void getInstanceTest2() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") @@ -283,7 +283,7 @@ public void createInstanceTest() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -292,7 +292,7 @@ public void createInstanceTest() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") @@ -349,7 +349,7 @@ public void createInstanceTest2() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -358,7 +358,7 @@ public void createInstanceTest2() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") @@ -415,7 +415,7 @@ public void updateInstanceTest() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -424,7 +424,7 @@ public void updateInstanceTest() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") @@ -478,7 +478,7 @@ public void upgradeInstanceTest() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -487,7 +487,7 @@ public void upgradeInstanceTest() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") @@ -541,7 +541,7 @@ public void upgradeInstanceTest2() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -550,7 +550,7 @@ public void upgradeInstanceTest2() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") @@ -604,7 +604,7 @@ public void importInstanceTest() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -613,7 +613,7 @@ public void importInstanceTest() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") @@ -667,7 +667,7 @@ public void exportInstanceTest() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -676,7 +676,7 @@ public void exportInstanceTest() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") @@ -730,7 +730,7 @@ public void failoverInstanceTest() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -739,7 +739,7 @@ public void failoverInstanceTest() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") @@ -795,7 +795,7 @@ public void failoverInstanceTest2() throws Exception { Instance.newBuilder() .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString()) .setDisplayName("display_name1615086568") - .putAllLabels(new HashMap<>()) + .putAllLabels(new HashMap()) .setLocationId("location_id552319461") .setAlternativeLocationId("alternative_location_id-718920621") .setRedisVersion("redis_version-685310444") @@ -804,7 +804,7 @@ public void failoverInstanceTest2() throws Exception { .setPort(3446913) .setCurrentLocationId("current_location_id1312712735") .setStatusMessage("status_message-239442758") - .putAllRedisConfigs(new HashMap<>()) + .putAllRedisConfigs(new HashMap()) .setMemorySizeGb(34199707) .setAuthorizedNetwork("authorized_network-1733809270") .setPersistenceIamIdentity("persistence_iam_identity1061944584") From a91a0858ed4edc12e5b354fc1f23711e62a06045 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 22:11:25 -0700 Subject: [PATCH 17/26] fix: pass all tokens to instansiate in resname 1-pattern case --- .../ResourceNameHelperClassComposer.java | 24 ++- .../ResourceNameHelperClassComposerTest.java | 58 +++++- .../goldens/BillingAccountLocationName.golden | 173 ++++++++++++++++++ 3 files changed, 242 insertions(+), 13 deletions(-) create mode 100644 src/test/java/com/google/api/generator/gapic/composer/goldens/BillingAccountLocationName.golden diff --git a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java index c1e499fbec..564e6dad4f 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ResourceNameHelperClassComposer.java @@ -1090,21 +1090,25 @@ private static MethodDefinition createToStringMethod( List> tokenHierarchies) { boolean hasVariants = tokenHierarchies.size() > 1; if (!hasVariants) { - String token = getTokenSet(tokenHierarchies).stream().collect(Collectors.toList()).get(0); - String javaTokenVarName = JavaStyle.toLowerCamelCase(token); - Preconditions.checkNotNull( - patternTokenVarExprs.get(token), - String.format( - "No expression found for token %s amongst values %s", - javaTokenVarName, patternTokenVarExprs.toString())); + + List instantiateArgExprs = new ArrayList<>(); + List tokens = getTokenSet(tokenHierarchies).stream().collect(Collectors.toList()); + for (int i = 0; i < tokens.size(); i++) { + String token = tokens.get(i); + Preconditions.checkNotNull( + patternTokenVarExprs.get(token), + String.format( + "No expression found for token %s amongst values %s", + token, patternTokenVarExprs.toString())); + instantiateArgExprs.add(ValueExpr.withValue(StringObjectValue.withValue(token))); + instantiateArgExprs.add(patternTokenVarExprs.get(token)); + } MethodInvocationExpr returnInstantiateExpr = MethodInvocationExpr.builder() .setExprReferenceExpr(templateFinalVarExprs.get(0)) .setMethodName("instantiate") - .setArguments( - ValueExpr.withValue(StringObjectValue.withValue(token)), - patternTokenVarExprs.get(token)) + .setArguments(instantiateArgExprs) .setReturnType(TypeNode.STRING) .build(); return MethodDefinition.builder() 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 cf29462c31..f29ea0ec7e 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 @@ -25,13 +25,19 @@ 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.logging.v2.LogEntryProto; +import com.google.logging.v2.LoggingConfigProto; +import com.google.logging.v2.LoggingMetricsProto; +import com.google.logging.v2.LoggingProto; 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 google.cloud.CommonResources; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -95,7 +101,6 @@ public void generateResourceNameClass_echoFoobarMultiplePatterns() { ResourceName foobarResname = resourceNames.get("showcase.googleapis.com/Foobar"); assertThat(outputResourceNames).contains(foobarResname); - Service echoProtoService = services.get(0); GapicClass clazz = ResourceNameHelperClassComposer.instance().generate(foobarResname); JavaWriterVisitor visitor = new JavaWriterVisitor(); @@ -105,6 +110,55 @@ public void generateResourceNameClass_echoFoobarMultiplePatterns() { Assert.assertCodeEquals(goldenFilePath, visitor.write()); } + @Test + public void generateResourceNameClass_loggingOnePatternMultipleVariables() { + FileDescriptor serviceFileDescriptor = LoggingConfigProto.getDescriptor(); + ServiceDescriptor serviceDescriptor = serviceFileDescriptor.getServices().get(0); + assertEquals(serviceDescriptor.getName(), "ConfigServiceV2"); + + List protoFiles = + Arrays.asList( + serviceFileDescriptor, + LoggingProto.getDescriptor(), + LogEntryProto.getDescriptor(), + LoggingConfigProto.getDescriptor(), + LoggingMetricsProto.getDescriptor()); + + Map resourceNames = new HashMap<>(); + Map messageTypes = new HashMap<>(); + for (FileDescriptor fileDescriptor : protoFiles) { + resourceNames.putAll(Parser.parseResourceNames(fileDescriptor)); + messageTypes.putAll(Parser.parseMessages(fileDescriptor)); + } + + // Additional resource names. + FileDescriptor commonResourcesFileDescriptor = CommonResources.getDescriptor(); + resourceNames.putAll(Parser.parseResourceNames(commonResourcesFileDescriptor)); + + Set outputResourceNames = new HashSet<>(); + List services = + Parser.parseService( + serviceFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); + + ResourceName billingAccountLocationResname = + resourceNames.get("logging.googleapis.com/BillingAccountLocation"); + assertThat(outputResourceNames).contains(billingAccountLocationResname); + + GapicClass clazz = + ResourceNameHelperClassComposer.instance().generate(billingAccountLocationResname); + + JavaWriterVisitor visitor = new JavaWriterVisitor(); + clazz.classDefinition().accept(visitor); + Utils.saveCodegenToFile(this.getClass(), "BillingAccountLocationName.golden", visitor.write()); + Path goldenFilePath = + Paths.get(ComposerConstants.GOLDENFILES_DIRECTORY, "BillingAccountLocationName.golden"); + Assert.assertCodeEquals(goldenFilePath, visitor.write()); + } + @Test public void generateResourceNameClass_testingSessionOnePattern() { FileDescriptor testingFileDescriptor = TestingOuterClass.getDescriptor(); @@ -125,7 +179,6 @@ public void generateResourceNameClass_testingSessionOnePattern() { ResourceName sessionResname = resourceNames.get("showcase.googleapis.com/Session"); assertThat(outputResourceNames).contains(sessionResname); - Service testingProtoService = services.get(0); GapicClass clazz = ResourceNameHelperClassComposer.instance().generate(sessionResname); JavaWriterVisitor visitor = new JavaWriterVisitor(); @@ -134,5 +187,4 @@ public void generateResourceNameClass_testingSessionOnePattern() { 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/goldens/BillingAccountLocationName.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/BillingAccountLocationName.golden new file mode 100644 index 0000000000..94fd7c738d --- /dev/null +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/BillingAccountLocationName.golden @@ -0,0 +1,173 @@ +package com.google.logging.v2; + +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 BillingAccountLocationName implements ResourceName { + private static final PathTemplate BILLING_ACCOUNT_LOCATION = + PathTemplate.createWithoutUrlEncoding( + "billingAccounts/{billing_account}/locations/{location}"); + private volatile Map fieldValuesMap; + private final String billingAccount; + private final String location; + + private BillingAccountLocationName(Builder builder) { + billingAccount = Preconditions.checkNotNull(builder.getBillingAccount()); + location = Preconditions.checkNotNull(builder.getLocation()); + } + + public String getBillingAccount() { + return billingAccount; + } + + public String getLocation() { + return location; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static BillingAccountLocationName of(String billingAccount, String location) { + return newBuilder().setBillingAccount(billingAccount).setLocation(location).build(); + } + + public static String format(String billingAccount, String location) { + return newBuilder().setBillingAccount(billingAccount).setLocation(location).build().toString(); + } + + public static BillingAccountLocationName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + BILLING_ACCOUNT_LOCATION.validatedMatch( + formattedString, + "BillingAccountLocationName.parse: formattedString not in valid format"); + return of(matchMap.get("billing_account"), matchMap.get("location")); + } + + 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 (BillingAccountLocationName value : values) { + if (Objects.isNull(value)) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return BILLING_ACCOUNT_LOCATION.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (Objects.isNull(fieldValuesMap)) { + synchronized (this) { + if (Objects.isNull(fieldValuesMap)) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (!Objects.isNull(billingAccount)) { + fieldMapBuilder.put("billing_account", billingAccount); + } + if (!Objects.isNull(location)) { + fieldMapBuilder.put("location", location); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return BILLING_ACCOUNT_LOCATION.instantiate( + "billing_account", billingAccount, "location", location); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + BillingAccountLocationName that = ((BillingAccountLocationName) o); + return Objects.equals(this.billingAccount, that.billingAccount) + && Objects.equals(this.location, that.location); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(billingAccount); + h *= 1000003; + h ^= Objects.hashCode(location); + return h; + } + + /** Builder for billingAccounts/{billing_account}/locations/{location}. */ + public static class Builder { + private String billingAccount; + private String location; + + private Builder() {} + + public String getBillingAccount() { + return billingAccount; + } + + public String getLocation() { + return location; + } + + public Builder setBillingAccount(String billingAccount) { + this.billingAccount = billingAccount; + return this; + } + + public Builder setLocation(String location) { + this.location = location; + return this; + } + + private Builder(BillingAccountLocationName billingAccountLocationName) { + billingAccount = billingAccountLocationName.billingAccount; + location = billingAccountLocationName.location; + } + + public BillingAccountLocationName build() { + return new BillingAccountLocationName(this); + } + } +} From 19e0a985ce3b65e34e1eb3891f301715e0d886b9 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 22:51:56 -0700 Subject: [PATCH 18/26] fix: update goldens --- .../goldens/logging/BillingAccountLocationName.java | 3 ++- test/integration/goldens/logging/FolderLocationName.java | 2 +- test/integration/goldens/logging/LocationName.java | 2 +- test/integration/goldens/logging/LogMetricName.java | 2 +- test/integration/goldens/logging/OrganizationLocationName.java | 2 +- 5 files changed, 6 insertions(+), 5 deletions(-) diff --git a/test/integration/goldens/logging/BillingAccountLocationName.java b/test/integration/goldens/logging/BillingAccountLocationName.java index 3d108a3a4b..ead5f6cdec 100644 --- a/test/integration/goldens/logging/BillingAccountLocationName.java +++ b/test/integration/goldens/logging/BillingAccountLocationName.java @@ -125,7 +125,8 @@ public String getFieldValue(String fieldName) { @Override public String toString() { - return BILLING_ACCOUNT_LOCATION.instantiate("billing_account", billingAccount); + return BILLING_ACCOUNT_LOCATION.instantiate( + "billing_account", billingAccount, "location", location); } @Override diff --git a/test/integration/goldens/logging/FolderLocationName.java b/test/integration/goldens/logging/FolderLocationName.java index 526f0d1b62..24d56ee303 100644 --- a/test/integration/goldens/logging/FolderLocationName.java +++ b/test/integration/goldens/logging/FolderLocationName.java @@ -123,7 +123,7 @@ public String getFieldValue(String fieldName) { @Override public String toString() { - return FOLDER_LOCATION.instantiate("folder", folder); + return FOLDER_LOCATION.instantiate("folder", folder, "location", location); } @Override diff --git a/test/integration/goldens/logging/LocationName.java b/test/integration/goldens/logging/LocationName.java index 9074b6586d..9bc33a8940 100644 --- a/test/integration/goldens/logging/LocationName.java +++ b/test/integration/goldens/logging/LocationName.java @@ -123,7 +123,7 @@ public String getFieldValue(String fieldName) { @Override public String toString() { - return PROJECT_LOCATION.instantiate("project", project); + return PROJECT_LOCATION.instantiate("project", project, "location", location); } @Override diff --git a/test/integration/goldens/logging/LogMetricName.java b/test/integration/goldens/logging/LogMetricName.java index 104ecc3266..1d7150abad 100644 --- a/test/integration/goldens/logging/LogMetricName.java +++ b/test/integration/goldens/logging/LogMetricName.java @@ -123,7 +123,7 @@ public String getFieldValue(String fieldName) { @Override public String toString() { - return PROJECT_METRIC.instantiate("project", project); + return PROJECT_METRIC.instantiate("project", project, "metric", metric); } @Override diff --git a/test/integration/goldens/logging/OrganizationLocationName.java b/test/integration/goldens/logging/OrganizationLocationName.java index 08dbc40fd5..2f9cde61d8 100644 --- a/test/integration/goldens/logging/OrganizationLocationName.java +++ b/test/integration/goldens/logging/OrganizationLocationName.java @@ -123,7 +123,7 @@ public String getFieldValue(String fieldName) { @Override public String toString() { - return ORGANIZATION_LOCATION.instantiate("organization", organization); + return ORGANIZATION_LOCATION.instantiate("organization", organization, "location", location); } @Override From 2dfd4b11989f3e61550dc89bcf2120c9a05d66c8 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 23:00:47 -0700 Subject: [PATCH 19/26] fix: update goldens --- test/integration/goldens/redis/InstanceName.java | 3 ++- test/integration/goldens/redis/LocationName.java | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/test/integration/goldens/redis/InstanceName.java b/test/integration/goldens/redis/InstanceName.java index f2fb7dfe5a..ac6e5b1ce5 100644 --- a/test/integration/goldens/redis/InstanceName.java +++ b/test/integration/goldens/redis/InstanceName.java @@ -138,7 +138,8 @@ public String getFieldValue(String fieldName) { @Override public String toString() { - return PROJECT_LOCATION_INSTANCE.instantiate("project", project); + return PROJECT_LOCATION_INSTANCE.instantiate( + "project", project, "location", location, "instance", instance); } @Override diff --git a/test/integration/goldens/redis/LocationName.java b/test/integration/goldens/redis/LocationName.java index d781b0b94b..89cad0d585 100644 --- a/test/integration/goldens/redis/LocationName.java +++ b/test/integration/goldens/redis/LocationName.java @@ -123,7 +123,7 @@ public String getFieldValue(String fieldName) { @Override public String toString() { - return PROJECT_LOCATION.instantiate("project", project); + return PROJECT_LOCATION.instantiate("project", project, "location", location); } @Override From 5dae22179fc979d760c0e6f573d64c9dec12537d Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 23:13:59 -0700 Subject: [PATCH 20/26] build: add all integration tests to pre-commit hook --- .githooks/pre-commit | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/.githooks/pre-commit b/.githooks/pre-commit index b2ba7fa58f..14cc39fa11 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -101,10 +101,10 @@ then fi fi -# Check tests. +# Check unit tests. if [ $NUM_JAVA_FILES_CHANGED -gt 0 ] then - echo_status "Checking tests..." + echo_status "Checking unit tests..." bazel --batch test --disk_cache="$BAZEL_CACHE_DIR" //src/test/... TEST_STATUS=$? if [ $TEST_STATUS != 0 ] @@ -114,6 +114,19 @@ then fi fi +# Check integration tests. +if [ $NUM_JAVA_FILES_CHANGED -gt 0 ] +then + echo_status "Checking integration tests..." + bazel --batch test --disk_cache="$BAZEL_CACHE_DIR" //test/integration/... + TEST_STATUS=$? + if [ $TEST_STATUS != 0 ] + then + echo_error "Tests failed." "Please fix them and try again." + exit 1 + fi +fi + # Check and fix Bazel format. if [ $NUM_BAZEL_FILES_CHANGED -gt 0 ] then From 6917a2b7b2436908624355b276461b16c1aa1840 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 23:19:49 -0700 Subject: [PATCH 21/26] build: run pre-commit when goldens have changed --- .githooks/pre-commit | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 14cc39fa11..6851916f81 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -63,6 +63,9 @@ fi # Check only the staged files. NUM_TOTAL_FILES_CHANGED=$(git diff --cached --name-only | wc -l) NUM_JAVA_FILES_CHANGED=$(git diff --cached --name-only "*.java" | wc -l) +NUM_UNIT_GOLDEN_FILES_CHANGED=$(git diff --cached --name-only "src/test/*/*.golden" | wc -l) +NUM_INTEGRATION_GOLDEN_FILES_CHANGED=$(git diff --cached --name-only "test/integration/goldens/*/*.golden" | wc -l) +NUM_INTEGRATION_BAZEL_FILES_CHANGED=$(git diff --cached --name-only "test/integration/*/BUILD.bazel" | wc -l) NUM_BAZEL_FILES_CHANGED=$(git diff --cached --name-only "*BUILD.bazel" | wc -l) if [ $NUM_TOTAL_FILES_CHANGED -le 0 ] @@ -102,7 +105,7 @@ then fi # Check unit tests. -if [ $NUM_JAVA_FILES_CHANGED -gt 0 ] +if [ $NUM_JAVA_FILES_CHANGED -gt 0 ] || [ $NUM_UNIT_GOLDEN_FILES_CHANGED -gt 0 ] then echo_status "Checking unit tests..." bazel --batch test --disk_cache="$BAZEL_CACHE_DIR" //src/test/... @@ -115,7 +118,9 @@ then fi # Check integration tests. -if [ $NUM_JAVA_FILES_CHANGED -gt 0 ] +if [ $NUM_JAVA_FILES_CHANGED -gt 0 ] \ + || [ $NUM_INTEGRATION_GOLDEN_FILES_CHANGED -gt 0 ] \ + || [ $NUM_INTEGRATION_BAZEL_FILES_CHANGED -gt 0 ] then echo_status "Checking integration tests..." bazel --batch test --disk_cache="$BAZEL_CACHE_DIR" //test/integration/... From 1aaf0a5e250d73886c363343e6816d01403fd431 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Thu, 29 Oct 2020 23:22:05 -0700 Subject: [PATCH 22/26] build: add integration golden tests to CircleCI --- .circleci/config.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index 04ada2f08e..1545665da8 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -35,6 +35,14 @@ jobs: cd /tmp/gapic-generator-java bazel --batch test //src/test/... --noshow_progress find . -type f -regex ".*/bazel-testlogs/.*xml" -exec cp {} ${TEST_REPORTS_DIR} \; + - run: + name: Run integration tests for gapic-generator-java + command: | + cd /tmp/gapic-generator-java + # Check only the goldens, rely on the pre-commits for client library compilation tests. + # Otherwise, this would take too long. + bazel --batch test //test/integration:asset //test/integration:logging //test/integration:redis --noshow_progress + find . -type f -regex ".*/bazel-testlogs/.*xml" -exec cp {} ${TEST_REPORTS_DIR} \; - store_test_results: path: ~/.cache/bazel google-java-format: From 0ba9f53f27ba7114220072a067a2fa02c60af7af Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Fri, 30 Oct 2020 13:58:50 -0700 Subject: [PATCH 23/26] fix: preserve newlines and parse itemized lists in protobuf comments --- .../ClientLibraryPackageInfoComposer.java | 35 +- .../ServiceClientCommentComposer.java | 59 +++- .../gapic/model/SourceCodeInfoLocation.java | 2 +- .../protoparser/SourceCodeInfoParserTest.java | 8 +- .../logging/ConfigServiceV2Client.java | 108 ++++--- .../goldens/redis/CloudRedisClient.java | 302 ++++++++++++------ .../goldens/redis/package-info.java | 29 +- 7 files changed, 377 insertions(+), 166 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ClientLibraryPackageInfoComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ClientLibraryPackageInfoComposer.java index a26255cd49..c4332baeb8 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ClientLibraryPackageInfoComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ClientLibraryPackageInfoComposer.java @@ -25,6 +25,9 @@ import com.google.api.generator.gapic.model.Service; import com.google.common.base.Preconditions; import com.google.common.base.Strings; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.annotation.Generated; public class ClientLibraryPackageInfoComposer { @@ -73,16 +76,34 @@ private static CommentStatement createPackageInfoJavadoc(GapicContext context) { javaDocCommentBuilder.addParagraph( String.format("%s %s %s", DIVIDER, javaClientName, DIVIDER)); - // TODO(miraleung): Paragraphs + // TODO(miraleung): Replace this with a comment converter when we upport CommonMark. if (service.hasDescription()) { - String[] descriptionParagraphs = service.description().split("\\r?\\n"); + String[] descriptionParagraphs = service.description().split("\\n\\n"); for (int i = 0; i < descriptionParagraphs.length; i++) { - if (i == 0) { + boolean startsWithItemizedList = descriptionParagraphs[i].startsWith(" * "); + // Split by listed items, then join newlines. + List listItems = + Stream.of(descriptionParagraphs[i].split("\\n \\*")) + .map(s -> s.replace("\n", "")) + .collect(Collectors.toList()); + if (startsWithItemizedList) { + // Remove the first asterisk. + listItems.set(0, listItems.get(0).substring(2)); + } + + if (!startsWithItemizedList) { + if (i == 0) { + javaDocCommentBuilder = + javaDocCommentBuilder.addParagraph( + String.format(SERVICE_DESCRIPTION_HEADER_PATTERN, listItems.get(0))); + } else { + javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(listItems.get(0)); + } + } + if (listItems.size() > 1 || startsWithItemizedList) { javaDocCommentBuilder = - javaDocCommentBuilder.addParagraph( - String.format(SERVICE_DESCRIPTION_HEADER_PATTERN, descriptionParagraphs[i])); - } else { - javaDocCommentBuilder = javaDocCommentBuilder.addParagraph(descriptionParagraphs[i]); + javaDocCommentBuilder.addUnorderedList( + listItems.subList(startsWithItemizedList ? 0 : 1, listItems.size())); } } } diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java index 336f2e8e34..0c3fe22c97 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java @@ -21,9 +21,12 @@ import com.google.api.generator.gapic.model.MethodArgument; import com.google.api.generator.gapic.model.Service; import com.google.api.generator.gapic.utils.JavaStyle; +import com.google.common.base.Strings; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; class ServiceClientCommentComposer { // Tokens. @@ -104,8 +107,11 @@ class ServiceClientCommentComposer { static List createClassHeaderComments(Service service) { JavaDocComment.Builder classHeaderJavadocBuilder = JavaDocComment.builder(); if (service.hasDescription()) { - classHeaderJavadocBuilder.addComment( - String.format(SERVICE_DESCRIPTION_SUMMARY_PATTERN, service.description())); + classHeaderJavadocBuilder = + processProtobufComment( + service.description(), + classHeaderJavadocBuilder, + SERVICE_DESCRIPTION_SUMMARY_PATTERN); } // Service introduction. @@ -146,7 +152,8 @@ static List createRpcMethodHeaderComment( JavaDocComment.Builder methodJavadocBuilder = JavaDocComment.builder(); if (method.hasDescription()) { - methodJavadocBuilder.addComment(method.description()); + methodJavadocBuilder = + processProtobufComment(method.description(), methodJavadocBuilder, null); } methodJavadocBuilder.addParagraph(METHOD_DESCRIPTION_SAMPLE_CODE_SUMMARY_STRING); @@ -157,8 +164,11 @@ static List createRpcMethodHeaderComment( "request", "The request object containing all of the parameters for the API call."); } else { for (MethodArgument argument : methodArguments) { + // TODO(miraleung): Remove the newline replacement when we support CommonMark. String description = - argument.field().hasDescription() ? argument.field().description() : EMPTY_STRING; + argument.field().hasDescription() + ? argument.field().description().replace("\n", "") + : EMPTY_STRING; methodJavadocBuilder.addParam(argument.name(), description); } } @@ -178,7 +188,8 @@ static List createRpcCallableMethodHeaderComment(Method method JavaDocComment.Builder methodJavadocBuilder = JavaDocComment.builder(); if (method.hasDescription()) { - methodJavadocBuilder.addComment(method.description()); + methodJavadocBuilder = + processProtobufComment(method.description(), methodJavadocBuilder, null); } methodJavadocBuilder.addParagraph(METHOD_DESCRIPTION_SAMPLE_CODE_SUMMARY_STRING); @@ -192,4 +203,42 @@ static List createRpcCallableMethodHeaderComment(Method method private static CommentStatement toSimpleComment(String comment) { return CommentStatement.withComment(JavaDocComment.withComment(comment)); } + + // TODO(miraleung): Replace this with a comment converter when we upport CommonMark. + private static JavaDocComment.Builder processProtobufComment( + String rawComment, JavaDocComment.Builder originalCommentBuilder, String firstPattern) { + JavaDocComment.Builder commentBuilder = originalCommentBuilder; + String[] descriptionParagraphs = rawComment.split("\\n\\n"); + for (int i = 0; i < descriptionParagraphs.length; i++) { + boolean startsWithItemizedList = descriptionParagraphs[i].startsWith(" * "); + // Split by listed items, then join newlines. + List listItems = + Stream.of(descriptionParagraphs[i].split("\\n \\*")) + .map(s -> s.replace("\n", "")) + .collect(Collectors.toList()); + if (startsWithItemizedList) { + // Remove the first asterisk. + listItems.set(0, listItems.get(0).substring(2)); + } + if (!startsWithItemizedList) { + if (i == 0) { + if (!Strings.isNullOrEmpty(firstPattern)) { + commentBuilder = + commentBuilder.addParagraph(String.format(firstPattern, listItems.get(0))); + } else { + commentBuilder = commentBuilder.addParagraph(listItems.get(0)); + } + } else { + commentBuilder = commentBuilder.addParagraph(listItems.get(0)); + } + } + if (listItems.size() > 1 || startsWithItemizedList) { + commentBuilder = + commentBuilder.addUnorderedList( + listItems.subList(startsWithItemizedList ? 0 : 1, listItems.size())); + } + } + + return commentBuilder; + } } diff --git a/src/main/java/com/google/api/generator/gapic/model/SourceCodeInfoLocation.java b/src/main/java/com/google/api/generator/gapic/model/SourceCodeInfoLocation.java index fca6e7c791..eb39964e04 100644 --- a/src/main/java/com/google/api/generator/gapic/model/SourceCodeInfoLocation.java +++ b/src/main/java/com/google/api/generator/gapic/model/SourceCodeInfoLocation.java @@ -50,7 +50,7 @@ public String getLeadingDetachedComments(int index) { } private String processProtobufComment(String s) { - return ESCAPER.escape(s).trim(); + return s.trim(); } private class NewlineEscaper extends Escaper { diff --git a/src/test/java/com/google/api/generator/gapic/protoparser/SourceCodeInfoParserTest.java b/src/test/java/com/google/api/generator/gapic/protoparser/SourceCodeInfoParserTest.java index b8daabefeb..a33f20c782 100644 --- a/src/test/java/com/google/api/generator/gapic/protoparser/SourceCodeInfoParserTest.java +++ b/src/test/java/com/google/api/generator/gapic/protoparser/SourceCodeInfoParserTest.java @@ -48,7 +48,7 @@ public void setUp() throws Exception { public void getServiceInfo() { SourceCodeInfoLocation location = parser.getLocation(protoFile.findServiceByName("FooService")); assertEquals( - "This is a service description. It takes up multiple lines, like so.", + "This is a service description.\n It takes up multiple lines, like so.", location.getLeadingComments()); location = parser.getLocation(protoFile.findServiceByName("BarService")); @@ -60,7 +60,7 @@ public void getMethodInfo() { ServiceDescriptor service = protoFile.findServiceByName("FooService"); SourceCodeInfoLocation location = parser.getLocation(service.findMethodByName("FooMethod")); assertEquals( - "FooMethod does something. This comment also takes up multiple lines.", + "FooMethod does something.\n This comment also takes up multiple lines.", location.getLeadingComments()); service = protoFile.findServiceByName("BarService"); @@ -73,13 +73,13 @@ public void getOuterMessageInfo() { Descriptor message = protoFile.findMessageTypeByName("FooMessage"); SourceCodeInfoLocation location = parser.getLocation(message); assertEquals( - "This is a message descxription. Lorum ipsum dolor sit amet consectetur adipiscing elit.", + "This is a message descxription.\n Lorum ipsum dolor sit amet consectetur adipiscing elit.", location.getLeadingComments()); // Fields. location = parser.getLocation(message.findFieldByName("field_one")); assertEquals( - "This is a field description for field_one. And here is the second line of that" + "This is a field description for field_one.\n And here is the second line of that" + " description.", location.getLeadingComments()); assertEquals("A field trailing comment.", location.getTrailingComments()); diff --git a/test/integration/goldens/logging/ConfigServiceV2Client.java b/test/integration/goldens/logging/ConfigServiceV2Client.java index f3b1c319ba..dcf1deac7f 100644 --- a/test/integration/goldens/logging/ConfigServiceV2Client.java +++ b/test/integration/goldens/logging/ConfigServiceV2Client.java @@ -299,10 +299,15 @@ public final UnaryCallable getBucketCallable() { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a bucket. This method replaces the following fields in the existing bucket with values - * from the new bucket: `retention_period` If the retention period is decreased and the bucket is - * locked, FAILED_PRECONDITION will be returned. If the bucket has a LifecycleState of - * DELETE_REQUESTED, FAILED_PRECONDITION will be returned. A buckets region may not be modified - * after it is created. This method is in Beta. + * from the new bucket: `retention_period` + * + *

If the retention period is decreased and the bucket is locked, FAILED_PRECONDITION will be + * returned. + * + *

If the bucket has a LifecycleState of DELETE_REQUESTED, FAILED_PRECONDITION will be + * returned. + * + *

A buckets region may not be modified after it is created. This method is in Beta. * *

Sample code: * @@ -316,10 +321,15 @@ public final LogBucket updateBucket(UpdateBucketRequest request) { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a bucket. This method replaces the following fields in the existing bucket with values - * from the new bucket: `retention_period` If the retention period is decreased and the bucket is - * locked, FAILED_PRECONDITION will be returned. If the bucket has a LifecycleState of - * DELETE_REQUESTED, FAILED_PRECONDITION will be returned. A buckets region may not be modified - * after it is created. This method is in Beta. + * from the new bucket: `retention_period` + * + *

If the retention period is decreased and the bucket is locked, FAILED_PRECONDITION will be + * returned. + * + *

If the bucket has a LifecycleState of DELETE_REQUESTED, FAILED_PRECONDITION will be + * returned. + * + *

A buckets region may not be modified after it is created. This method is in Beta. * *

Sample code: */ @@ -671,8 +681,10 @@ public final UnaryCallable createSinkCallable() { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a sink. This method replaces the following fields in the existing sink with values from - * the new sink: `destination`, and `filter`. The updated sink might also have a new - * `writer_identity`; see the `unique_writer_identity` field. + * the new sink: `destination`, and `filter`. + * + *

The updated sink might also have a new `writer_identity`; see the `unique_writer_identity` + * field. * *

Sample code: * @@ -697,8 +709,10 @@ public final LogSink updateSink(LogSinkName sinkName, LogSink sink) { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a sink. This method replaces the following fields in the existing sink with values from - * the new sink: `destination`, and `filter`. The updated sink might also have a new - * `writer_identity`; see the `unique_writer_identity` field. + * the new sink: `destination`, and `filter`. + * + *

The updated sink might also have a new `writer_identity`; see the `unique_writer_identity` + * field. * *

Sample code: * @@ -720,8 +734,10 @@ public final LogSink updateSink(String sinkName, LogSink sink) { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a sink. This method replaces the following fields in the existing sink with values from - * the new sink: `destination`, and `filter`. The updated sink might also have a new - * `writer_identity`; see the `unique_writer_identity` field. + * the new sink: `destination`, and `filter`. + * + *

The updated sink might also have a new `writer_identity`; see the `unique_writer_identity` + * field. * *

Sample code: * @@ -756,8 +772,10 @@ public final LogSink updateSink(LogSinkName sinkName, LogSink sink, FieldMask up // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a sink. This method replaces the following fields in the existing sink with values from - * the new sink: `destination`, and `filter`. The updated sink might also have a new - * `writer_identity`; see the `unique_writer_identity` field. + * the new sink: `destination`, and `filter`. + * + *

The updated sink might also have a new `writer_identity`; see the `unique_writer_identity` + * field. * *

Sample code: * @@ -792,8 +810,10 @@ public final LogSink updateSink(String sinkName, LogSink sink, FieldMask updateM // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a sink. This method replaces the following fields in the existing sink with values from - * the new sink: `destination`, and `filter`. The updated sink might also have a new - * `writer_identity`; see the `unique_writer_identity` field. + * the new sink: `destination`, and `filter`. + * + *

The updated sink might also have a new `writer_identity`; see the `unique_writer_identity` + * field. * *

Sample code: * @@ -807,8 +827,10 @@ public final LogSink updateSink(UpdateSinkRequest request) { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a sink. This method replaces the following fields in the existing sink with values from - * the new sink: `destination`, and `filter`. The updated sink might also have a new - * `writer_identity`; see the `unique_writer_identity` field. + * the new sink: `destination`, and `filter`. + * + *

The updated sink might also have a new `writer_identity`; see the `unique_writer_identity` + * field. * *

Sample code: */ @@ -1370,9 +1392,12 @@ public final UnaryCallable deleteExclusionCallabl // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Gets the Logs Router CMEK settings for the given resource. Note: CMEK for the Logs Router can - * currently only be configured for GCP organizations. Once configured, it applies to all projects - * and folders in the GCP organization. See [Enabling CMEK for Logs + * Gets the Logs Router CMEK settings for the given resource. + * + *

Note: CMEK for the Logs Router can currently only be configured for GCP organizations. Once + * configured, it applies to all projects and folders in the GCP organization. + * + *

See [Enabling CMEK for Logs * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. * *

Sample code: @@ -1386,9 +1411,12 @@ public final CmekSettings getCmekSettings(GetCmekSettingsRequest request) { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Gets the Logs Router CMEK settings for the given resource. Note: CMEK for the Logs Router can - * currently only be configured for GCP organizations. Once configured, it applies to all projects - * and folders in the GCP organization. See [Enabling CMEK for Logs + * Gets the Logs Router CMEK settings for the given resource. + * + *

Note: CMEK for the Logs Router can currently only be configured for GCP organizations. Once + * configured, it applies to all projects and folders in the GCP organization. + * + *

See [Enabling CMEK for Logs * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. * *

Sample code: @@ -1399,13 +1427,17 @@ public final UnaryCallable getCmekSettings // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Updates the Logs Router CMEK settings for the given resource. Note: CMEK for the Logs Router - * can currently only be configured for GCP organizations. Once configured, it applies to all - * projects and folders in the GCP organization. - * [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] will fail if 1) + * Updates the Logs Router CMEK settings for the given resource. + * + *

Note: CMEK for the Logs Router can currently only be configured for GCP organizations. Once + * configured, it applies to all projects and folders in the GCP organization. + * + *

[UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] will fail if 1) * `kms_key_name` is invalid, or 2) the associated service account does not have the required * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or 3) access to the key - * is disabled. See [Enabling CMEK for Logs + * is disabled. + * + *

See [Enabling CMEK for Logs * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. * *

Sample code: @@ -1419,13 +1451,17 @@ public final CmekSettings updateCmekSettings(UpdateCmekSettingsRequest request) // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Updates the Logs Router CMEK settings for the given resource. Note: CMEK for the Logs Router - * can currently only be configured for GCP organizations. Once configured, it applies to all - * projects and folders in the GCP organization. - * [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] will fail if 1) + * Updates the Logs Router CMEK settings for the given resource. + * + *

Note: CMEK for the Logs Router can currently only be configured for GCP organizations. Once + * configured, it applies to all projects and folders in the GCP organization. + * + *

[UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] will fail if 1) * `kms_key_name` is invalid, or 2) the associated service account does not have the required * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or 3) access to the key - * is disabled. See [Enabling CMEK for Logs + * is disabled. + * + *

See [Enabling CMEK for Logs * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. * *

Sample code: diff --git a/test/integration/goldens/redis/CloudRedisClient.java b/test/integration/goldens/redis/CloudRedisClient.java index 83a43c2b11..cdd4362e32 100644 --- a/test/integration/goldens/redis/CloudRedisClient.java +++ b/test/integration/goldens/redis/CloudRedisClient.java @@ -43,15 +43,26 @@ // AUTO-GENERATED DOCUMENTATION AND CLASS. /** - * Service Description: Configures and manages Cloud Memorystore for Redis instances Google Cloud - * Memorystore for Redis v1 The `redis.googleapis.com` service implements the Google Cloud - * Memorystore for Redis API and defines the following resource model for managing Redis instances: - * * The service works with a collection of cloud projects, named: `/projects/*` * Each - * project has a collection of available locations, named: `/locations/*` * Each location - * has a collection of Redis instances, named: `/instances/*` * As such, Redis instances are - * resources of the form: `/projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * Note that location_id must be referring to a GCP `region`; for example: * - * `projects/redpepper-1290/locations/us-central1/instances/my-redis` + * Service Description: Configures and manages Cloud Memorystore for Redis instances + * + *

Google Cloud Memorystore for Redis v1 + * + *

The `redis.googleapis.com` service implements the Google Cloud Memorystore for Redis API and + * defines the following resource model for managing Redis instances: + * + *

    + *
  • The service works with a collection of cloud projects, named: `/projects/*` + *
  • Each project has a collection of available locations, named: `/locations/*` + *
  • Each location has a collection of Redis instances, named: `/instances/*` + *
  • As such, Redis instances are resources of the form: + * `/projects/{project_id}/locations/{location_id}/instances/{instance_id}` + *
+ * + *

Note that location_id must be referring to a GCP `region`; for example: + * + *

    + *
  • `projects/redpepper-1290/locations/us-central1/instances/my-redis` + *
* *

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: @@ -152,10 +163,16 @@ public final OperationsClient getOperationsClient() { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists all Redis instances owned by a project in either the specified location (region) or all - * locations. The location should have the following format: * - * `projects/{project_id}/locations/{location_id}` If `location_id` is specified as `-` - * (wildcard), then all regions available to the project are queried, and the results are - * aggregated. + * locations. + * + *

The location should have the following format: + * + *

    + *
  • `projects/{project_id}/locations/{location_id}` + *
+ * + *

If `location_id` is specified as `-` (wildcard), then all regions available to the project + * are queried, and the results are aggregated. * *

Sample code: * @@ -174,10 +191,16 @@ public final ListInstancesPagedResponse listInstances(LocationName parent) { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists all Redis instances owned by a project in either the specified location (region) or all - * locations. The location should have the following format: * - * `projects/{project_id}/locations/{location_id}` If `location_id` is specified as `-` - * (wildcard), then all regions available to the project are queried, and the results are - * aggregated. + * locations. + * + *

The location should have the following format: + * + *

    + *
  • `projects/{project_id}/locations/{location_id}` + *
+ * + *

If `location_id` is specified as `-` (wildcard), then all regions available to the project + * are queried, and the results are aggregated. * *

Sample code: * @@ -193,10 +216,16 @@ public final ListInstancesPagedResponse listInstances(String parent) { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists all Redis instances owned by a project in either the specified location (region) or all - * locations. The location should have the following format: * - * `projects/{project_id}/locations/{location_id}` If `location_id` is specified as `-` - * (wildcard), then all regions available to the project are queried, and the results are - * aggregated. + * locations. + * + *

The location should have the following format: + * + *

    + *
  • `projects/{project_id}/locations/{location_id}` + *
+ * + *

If `location_id` is specified as `-` (wildcard), then all regions available to the project + * are queried, and the results are aggregated. * *

Sample code: * @@ -210,10 +239,16 @@ public final ListInstancesPagedResponse listInstances(ListInstancesRequest reque // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists all Redis instances owned by a project in either the specified location (region) or all - * locations. The location should have the following format: * - * `projects/{project_id}/locations/{location_id}` If `location_id` is specified as `-` - * (wildcard), then all regions available to the project are queried, and the results are - * aggregated. + * locations. + * + *

The location should have the following format: + * + *

    + *
  • `projects/{project_id}/locations/{location_id}` + *
+ * + *

If `location_id` is specified as `-` (wildcard), then all regions available to the project + * are queried, and the results are aggregated. * *

Sample code: */ @@ -225,10 +260,16 @@ public final ListInstancesPagedResponse listInstances(ListInstancesRequest reque // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists all Redis instances owned by a project in either the specified location (region) or all - * locations. The location should have the following format: * - * `projects/{project_id}/locations/{location_id}` If `location_id` is specified as `-` - * (wildcard), then all regions available to the project are queried, and the results are - * aggregated. + * locations. + * + *

The location should have the following format: + * + *

    + *
  • `projects/{project_id}/locations/{location_id}` + *
+ * + *

If `location_id` is specified as `-` (wildcard), then all regions available to the project + * are queried, and the results are aggregated. * *

Sample code: */ @@ -296,13 +337,18 @@ public final UnaryCallable getInstanceCallable() { // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Creates a Redis instance based on the specified tier and memory size. By default, the instance - * is accessible from the project's [default network](https://cloud.google.com/vpc/docs/vpc). The - * creation is executed asynchronously and callers may check the returned operation to track its - * progress. Once the operation is completed the Redis instance will be fully functional. - * Completed longrunning.Operation will contain the new instance object in the response field. The - * returned operation is automatically deleted after a few hours, so there is no need to call - * DeleteOperation. + * Creates a Redis instance based on the specified tier and memory size. + * + *

By default, the instance is accessible from the project's [default + * network](https://cloud.google.com/vpc/docs/vpc). + * + *

The creation is executed asynchronously and callers may check the returned operation to + * track its progress. Once the operation is completed the Redis instance will be fully + * functional. Completed longrunning.Operation will contain the new instance object in the + * response field. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: * @@ -328,13 +374,18 @@ public final OperationFuture createInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Creates a Redis instance based on the specified tier and memory size. By default, the instance - * is accessible from the project's [default network](https://cloud.google.com/vpc/docs/vpc). The - * creation is executed asynchronously and callers may check the returned operation to track its - * progress. Once the operation is completed the Redis instance will be fully functional. - * Completed longrunning.Operation will contain the new instance object in the response field. The - * returned operation is automatically deleted after a few hours, so there is no need to call - * DeleteOperation. + * Creates a Redis instance based on the specified tier and memory size. + * + *

By default, the instance is accessible from the project's [default + * network](https://cloud.google.com/vpc/docs/vpc). + * + *

The creation is executed asynchronously and callers may check the returned operation to + * track its progress. Once the operation is completed the Redis instance will be fully + * functional. Completed longrunning.Operation will contain the new instance object in the + * response field. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: * @@ -360,13 +411,18 @@ public final OperationFuture createInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Creates a Redis instance based on the specified tier and memory size. By default, the instance - * is accessible from the project's [default network](https://cloud.google.com/vpc/docs/vpc). The - * creation is executed asynchronously and callers may check the returned operation to track its - * progress. Once the operation is completed the Redis instance will be fully functional. - * Completed longrunning.Operation will contain the new instance object in the response field. The - * returned operation is automatically deleted after a few hours, so there is no need to call - * DeleteOperation. + * Creates a Redis instance based on the specified tier and memory size. + * + *

By default, the instance is accessible from the project's [default + * network](https://cloud.google.com/vpc/docs/vpc). + * + *

The creation is executed asynchronously and callers may check the returned operation to + * track its progress. Once the operation is completed the Redis instance will be fully + * functional. Completed longrunning.Operation will contain the new instance object in the + * response field. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: * @@ -380,13 +436,18 @@ public final OperationFuture createInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Creates a Redis instance based on the specified tier and memory size. By default, the instance - * is accessible from the project's [default network](https://cloud.google.com/vpc/docs/vpc). The - * creation is executed asynchronously and callers may check the returned operation to track its - * progress. Once the operation is completed the Redis instance will be fully functional. - * Completed longrunning.Operation will contain the new instance object in the response field. The - * returned operation is automatically deleted after a few hours, so there is no need to call - * DeleteOperation. + * Creates a Redis instance based on the specified tier and memory size. + * + *

By default, the instance is accessible from the project's [default + * network](https://cloud.google.com/vpc/docs/vpc). + * + *

The creation is executed asynchronously and callers may check the returned operation to + * track its progress. Once the operation is completed the Redis instance will be fully + * functional. Completed longrunning.Operation will contain the new instance object in the + * response field. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: */ @@ -397,13 +458,18 @@ public final OperationFuture createInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Creates a Redis instance based on the specified tier and memory size. By default, the instance - * is accessible from the project's [default network](https://cloud.google.com/vpc/docs/vpc). The - * creation is executed asynchronously and callers may check the returned operation to track its - * progress. Once the operation is completed the Redis instance will be fully functional. - * Completed longrunning.Operation will contain the new instance object in the response field. The - * returned operation is automatically deleted after a few hours, so there is no need to call - * DeleteOperation. + * Creates a Redis instance based on the specified tier and memory size. + * + *

By default, the instance is accessible from the project's [default + * network](https://cloud.google.com/vpc/docs/vpc). + * + *

The creation is executed asynchronously and callers may check the returned operation to + * track its progress. Once the operation is completed the Redis instance will be fully + * functional. Completed longrunning.Operation will contain the new instance object in the + * response field. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: */ @@ -413,9 +479,10 @@ public final UnaryCallable createInstanceCalla // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Updates the metadata and configuration of a specific Redis instance. Completed - * longrunning.Operation will contain the new instance object in the response field. The returned - * operation is automatically deleted after a few hours, so there is no need to call + * Updates the metadata and configuration of a specific Redis instance. + * + *

Completed longrunning.Operation will contain the new instance object in the response field. + * The returned operation is automatically deleted after a few hours, so there is no need to call * DeleteOperation. * *

Sample code: @@ -436,9 +503,10 @@ public final OperationFuture updateInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Updates the metadata and configuration of a specific Redis instance. Completed - * longrunning.Operation will contain the new instance object in the response field. The returned - * operation is automatically deleted after a few hours, so there is no need to call + * Updates the metadata and configuration of a specific Redis instance. + * + *

Completed longrunning.Operation will contain the new instance object in the response field. + * The returned operation is automatically deleted after a few hours, so there is no need to call * DeleteOperation. * *

Sample code: @@ -453,9 +521,10 @@ public final OperationFuture updateInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Updates the metadata and configuration of a specific Redis instance. Completed - * longrunning.Operation will contain the new instance object in the response field. The returned - * operation is automatically deleted after a few hours, so there is no need to call + * Updates the metadata and configuration of a specific Redis instance. + * + *

Completed longrunning.Operation will contain the new instance object in the response field. + * The returned operation is automatically deleted after a few hours, so there is no need to call * DeleteOperation. * *

Sample code: @@ -467,9 +536,10 @@ public final OperationFuture updateInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Updates the metadata and configuration of a specific Redis instance. Completed - * longrunning.Operation will contain the new instance object in the response field. The returned - * operation is automatically deleted after a few hours, so there is no need to call + * Updates the metadata and configuration of a specific Redis instance. + * + *

Completed longrunning.Operation will contain the new instance object in the response field. + * The returned operation is automatically deleted after a few hours, so there is no need to call * DeleteOperation. * *

Sample code: @@ -556,10 +626,13 @@ public final UnaryCallable upgradeInstanceCal // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. Redis may stop - * serving during this operation. Instance state will be IMPORTING for entire operation. When - * complete, the instance will contain only data from the imported file. The returned operation is - * automatically deleted after a few hours, so there is no need to call DeleteOperation. + * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. + * + *

Redis may stop serving during this operation. Instance state will be IMPORTING for entire + * operation. When complete, the instance will contain only data from the imported file. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: * @@ -578,10 +651,13 @@ public final OperationFuture importInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. Redis may stop - * serving during this operation. Instance state will be IMPORTING for entire operation. When - * complete, the instance will contain only data from the imported file. The returned operation is - * automatically deleted after a few hours, so there is no need to call DeleteOperation. + * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. + * + *

Redis may stop serving during this operation. Instance state will be IMPORTING for entire + * operation. When complete, the instance will contain only data from the imported file. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: * @@ -595,10 +671,13 @@ public final OperationFuture importInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. Redis may stop - * serving during this operation. Instance state will be IMPORTING for entire operation. When - * complete, the instance will contain only data from the imported file. The returned operation is - * automatically deleted after a few hours, so there is no need to call DeleteOperation. + * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. + * + *

Redis may stop serving during this operation. Instance state will be IMPORTING for entire + * operation. When complete, the instance will contain only data from the imported file. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: */ @@ -609,10 +688,13 @@ public final OperationFuture importInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. Redis may stop - * serving during this operation. Instance state will be IMPORTING for entire operation. When - * complete, the instance will contain only data from the imported file. The returned operation is - * automatically deleted after a few hours, so there is no need to call DeleteOperation. + * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. + * + *

Redis may stop serving during this operation. Instance state will be IMPORTING for entire + * operation. When complete, the instance will contain only data from the imported file. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: */ @@ -622,9 +704,12 @@ public final UnaryCallable importInstanceCalla // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Export Redis instance data into a Redis RDB format file in Cloud Storage. Redis will continue - * serving during this operation. The returned operation is automatically deleted after a few - * hours, so there is no need to call DeleteOperation. + * Export Redis instance data into a Redis RDB format file in Cloud Storage. + * + *

Redis will continue serving during this operation. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: * @@ -643,9 +728,12 @@ public final OperationFuture exportInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Export Redis instance data into a Redis RDB format file in Cloud Storage. Redis will continue - * serving during this operation. The returned operation is automatically deleted after a few - * hours, so there is no need to call DeleteOperation. + * Export Redis instance data into a Redis RDB format file in Cloud Storage. + * + *

Redis will continue serving during this operation. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: * @@ -659,9 +747,12 @@ public final OperationFuture exportInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Export Redis instance data into a Redis RDB format file in Cloud Storage. Redis will continue - * serving during this operation. The returned operation is automatically deleted after a few - * hours, so there is no need to call DeleteOperation. + * Export Redis instance data into a Redis RDB format file in Cloud Storage. + * + *

Redis will continue serving during this operation. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: */ @@ -672,9 +763,12 @@ public final OperationFuture exportInstanceAsync( // AUTO-GENERATED DOCUMENTATION AND METHOD. /** - * Export Redis instance data into a Redis RDB format file in Cloud Storage. Redis will continue - * serving during this operation. The returned operation is automatically deleted after a few - * hours, so there is no need to call DeleteOperation. + * Export Redis instance data into a Redis RDB format file in Cloud Storage. + * + *

Redis will continue serving during this operation. + * + *

The returned operation is automatically deleted after a few hours, so there is no need to + * call DeleteOperation. * *

Sample code: */ diff --git a/test/integration/goldens/redis/package-info.java b/test/integration/goldens/redis/package-info.java index 8e1e2d6fb8..702bad9fc3 100644 --- a/test/integration/goldens/redis/package-info.java +++ b/test/integration/goldens/redis/package-info.java @@ -21,15 +21,26 @@ * *

======================= CloudRedisClient ======================= * - *

Service Description: Configures and manages Cloud Memorystore for Redis instances Google Cloud - * Memorystore for Redis v1 The `redis.googleapis.com` service implements the Google Cloud - * Memorystore for Redis API and defines the following resource model for managing Redis instances: - * * The service works with a collection of cloud projects, named: `/projects/*` * Each project has - * a collection of available locations, named: `/locations/*` * Each location has a collection of - * Redis instances, named: `/instances/*` * As such, Redis instances are resources of the form: - * `/projects/{project_id}/locations/{location_id}/instances/{instance_id}` Note that location_id - * must be referring to a GCP `region`; for example: * - * `projects/redpepper-1290/locations/us-central1/instances/my-redis` + *

Service Description: Configures and manages Cloud Memorystore for Redis instances + * + *

Google Cloud Memorystore for Redis v1 + * + *

The `redis.googleapis.com` service implements the Google Cloud Memorystore for Redis API and + * defines the following resource model for managing Redis instances: + * + *

    + *
  • The service works with a collection of cloud projects, named: `/projects/*` + *
  • Each project has a collection of available locations, named: `/locations/*` + *
  • Each location has a collection of Redis instances, named: `/instances/*` + *
  • As such, Redis instances are resources of the form: + * `/projects/{project_id}/locations/{location_id}/instances/{instance_id}` + *
+ * + *

Note that location_id must be referring to a GCP `region`; for example: + * + *

    + *
  • `projects/redpepper-1290/locations/us-central1/instances/my-redis` + *
* *

Sample for CloudRedisClient: */ From 2b1b8d1ad6bbe1d5e4bc1eaaf3adc4d30aff2b31 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Fri, 30 Oct 2020 14:03:31 -0700 Subject: [PATCH 24/26] fix: remove extraneous escaper --- .../gapic/model/SourceCodeInfoLocation.java | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/model/SourceCodeInfoLocation.java b/src/main/java/com/google/api/generator/gapic/model/SourceCodeInfoLocation.java index eb39964e04..f39cb39530 100644 --- a/src/main/java/com/google/api/generator/gapic/model/SourceCodeInfoLocation.java +++ b/src/main/java/com/google/api/generator/gapic/model/SourceCodeInfoLocation.java @@ -14,8 +14,6 @@ package com.google.api.generator.gapic.model; -import com.google.common.escape.Escaper; -import com.google.common.escape.Escapers; import com.google.protobuf.DescriptorProtos.SourceCodeInfo.Location; import javax.annotation.Nonnull; @@ -24,9 +22,6 @@ * additional documentation on descriptor.proto. */ public class SourceCodeInfoLocation { - // Not a singleton because of nested-class instantiation mechanics. - private final NewlineEscaper ESCAPER = new NewlineEscaper(); - @Nonnull private final Location location; private SourceCodeInfoLocation(Location location) { @@ -52,13 +47,4 @@ public String getLeadingDetachedComments(int index) { private String processProtobufComment(String s) { return s.trim(); } - - private class NewlineEscaper extends Escaper { - private final Escaper charEscaper = Escapers.builder().addEscape('\n', "").build(); - - @Override - public String escape(String sourceString) { - return charEscaper.escape(sourceString); - } - } } From 17893de4de2ddd2551daf370f1646dbba8e3eb61 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Fri, 30 Oct 2020 14:24:53 -0700 Subject: [PATCH 25/26] fix: update integration goldens for ServiceClient comment names --- .../goldens/asset/AssetServiceClient.java | 15 ++++++++------- .../goldens/logging/ConfigServiceV2Client.java | 15 ++++++++------- .../goldens/logging/LoggingServiceV2Client.java | 15 ++++++++------- .../goldens/logging/MetricsServiceV2Client.java | 15 ++++++++------- .../goldens/redis/CloudRedisClient.java | 12 ++++++------ 5 files changed, 38 insertions(+), 34 deletions(-) diff --git a/test/integration/goldens/asset/AssetServiceClient.java b/test/integration/goldens/asset/AssetServiceClient.java index 5035f43170..c45dcbdabd 100644 --- a/test/integration/goldens/asset/AssetServiceClient.java +++ b/test/integration/goldens/asset/AssetServiceClient.java @@ -84,22 +84,22 @@ public class AssetServiceClient implements BackgroundResource { private final AssetServiceStub stub; private final OperationsClient operationsClient; - /** Constructs an instance of EchoClient with default settings. */ + /** Constructs an instance of AssetServiceClient with default settings. */ public static final AssetServiceClient create() throws IOException { return create(AssetServiceSettings.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. + * Constructs an instance of AssetServiceClient, 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 AssetServiceClient create(AssetServiceSettings settings) throws IOException { return new AssetServiceClient(settings); } /** - * Constructs an instance of EchoClient, using the given stub for making calls. This is for - * advanced usage - prefer using create(AssetServiceSettings). + * Constructs an instance of AssetServiceClient, using the given stub for making calls. This is + * for advanced usage - prefer using create(AssetServiceSettings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final AssetServiceClient create(AssetServiceStub stub) { @@ -107,8 +107,9 @@ public static final AssetServiceClient create(AssetServiceStub 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. + * Constructs an instance of AssetServiceClient, 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 AssetServiceClient(AssetServiceSettings settings) throws IOException { this.settings = settings; diff --git a/test/integration/goldens/logging/ConfigServiceV2Client.java b/test/integration/goldens/logging/ConfigServiceV2Client.java index dcf1deac7f..7e0b805328 100644 --- a/test/integration/goldens/logging/ConfigServiceV2Client.java +++ b/test/integration/goldens/logging/ConfigServiceV2Client.java @@ -80,14 +80,14 @@ public class ConfigServiceV2Client implements BackgroundResource { private final ConfigServiceV2Settings settings; private final ConfigServiceV2Stub stub; - /** Constructs an instance of EchoClient with default settings. */ + /** Constructs an instance of ConfigServiceV2Client with default settings. */ public static final ConfigServiceV2Client create() throws IOException { return create(ConfigServiceV2Settings.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. + * Constructs an instance of ConfigServiceV2Client, 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 ConfigServiceV2Client create(ConfigServiceV2Settings settings) throws IOException { @@ -95,8 +95,8 @@ public static final ConfigServiceV2Client create(ConfigServiceV2Settings setting } /** - * Constructs an instance of EchoClient, using the given stub for making calls. This is for - * advanced usage - prefer using create(ConfigServiceV2Settings). + * Constructs an instance of ConfigServiceV2Client, using the given stub for making calls. This is + * for advanced usage - prefer using create(ConfigServiceV2Settings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final ConfigServiceV2Client create(ConfigServiceV2Stub stub) { @@ -104,8 +104,9 @@ public static final ConfigServiceV2Client create(ConfigServiceV2Stub 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. + * Constructs an instance of ConfigServiceV2Client, 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 ConfigServiceV2Client(ConfigServiceV2Settings settings) throws IOException { this.settings = settings; diff --git a/test/integration/goldens/logging/LoggingServiceV2Client.java b/test/integration/goldens/logging/LoggingServiceV2Client.java index 2bbf50ba65..838256ea3a 100644 --- a/test/integration/goldens/logging/LoggingServiceV2Client.java +++ b/test/integration/goldens/logging/LoggingServiceV2Client.java @@ -82,14 +82,14 @@ public class LoggingServiceV2Client implements BackgroundResource { private final LoggingServiceV2Settings settings; private final LoggingServiceV2Stub stub; - /** Constructs an instance of EchoClient with default settings. */ + /** Constructs an instance of LoggingServiceV2Client with default settings. */ public static final LoggingServiceV2Client create() throws IOException { return create(LoggingServiceV2Settings.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. + * Constructs an instance of LoggingServiceV2Client, 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 LoggingServiceV2Client create(LoggingServiceV2Settings settings) throws IOException { @@ -97,8 +97,8 @@ public static final LoggingServiceV2Client create(LoggingServiceV2Settings setti } /** - * Constructs an instance of EchoClient, using the given stub for making calls. This is for - * advanced usage - prefer using create(LoggingServiceV2Settings). + * Constructs an instance of LoggingServiceV2Client, using the given stub for making calls. This + * is for advanced usage - prefer using create(LoggingServiceV2Settings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final LoggingServiceV2Client create(LoggingServiceV2Stub stub) { @@ -106,8 +106,9 @@ public static final LoggingServiceV2Client create(LoggingServiceV2Stub 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. + * Constructs an instance of LoggingServiceV2Client, 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 LoggingServiceV2Client(LoggingServiceV2Settings settings) throws IOException { this.settings = settings; diff --git a/test/integration/goldens/logging/MetricsServiceV2Client.java b/test/integration/goldens/logging/MetricsServiceV2Client.java index 9341c256f0..2a1fefb209 100644 --- a/test/integration/goldens/logging/MetricsServiceV2Client.java +++ b/test/integration/goldens/logging/MetricsServiceV2Client.java @@ -79,14 +79,14 @@ public class MetricsServiceV2Client implements BackgroundResource { private final MetricsServiceV2Settings settings; private final MetricsServiceV2Stub stub; - /** Constructs an instance of EchoClient with default settings. */ + /** Constructs an instance of MetricsServiceV2Client with default settings. */ public static final MetricsServiceV2Client create() throws IOException { return create(MetricsServiceV2Settings.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. + * Constructs an instance of MetricsServiceV2Client, 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 MetricsServiceV2Client create(MetricsServiceV2Settings settings) throws IOException { @@ -94,8 +94,8 @@ public static final MetricsServiceV2Client create(MetricsServiceV2Settings setti } /** - * Constructs an instance of EchoClient, using the given stub for making calls. This is for - * advanced usage - prefer using create(MetricsServiceV2Settings). + * Constructs an instance of MetricsServiceV2Client, using the given stub for making calls. This + * is for advanced usage - prefer using create(MetricsServiceV2Settings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final MetricsServiceV2Client create(MetricsServiceV2Stub stub) { @@ -103,8 +103,9 @@ public static final MetricsServiceV2Client create(MetricsServiceV2Stub 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. + * Constructs an instance of MetricsServiceV2Client, 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 MetricsServiceV2Client(MetricsServiceV2Settings settings) throws IOException { this.settings = settings; diff --git a/test/integration/goldens/redis/CloudRedisClient.java b/test/integration/goldens/redis/CloudRedisClient.java index cdd4362e32..305a9d0e8f 100644 --- a/test/integration/goldens/redis/CloudRedisClient.java +++ b/test/integration/goldens/redis/CloudRedisClient.java @@ -104,21 +104,21 @@ public class CloudRedisClient implements BackgroundResource { private final CloudRedisStub stub; private final OperationsClient operationsClient; - /** Constructs an instance of EchoClient with default settings. */ + /** Constructs an instance of CloudRedisClient with default settings. */ public static final CloudRedisClient create() throws IOException { return create(CloudRedisSettings.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. + * Constructs an instance of CloudRedisClient, 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 CloudRedisClient create(CloudRedisSettings settings) throws IOException { return new CloudRedisClient(settings); } /** - * Constructs an instance of EchoClient, using the given stub for making calls. This is for + * Constructs an instance of CloudRedisClient, using the given stub for making calls. This is for * advanced usage - prefer using create(CloudRedisSettings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") @@ -127,8 +127,8 @@ public static final CloudRedisClient create(CloudRedisStub 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. + * Constructs an instance of CloudRedisClient, 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 CloudRedisClient(CloudRedisSettings settings) throws IOException { this.settings = settings; From e75e8288a48f1fc37dd3de089e25fc335e0a48a2 Mon Sep 17 00:00:00 2001 From: Mira Leung Date: Fri, 30 Oct 2020 14:32:54 -0700 Subject: [PATCH 26/26] fix: use serviceClient varname in ServiceClient codegen comments --- .../composer/ServiceClientCommentComposer.java | 13 ++++++++----- .../gapic/composer/goldens/IdentityClient.golden | 2 +- .../goldens/asset/AssetServiceClient.java | 4 ++-- .../goldens/logging/ConfigServiceV2Client.java | 5 +++-- .../goldens/logging/LoggingServiceV2Client.java | 5 +++-- .../goldens/logging/MetricsServiceV2Client.java | 5 +++-- .../integration/goldens/redis/CloudRedisClient.java | 2 +- 7 files changed, 21 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java index fca8c84ee9..d36f6c3ac6 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientCommentComposer.java @@ -39,10 +39,6 @@ class ServiceClientCommentComposer { private static final String SERVICE_DESCRIPTION_INTRO_STRING = "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:"; - private static final String SERVICE_DESCRIPTION_CLOSE_STRING = - "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()."; private static final String SERVICE_DESCRIPTION_SURFACE_SUMMARY_STRING = "The surface of this class includes several types of Java methods for each of the API's " + "methods:"; @@ -77,6 +73,11 @@ class ServiceClientCommentComposer { "Constructs an instance of %sClient, using the given stub for making calls. This is for" + " advanced usage - prefer using create(%s)."; + private static final String SERVICE_DESCRIPTION_CLOSE_PATTERN = + "Note: close() needs to be called on the %sClient object to clean up resources such as " + + "threads. In the example above, try-with-resources is used, which automatically calls " + + "close()."; + private static final String SERVICE_DESCRIPTION_CUSTOMIZE_SUMMARY_PATTERN = "This class can be customized by passing in a custom instance of %s to create(). For" + " example:"; @@ -117,7 +118,9 @@ static List createClassHeaderComments(Service service) { // TODO(summerji): Add sample code here. // API surface description. - classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_CLOSE_STRING); + classHeaderJavadocBuilder.addParagraph( + String.format( + SERVICE_DESCRIPTION_CLOSE_PATTERN, JavaStyle.toLowerCamelCase(service.name()))); classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_SURFACE_SUMMARY_STRING); classHeaderJavadocBuilder.addOrderedList(SERVICE_DESCRIPTION_SURFACE_DESCRIPTION); classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_SURFACE_CODA_STRING); diff --git a/src/test/java/com/google/api/generator/gapic/composer/goldens/IdentityClient.golden b/src/test/java/com/google/api/generator/gapic/composer/goldens/IdentityClient.golden index f509765142..0f48757f2b 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/goldens/IdentityClient.golden +++ b/src/test/java/com/google/api/generator/gapic/composer/goldens/IdentityClient.golden @@ -25,7 +25,7 @@ import javax.annotation.Generated; * 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 + *

Note: close() needs to be called on the identityClient 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 diff --git a/test/integration/goldens/asset/AssetServiceClient.java b/test/integration/goldens/asset/AssetServiceClient.java index c45dcbdabd..9c2ed0b961 100644 --- a/test/integration/goldens/asset/AssetServiceClient.java +++ b/test/integration/goldens/asset/AssetServiceClient.java @@ -47,8 +47,8 @@ *

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(). + *

Note: close() needs to be called on the assetServiceClient 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: diff --git a/test/integration/goldens/logging/ConfigServiceV2Client.java b/test/integration/goldens/logging/ConfigServiceV2Client.java index 7e0b805328..bfecf0d814 100644 --- a/test/integration/goldens/logging/ConfigServiceV2Client.java +++ b/test/integration/goldens/logging/ConfigServiceV2Client.java @@ -44,8 +44,9 @@ *

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(). + *

Note: close() needs to be called on the configServiceV2Client 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: diff --git a/test/integration/goldens/logging/LoggingServiceV2Client.java b/test/integration/goldens/logging/LoggingServiceV2Client.java index 838256ea3a..9f9406c0d2 100644 --- a/test/integration/goldens/logging/LoggingServiceV2Client.java +++ b/test/integration/goldens/logging/LoggingServiceV2Client.java @@ -46,8 +46,9 @@ *

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(). + *

Note: close() needs to be called on the loggingServiceV2Client 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: diff --git a/test/integration/goldens/logging/MetricsServiceV2Client.java b/test/integration/goldens/logging/MetricsServiceV2Client.java index 2a1fefb209..01fb3da302 100644 --- a/test/integration/goldens/logging/MetricsServiceV2Client.java +++ b/test/integration/goldens/logging/MetricsServiceV2Client.java @@ -43,8 +43,9 @@ *

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(). + *

Note: close() needs to be called on the metricsServiceV2Client 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: diff --git a/test/integration/goldens/redis/CloudRedisClient.java b/test/integration/goldens/redis/CloudRedisClient.java index 305a9d0e8f..158d71fc5b 100644 --- a/test/integration/goldens/redis/CloudRedisClient.java +++ b/test/integration/goldens/redis/CloudRedisClient.java @@ -67,7 +67,7 @@ *

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 + *

Note: close() needs to be called on the cloudRedisClient 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