diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 33b7738029..13132e39e1 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -49,7 +49,7 @@ jobs: run: bazel --batch test $(bazel query "//src/test/..." | grep "Test$") --noshow_progress - name: Integration Tests - run: bazel --batch test //test/integration:asset //test/integration:credentials //test/integration:iam //test/integration:kms //test/integration:logging //test/integration:redis //test/integration:library --noshow_progress + run: bazel --batch test //test/integration:asset //test/integration:credentials //test/integration:iam //test/integration:kms //test/integration:logging //test/integration:pubsub //test/integration:redis //test/integration:library --noshow_progress - uses: actions/upload-artifact@v2 if: ${{ failure() }} diff --git a/src/main/java/com/google/api/generator/gapic/composer/resourcename/ResourceNameHelperClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/resourcename/ResourceNameHelperClassComposer.java index 7e2d5aa4f3..28b65cd52e 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/resourcename/ResourceNameHelperClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/resourcename/ResourceNameHelperClassComposer.java @@ -51,6 +51,7 @@ import com.google.api.generator.gapic.model.GapicClass; import com.google.api.generator.gapic.model.ResourceName; import com.google.api.generator.gapic.utils.JavaStyle; +import com.google.api.generator.gapic.utils.ResourceNameConstants; import com.google.api.pathtemplate.PathTemplate; import com.google.api.pathtemplate.ValidationException; import com.google.common.annotations.VisibleForTesting; @@ -68,7 +69,6 @@ import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; -import java.util.stream.IntStream; import javax.annotation.Generated; public class ResourceNameHelperClassComposer { @@ -158,14 +158,23 @@ private static List createTemplateClassMembers( VariableExpr.withVariable( Variable.builder() .setName(concatToUpperSnakeCaseName(ts)) - .setType(FIXED_TYPESTORE.get("PathTemplate")) + .setType( + // PubSub special-case handling for the _deleted-topic_ pattern. + ts.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL) + ? TypeNode.STRING + : FIXED_TYPESTORE.get("PathTemplate")) .build())) .collect(Collectors.toList()); } private static Map createPatternTokenClassMembers( List> tokenHierarchies) { - Set tokenSet = getTokenSet(tokenHierarchies); + // PubSub special-case handling - exclude _deleted-topic_. + List> processedTokenHierarchies = + tokenHierarchies.stream() + .filter(ts -> !ts.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) + .collect(Collectors.toList()); + Set tokenSet = getTokenSet(processedTokenHierarchies); return tokenSet.stream() .collect( Collectors.toMap( @@ -197,19 +206,21 @@ private static List createClassStatements( .setIsStatic(true) .setIsFinal(true) .build(); - Expr createWithoutUrlEncodingExpr = + String pattern = patterns.get(i); + Expr valueExpr = MethodInvocationExpr.builder() .setStaticReferenceType(FIXED_TYPESTORE.get("PathTemplate")) .setMethodName("createWithoutUrlEncoding") .setArguments( - Arrays.asList(ValueExpr.withValue(StringObjectValue.withValue(patterns.get(i))))) + Arrays.asList(ValueExpr.withValue(StringObjectValue.withValue(pattern)))) .setReturnType(FIXED_TYPESTORE.get("PathTemplate")) .build(); + // PubSub special-case handling for _deleted-topic_. + if (pattern.equals(ResourceNameConstants.DELETED_TOPIC_LITERAL)) { + valueExpr = ValueExpr.withValue(StringObjectValue.withValue(pattern)); + } memberVars.add( - AssignmentExpr.builder() - .setVariableExpr(varExpr) - .setValueExpr(createWithoutUrlEncodingExpr) - .build()); + AssignmentExpr.builder().setVariableExpr(varExpr).setValueExpr(valueExpr).build()); } memberVars.add( @@ -231,8 +242,13 @@ private static List createClassStatements( // Use the token set as a key to maintain ordering (for consistency). Function toFinalDeclFn = v -> v.toBuilder().setIsDecl(true).setScope(ScopeNode.PRIVATE).setIsFinal(true).build(); + // Special-cased PubSub handling. + List> processedTokenHierarchies = + tokenHierarchies.stream() + .filter(tokens -> !tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) + .collect(Collectors.toList()); memberVars.addAll( - getTokenSet(tokenHierarchies).stream() + getTokenSet(processedTokenHierarchies).stream() .map(t -> toFinalDeclFn.apply(patternTokenVarExprs.get(t))) .collect(Collectors.toList())); return memberVars.stream().map(e -> ExprStatement.withExpr(e)).collect(Collectors.toList()); @@ -297,6 +313,13 @@ private static List createConstructorMethods( .setValueExpr(nullExpr) .build(); + // Special-cased PubSub handling. + List> processedTokenHierarchies = + tokenHierarchies.stream() + .filter(tokens -> !tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) + .collect(Collectors.toList()); + boolean hasDeletedTopicPattern = tokenHierarchies.size() > processedTokenHierarchies.size(); + // First deprecated constructor. javaMethods.add( MethodDefinition.constructorBuilder() @@ -307,15 +330,16 @@ private static List createConstructorMethods( .setScope(ScopeNode.PROTECTED) .setReturnType(thisClassType) .setBody( - getTokenSet(tokenHierarchies).stream() + getTokenSet(processedTokenHierarchies).stream() .map(t -> ExprStatement.withExpr(assignTokenToNullExpr.apply(t))) .collect(Collectors.toList())) .build()); - for (int i = 0; i < tokenHierarchies.size(); i++) { - List tokens = tokenHierarchies.get(i); + for (int i = 0; i < processedTokenHierarchies.size(); i++) { + List tokens = processedTokenHierarchies.get(i); + List bodyExprs = new ArrayList<>(); - TypeNode argType = getBuilderType(typeStore, tokenHierarchies, i); + TypeNode argType = getBuilderType(typeStore, processedTokenHierarchies, i); VariableExpr builderArgExpr = VariableExpr.withVariable(Variable.builder().setName("builder").setType(argType).build()); for (String token : tokens) { @@ -339,7 +363,7 @@ private static List createConstructorMethods( .build()); } // Initialize the rest to null. - for (String token : getTokenSet(tokenHierarchies)) { + for (String token : getTokenSet(processedTokenHierarchies)) { if (tokens.contains(token)) { continue; } @@ -368,12 +392,66 @@ private static List createConstructorMethods( .build()); } + if (hasDeletedTopicPattern) { + Expr thisExpr = ValueExpr.withValue(ThisObjectValue.withType(thisClassType)); + // PubSub special-case handling for the _deleted-topic_ pattern - add an extra constructor. + // private TopicName(String fixedValue) { + // this.fixedValue = fixedValue; + // fieldValuesMap = ImmutableMap.of("", fixedValue); + // } + VariableExpr fixedValueVarExpr = + VariableExpr.withVariable( + Variable.builder().setName("fixedValue").setType(TypeNode.STRING).build()); + List specialCtorBodyExprs = new ArrayList<>(); + specialCtorBodyExprs.add( + AssignmentExpr.builder() + .setVariableExpr( + VariableExpr.builder() + .setExprReferenceExpr(thisExpr) + .setVariable(fixedValueVarExpr.variable()) + .build()) + .setValueExpr(fixedValueVarExpr) + .build()); + specialCtorBodyExprs.add( + AssignmentExpr.builder() + .setVariableExpr(FIXED_CLASS_VARS.get("fieldValuesMap")) + .setValueExpr( + MethodInvocationExpr.builder() + .setStaticReferenceType(FIXED_TYPESTORE.get("ImmutableMap")) + .setMethodName("of") + .setArguments( + ValueExpr.withValue(StringObjectValue.withValue("")), fixedValueVarExpr) + .setReturnType(FIXED_TYPESTORE.get("ImmutableMap")) + .build()) + .build()); + specialCtorBodyExprs.addAll( + getTokenSet(processedTokenHierarchies).stream() + .map(t -> assignTokenToNullExpr.apply(t)) + .collect(Collectors.toList())); + + javaMethods.add( + MethodDefinition.constructorBuilder() + .setScope(ScopeNode.PRIVATE) + .setReturnType(thisClassType) + .setArguments(Arrays.asList(fixedValueVarExpr.toBuilder().setIsDecl(true).build())) + .setBody( + specialCtorBodyExprs.stream() + .map(e -> ExprStatement.withExpr(e)) + .collect(Collectors.toList())) + .build()); + } + return javaMethods; } private static List createTokenGetterMethods( Map patternTokenVarExprs, List> tokenHierarchies) { - return getTokenSet(tokenHierarchies).stream() + // PubSub special-case handling. + List> processedTokenHierarchies = + tokenHierarchies.stream() + .filter(ts -> !ts.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) + .collect(Collectors.toList()); + return getTokenSet(processedTokenHierarchies).stream() .map( t -> MethodDefinition.builder() @@ -400,6 +478,11 @@ private static List createBuilderCreatorMethods( // Create the newBuilder and variation methods here. // Variation example: newProjectLocationAutoscalingPolicyBuilder(). for (int i = 0; i < tokenHierarchies.size(); i++) { + // PubSub special-case handling. + if (tokenHierarchies.get(i).contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) { + continue; + } + final TypeNode returnType = getBuilderType(typeStore, tokenHierarchies, i); final Expr returnExpr = NewObjectExpr.withType(returnType); @@ -495,6 +578,31 @@ private static List createOfOrFormatMethodHelper( boolean hasVariants = tokenHierarchies.size() > 1; for (int i = 0; i < tokenHierarchies.size(); i++) { List tokens = tokenHierarchies.get(i); + // PubSub special-case handling. + if (tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) { + Expr deletedTopicStringValExpr = + ValueExpr.withValue( + StringObjectValue.withValue(ResourceNameConstants.DELETED_TOPIC_LITERAL)); + // Simply return `new TopicName("_deleted-topic_")` or the string value itself. + javaMethods.add( + MethodDefinition.builder() + .setScope(ScopeNode.PUBLIC) + .setIsStatic(true) + .setAnnotations(annotations) + .setReturnType(returnType) + .setName( + String.format(methodNameFormat, concatToUpperCamelCaseName(tokens) + "Name")) + .setReturnExpr( + returnType.equals(TypeNode.STRING) + ? deletedTopicStringValExpr + : NewObjectExpr.builder() + .setType(returnType) + .setArguments(deletedTopicStringValExpr) + .build()) + .build()); + continue; + } + String builderMethodName = String.format(newBuilderMethodNameFormat, getBuilderTypeName(tokenHierarchies, i)); @@ -542,8 +650,7 @@ private static List createOfOrFormatMethodHelper( .setReturnType(returnType) .setName( String.format( - methodNameFormat, - i == 0 ? "" : concatToUpperCamelCaseName(tokenHierarchies.get(i)) + "Name")) + methodNameFormat, i == 0 ? "" : concatToUpperCamelCaseName(tokens) + "Name")) .setArguments(methodArgs) .setReturnExpr(returnExpr) .build()); @@ -679,11 +786,15 @@ private static MethodDefinition createParseMethod( IfStatement.Builder ifStatementBuilder = IfStatement.builder(); String ofMethodNamePattern = "of%sName"; for (int i = 0; i < tokenHierarchies.size(); i++) { + // PubSub special-case handling for the "_deleted-topic_" pattern. + boolean isDeletedTopicPattern = + tokenHierarchies.get(i).contains(ResourceNameConstants.DELETED_TOPIC_LITERAL); + VariableExpr templateVarExpr = templateFinalVarExprs.get(i); MethodInvocationExpr conditionExpr = MethodInvocationExpr.builder() .setExprReferenceExpr(templateVarExpr) - .setMethodName("matches") + .setMethodName(isDeletedTopicPattern ? "equals" : "matches") .setArguments(formattedStringArgList) .setReturnType(TypeNode.BOOLEAN) .build(); @@ -730,6 +841,21 @@ private static MethodDefinition createParseMethod( ifStatementBuilder = ifStatementBuilder.setConditionExpr(conditionExpr).setBody(ifStatements); } else { + // PubSub special-case handling - clobber ifStatements if the current pattern is + // _deleted-topic_. + if (isDeletedTopicPattern) { + ifStatements.clear(); + ifStatements.add( + ExprStatement.withExpr( + ReturnExpr.withExpr( + NewObjectExpr.builder() + .setType(thisClassType) + .setArguments( + ValueExpr.withValue( + StringObjectValue.withValue( + ResourceNameConstants.DELETED_TOPIC_LITERAL))) + .build()))); + } ifStatementBuilder = ifStatementBuilder.addElseIf(conditionExpr, ifStatements); } } @@ -923,12 +1049,17 @@ private static MethodDefinition createIsParseableFromMethod( .setReturnType(TypeNode.BOOLEAN) .build(); for (int i = 1; i < templateFinalVarExprs.size(); i++) { + VariableExpr templateVarExpr = templateFinalVarExprs.get(i); returnOrExpr = LogicalOperationExpr.logicalOrWithExprs( returnOrExpr, MethodInvocationExpr.builder() - .setExprReferenceExpr(templateFinalVarExprs.get(i)) - .setMethodName("matches") + .setExprReferenceExpr(templateVarExpr) + .setMethodName( + // PubSub special-case handling for the _deleted-topic_ pattern. + templateVarExpr.variable().identifier().name().equals("DELETED_TOPIC") + ? "equals" + : "matches") .setArguments(Arrays.asList(formattedStringVarExpr)) .setReturnType(TypeNode.BOOLEAN) .build()); @@ -986,9 +1117,15 @@ private static MethodDefinition createGetFieldValuesMapMethod( .build()) .build(); + // Special-cased PubSub handling. + List> processedTokenHierarchies = + tokenHierarchies.stream() + .filter(tokens -> !tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) + .collect(Collectors.toList()); + // Innermost if-blocks. List tokenIfStatements = new ArrayList<>(); - for (String token : getTokenSet(tokenHierarchies)) { + for (String token : getTokenSet(processedTokenHierarchies)) { VariableExpr tokenVarExpr = patternTokenVarExprs.get(token); Preconditions.checkNotNull( tokenVarExpr, @@ -1188,8 +1325,14 @@ private static MethodDefinition createEqualsMethod( .setValueExpr(oCastExpr) .build(); + // PubSub special-case handling - exclude _deleted-topic_. + List> processedTokenHierarchies = + tokenHierarchies.stream() + .filter(ts -> !ts.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) + .collect(Collectors.toList()); + // Create return expression in the second if statement's body. - Set tokenSet = getTokenSet(tokenHierarchies); + Set tokenSet = getTokenSet(processedTokenHierarchies); Iterator itToken = tokenSet.iterator(); Expr curTokenExpr = createObjectsEqualsForTokenMethodExpr( @@ -1279,8 +1422,15 @@ private static MethodDefinition createHashCodeMethod(List> tokenHie PrimitiveValue.builder().setType(TypeNode.INT).setValue("1000003").build()); AssignmentOperationExpr multiplyAssignmentOpExpr = AssignmentOperationExpr.multiplyAssignmentWithExprs(hVarExpr, numValueExpr); + + // PubSub special-case handling - exclude _deleted-topic_. + List> processedTokenHierarchies = + tokenHierarchies.stream() + .filter(ts -> !ts.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) + .collect(Collectors.toList()); + // If it has variants, add the multiply and xor assignment operation exprs for fixedValue. - boolean hasVariants = tokenHierarchies.size() > 1; + boolean hasVariants = processedTokenHierarchies.size() > 1; if (hasVariants) { VariableExpr fixedValueVarExpr = FIXED_CLASS_VARS.get("fixedValue"); assignmentBody.add(ExprStatement.withExpr(multiplyAssignmentOpExpr)); @@ -1290,7 +1440,7 @@ private static MethodDefinition createHashCodeMethod(List> tokenHie hVarExpr, createObjectsHashCodeForVarMethod(fixedValueVarExpr)))); } // Add the multiply and xor assignment operation exprs for tokens. - Set tokenSet = getTokenSet(tokenHierarchies); + Set tokenSet = getTokenSet(processedTokenHierarchies); tokenSet.stream() .forEach( token -> { @@ -1335,18 +1485,24 @@ private static List createNestedBuilderClasses( String thisClassName = getThisClassName(resourceName); TypeNode outerThisClassType = typeStore.get(thisClassName); boolean hasVariants = tokenHierarchies.size() > 1; - return IntStream.range(0, tokenHierarchies.size()) - .mapToObj( - i -> - createNestedBuilderClass( - outerThisClassType, - tokenHierarchies.get(i), - templateFinalVarExprs.get(i), - resourceName.patterns().get(i), - typeStore, - hasVariants, - i == 0)) - .collect(Collectors.toList()); + List nestedClasses = new ArrayList<>(); + for (int i = 0; i < tokenHierarchies.size(); i++) { + List tokens = tokenHierarchies.get(i); + // PubSub special-case handling. + if (tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) { + continue; + } + nestedClasses.add( + createNestedBuilderClass( + outerThisClassType, + tokens, + templateFinalVarExprs.get(i), + resourceName.patterns().get(i), + typeStore, + hasVariants, + i == 0)); + } + return nestedClasses; } private static ClassDefinition createNestedBuilderClass( @@ -1554,7 +1710,13 @@ private static TypeStore createDynamicTypes( typeStore.put(resourceName.pakkage(), thisClassName); typeStore.put(resourceName.pakkage(), "Builder", true, thisClassName); - if (tokenHierarchies.size() > 1) { + // Special-cased PubSub handling. + List> processedTokenHierarchies = + tokenHierarchies.stream() + .filter(tokens -> !tokens.contains(ResourceNameConstants.DELETED_TOPIC_LITERAL)) + .collect(Collectors.toList()); + + if (processedTokenHierarchies.size() > 1) { typeStore.putAll( resourceName.pakkage(), tokenHierarchies.subList(1, tokenHierarchies.size()).stream() diff --git a/src/main/java/com/google/api/generator/gapic/composer/resourcename/ResourceNameTokenizer.java b/src/main/java/com/google/api/generator/gapic/composer/resourcename/ResourceNameTokenizer.java index 18cfd81c0c..4a72abeac6 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/resourcename/ResourceNameTokenizer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/resourcename/ResourceNameTokenizer.java @@ -14,6 +14,7 @@ package com.google.api.generator.gapic.composer.resourcename; +import com.google.api.generator.gapic.utils.ResourceNameConstants; import com.google.api.pathtemplate.PathTemplate; import com.google.common.base.Preconditions; import java.util.ArrayList; @@ -42,6 +43,12 @@ public static List> parseTokenHierarchy(List patterns) { // Process variables. for (String rawPatternToken : rawPatternTokens) { + // PubSub exception case. + if (rawPatternToken.equals(ResourceNameConstants.DELETED_TOPIC_LITERAL)) { + hierarchy.add(rawPatternToken); + continue; + } + if (!rawPatternToken.startsWith(LEFT_BRACE) || !rawPatternToken.endsWith(RIGHT_BRACE)) { continue; } diff --git a/src/main/java/com/google/api/generator/gapic/utils/JavaStyle.java b/src/main/java/com/google/api/generator/gapic/utils/JavaStyle.java index ba9c38d455..90efae459e 100644 --- a/src/main/java/com/google/api/generator/gapic/utils/JavaStyle.java +++ b/src/main/java/com/google/api/generator/gapic/utils/JavaStyle.java @@ -26,6 +26,8 @@ public static String toLowerCamelCase(String s) { return s; } + s = s.replace('-', '_'); + if (s.indexOf(UNDERSCORE) >= 0) { s = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, s); } @@ -39,6 +41,8 @@ public static String toUpperCamelCase(String s) { return s; } + s = s.replace('-', '_'); + if (s.indexOf(UNDERSCORE) >= 0) { s = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, s); } diff --git a/test/integration/BUILD.bazel b/test/integration/BUILD.bazel index 24d2c9d104..23360e672b 100644 --- a/test/integration/BUILD.bazel +++ b/test/integration/BUILD.bazel @@ -25,6 +25,7 @@ INTEGRATION_TEST_LIBRARIES = [ "credentials", # Check that the capital name edge case is handled. "iam", # Mixin-only special-case API can build on its own. "kms", # Mixins, with an override in the proto file. + "pubsub", # Special=case handling for "_deleted-topic_" resource name patterns. "logging", # Java package remapping in gapic.yaml. "redis", # Has a gapic.yaml. "library", # No gRPC service config. @@ -36,6 +37,7 @@ API_GAPIC_TARGETS = { "credentials": "@com_google_googleapis//google/iam/credentials/v1:credentials_java_gapic", "iam": ":iam_java_gapic", # Googleapis' LRO does not have a Java Gapic. "kms": ":kms_java_gapic", # Local target because mixins are not rolled out yet. + "pubsub": ":pubsub_java_gapic", "logging": "@com_google_googleapis//google/logging/v2:logging_java_gapic", "redis": "@com_google_googleapis//google/cloud/redis/v1beta1:redis_java_gapic", "library": "@com_google_googleapis//google/example/library/v1:library_java_gapic", @@ -274,3 +276,41 @@ java_gapic_assembly_gradle_pkg( "@com_google_googleapis//google/cloud/location:location_java_proto", ], ) + +# PubSub +# TODO: Remove some of these targets when PubSub has been migrated in googleapis. +java_gapic_library( + name = "pubsub_java_gapic", + srcs = ["@com_google_googleapis//google/pubsub/v1:pubsub_proto_with_info"], + gapic_yaml = "@com_google_googleapis//google/pubsub/v1:pubsub_gapic.yaml", + grpc_service_config = "@com_google_googleapis//google/pubsub/v1:pubsub_grpc_service_config.json", + # For the IAM mixin. + service_yaml = "pubsub_v1.yaml", + test_deps = [ + "@com_google_googleapis//google/pubsub/v1:pubsub_java_grpc", + "@com_google_googleapis//google/iam/v1:iam_java_grpc", + ], + deps = [ + "@com_google_googleapis//google/iam/v1:iam_java_proto", + "@com_google_googleapis//google/pubsub/v1:pubsub_java_proto", + ], +) + +java_gapic_test( + name = "pubsub_java_gapic_test_suite", + test_classes = [ + "com.google.cloud.pubsub.v1.SubscriptionAdminClientTest", + "com.google.cloud.pubsub.v1.TopicAdminClientTest", + ], + runtime_deps = [":pubsub_java_gapic_test"], +) + +java_gapic_assembly_gradle_pkg( + name = "google-cloud-pubsub-v1-java", + deps = [ + ":pubsub_java_gapic", + "@com_google_googleapis//google/pubsub/v1:pubsub_java_grpc", + "@com_google_googleapis//google/pubsub/v1:pubsub_java_proto", + "@com_google_googleapis//google/pubsub/v1:pubsub_proto", + ], +) diff --git a/test/integration/goldens/pubsub/BUILD.bazel b/test/integration/goldens/pubsub/BUILD.bazel new file mode 100644 index 0000000000..667772f01b --- /dev/null +++ b/test/integration/goldens/pubsub/BUILD.bazel @@ -0,0 +1,9 @@ +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "goldens_files", + srcs = glob([ + "*.java", + "gapic_metadata.json", + ]), +) diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockIAMPolicy.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockIAMPolicy.java new file mode 100644 index 0000000000..e7583f2d95 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockIAMPolicy.java @@ -0,0 +1,59 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +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 MockIAMPolicy implements MockGrpcService { + private final MockIAMPolicyImpl serviceImpl; + + public MockIAMPolicy() { + serviceImpl = new MockIAMPolicyImpl(); + } + + @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/pubsub/com/google/cloud/pubsub/v1/MockIAMPolicyImpl.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockIAMPolicyImpl.java new file mode 100644 index 0000000000..836144b7ee --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockIAMPolicyImpl.java @@ -0,0 +1,127 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +import com.google.api.core.BetaApi; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.IAMPolicyGrpc.IAMPolicyImplBase; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.AbstractMessage; +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 MockIAMPolicyImpl extends IAMPolicyImplBase { + private List requests; + private Queue responses; + + public MockIAMPolicyImpl() { + 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 setIamPolicy(SetIamPolicyRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Policy) { + requests.add(request); + responseObserver.onNext(((Policy) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method SetIamPolicy, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Policy.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void getIamPolicy(GetIamPolicyRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Policy) { + requests.add(request); + responseObserver.onNext(((Policy) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method GetIamPolicy, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Policy.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void testIamPermissions( + TestIamPermissionsRequest request, + StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof TestIamPermissionsResponse) { + requests.add(request); + responseObserver.onNext(((TestIamPermissionsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method TestIamPermissions, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + TestIamPermissionsResponse.class.getName(), + Exception.class.getName()))); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockPublisher.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockPublisher.java new file mode 100644 index 0000000000..78513630a5 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockPublisher.java @@ -0,0 +1,59 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +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 MockPublisher implements MockGrpcService { + private final MockPublisherImpl serviceImpl; + + public MockPublisher() { + serviceImpl = new MockPublisherImpl(); + } + + @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/pubsub/com/google/cloud/pubsub/v1/MockPublisherImpl.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockPublisherImpl.java new file mode 100644 index 0000000000..9209178584 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockPublisherImpl.java @@ -0,0 +1,262 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +import com.google.api.core.BetaApi; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.DeleteTopicRequest; +import com.google.pubsub.v1.DetachSubscriptionRequest; +import com.google.pubsub.v1.DetachSubscriptionResponse; +import com.google.pubsub.v1.GetTopicRequest; +import com.google.pubsub.v1.ListTopicSnapshotsRequest; +import com.google.pubsub.v1.ListTopicSnapshotsResponse; +import com.google.pubsub.v1.ListTopicSubscriptionsRequest; +import com.google.pubsub.v1.ListTopicSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ListTopicsResponse; +import com.google.pubsub.v1.PublishRequest; +import com.google.pubsub.v1.PublishResponse; +import com.google.pubsub.v1.PublisherGrpc.PublisherImplBase; +import com.google.pubsub.v1.Topic; +import com.google.pubsub.v1.UpdateTopicRequest; +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 MockPublisherImpl extends PublisherImplBase { + private List requests; + private Queue responses; + + public MockPublisherImpl() { + 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 createTopic(Topic request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Topic) { + requests.add(request); + responseObserver.onNext(((Topic) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method CreateTopic, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Topic.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void updateTopic(UpdateTopicRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Topic) { + requests.add(request); + responseObserver.onNext(((Topic) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method UpdateTopic, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Topic.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void publish(PublishRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof PublishResponse) { + requests.add(request); + responseObserver.onNext(((PublishResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method Publish, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + PublishResponse.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void getTopic(GetTopicRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Topic) { + requests.add(request); + responseObserver.onNext(((Topic) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method GetTopic, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Topic.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void listTopics( + ListTopicsRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof ListTopicsResponse) { + requests.add(request); + responseObserver.onNext(((ListTopicsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method ListTopics, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + ListTopicsResponse.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void listTopicSubscriptions( + ListTopicSubscriptionsRequest request, + StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof ListTopicSubscriptionsResponse) { + requests.add(request); + responseObserver.onNext(((ListTopicSubscriptionsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method ListTopicSubscriptions, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + ListTopicSubscriptionsResponse.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void listTopicSnapshots( + ListTopicSnapshotsRequest request, + StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof ListTopicSnapshotsResponse) { + requests.add(request); + responseObserver.onNext(((ListTopicSnapshotsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method ListTopicSnapshots, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + ListTopicSnapshotsResponse.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void deleteTopic(DeleteTopicRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + 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( + String.format( + "Unrecognized response type %s for method DeleteTopic, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Empty.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void detachSubscription( + DetachSubscriptionRequest request, + StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof DetachSubscriptionResponse) { + requests.add(request); + responseObserver.onNext(((DetachSubscriptionResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method DetachSubscription, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + DetachSubscriptionResponse.class.getName(), + Exception.class.getName()))); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockSchemaService.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockSchemaService.java new file mode 100644 index 0000000000..a7fc32c585 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockSchemaService.java @@ -0,0 +1,59 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +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 MockSchemaService implements MockGrpcService { + private final MockSchemaServiceImpl serviceImpl; + + public MockSchemaService() { + serviceImpl = new MockSchemaServiceImpl(); + } + + @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/pubsub/com/google/cloud/pubsub/v1/MockSchemaServiceImpl.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockSchemaServiceImpl.java new file mode 100644 index 0000000000..5b908db486 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockSchemaServiceImpl.java @@ -0,0 +1,194 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +import com.google.api.core.BetaApi; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.CreateSchemaRequest; +import com.google.pubsub.v1.DeleteSchemaRequest; +import com.google.pubsub.v1.GetSchemaRequest; +import com.google.pubsub.v1.ListSchemasRequest; +import com.google.pubsub.v1.ListSchemasResponse; +import com.google.pubsub.v1.Schema; +import com.google.pubsub.v1.SchemaServiceGrpc.SchemaServiceImplBase; +import com.google.pubsub.v1.ValidateMessageRequest; +import com.google.pubsub.v1.ValidateMessageResponse; +import com.google.pubsub.v1.ValidateSchemaRequest; +import com.google.pubsub.v1.ValidateSchemaResponse; +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 MockSchemaServiceImpl extends SchemaServiceImplBase { + private List requests; + private Queue responses; + + public MockSchemaServiceImpl() { + 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 createSchema(CreateSchemaRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Schema) { + requests.add(request); + responseObserver.onNext(((Schema) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method CreateSchema, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Schema.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void getSchema(GetSchemaRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Schema) { + requests.add(request); + responseObserver.onNext(((Schema) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method GetSchema, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Schema.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void listSchemas( + ListSchemasRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof ListSchemasResponse) { + requests.add(request); + responseObserver.onNext(((ListSchemasResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method ListSchemas, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + ListSchemasResponse.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void deleteSchema(DeleteSchemaRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + 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( + String.format( + "Unrecognized response type %s for method DeleteSchema, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Empty.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void validateSchema( + ValidateSchemaRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof ValidateSchemaResponse) { + requests.add(request); + responseObserver.onNext(((ValidateSchemaResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method ValidateSchema, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + ValidateSchemaResponse.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void validateMessage( + ValidateMessageRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof ValidateMessageResponse) { + requests.add(request); + responseObserver.onNext(((ValidateMessageResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method ValidateMessage, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + ValidateMessageResponse.class.getName(), + Exception.class.getName()))); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockSubscriber.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockSubscriber.java new file mode 100644 index 0000000000..8d3f29fe09 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockSubscriber.java @@ -0,0 +1,59 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +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 MockSubscriber implements MockGrpcService { + private final MockSubscriberImpl serviceImpl; + + public MockSubscriber() { + serviceImpl = new MockSubscriberImpl(); + } + + @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/pubsub/com/google/cloud/pubsub/v1/MockSubscriberImpl.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockSubscriberImpl.java new file mode 100644 index 0000000000..a181138d93 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/MockSubscriberImpl.java @@ -0,0 +1,432 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +import com.google.api.core.BetaApi; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.AcknowledgeRequest; +import com.google.pubsub.v1.CreateSnapshotRequest; +import com.google.pubsub.v1.DeleteSnapshotRequest; +import com.google.pubsub.v1.DeleteSubscriptionRequest; +import com.google.pubsub.v1.GetSnapshotRequest; +import com.google.pubsub.v1.GetSubscriptionRequest; +import com.google.pubsub.v1.ListSnapshotsRequest; +import com.google.pubsub.v1.ListSnapshotsResponse; +import com.google.pubsub.v1.ListSubscriptionsRequest; +import com.google.pubsub.v1.ListSubscriptionsResponse; +import com.google.pubsub.v1.ModifyAckDeadlineRequest; +import com.google.pubsub.v1.ModifyPushConfigRequest; +import com.google.pubsub.v1.PullRequest; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.SeekRequest; +import com.google.pubsub.v1.SeekResponse; +import com.google.pubsub.v1.Snapshot; +import com.google.pubsub.v1.StreamingPullRequest; +import com.google.pubsub.v1.StreamingPullResponse; +import com.google.pubsub.v1.SubscriberGrpc.SubscriberImplBase; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.UpdateSnapshotRequest; +import com.google.pubsub.v1.UpdateSubscriptionRequest; +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 MockSubscriberImpl extends SubscriberImplBase { + private List requests; + private Queue responses; + + public MockSubscriberImpl() { + 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 createSubscription( + Subscription request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Subscription) { + requests.add(request); + responseObserver.onNext(((Subscription) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method CreateSubscription, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Subscription.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void getSubscription( + GetSubscriptionRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Subscription) { + requests.add(request); + responseObserver.onNext(((Subscription) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method GetSubscription, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Subscription.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void updateSubscription( + UpdateSubscriptionRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Subscription) { + requests.add(request); + responseObserver.onNext(((Subscription) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method UpdateSubscription, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Subscription.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void listSubscriptions( + ListSubscriptionsRequest request, + StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof ListSubscriptionsResponse) { + requests.add(request); + responseObserver.onNext(((ListSubscriptionsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method ListSubscriptions, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + ListSubscriptionsResponse.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void deleteSubscription( + DeleteSubscriptionRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + 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( + String.format( + "Unrecognized response type %s for method DeleteSubscription, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Empty.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void modifyAckDeadline( + ModifyAckDeadlineRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + 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( + String.format( + "Unrecognized response type %s for method ModifyAckDeadline, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Empty.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void acknowledge(AcknowledgeRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + 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( + String.format( + "Unrecognized response type %s for method Acknowledge, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Empty.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void pull(PullRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof PullResponse) { + requests.add(request); + responseObserver.onNext(((PullResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method Pull, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + PullResponse.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public StreamObserver streamingPull( + final StreamObserver responseObserver) { + StreamObserver requestObserver = + new StreamObserver() { + @Override + public void onNext(StreamingPullRequest value) { + requests.add(value); + final Object response = responses.remove(); + if (response instanceof StreamingPullResponse) { + responseObserver.onNext(((StreamingPullResponse) response)); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method StreamingPull, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + StreamingPullResponse.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void onError(Throwable t) { + responseObserver.onError(t); + } + + @Override + public void onCompleted() { + responseObserver.onCompleted(); + } + }; + return requestObserver; + } + + @Override + public void modifyPushConfig( + ModifyPushConfigRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + 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( + String.format( + "Unrecognized response type %s for method ModifyPushConfig, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Empty.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void getSnapshot(GetSnapshotRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Snapshot) { + requests.add(request); + responseObserver.onNext(((Snapshot) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method GetSnapshot, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Snapshot.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void listSnapshots( + ListSnapshotsRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof ListSnapshotsResponse) { + requests.add(request); + responseObserver.onNext(((ListSnapshotsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method ListSnapshots, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + ListSnapshotsResponse.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void createSnapshot( + CreateSnapshotRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Snapshot) { + requests.add(request); + responseObserver.onNext(((Snapshot) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method CreateSnapshot, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Snapshot.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void updateSnapshot( + UpdateSnapshotRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof Snapshot) { + requests.add(request); + responseObserver.onNext(((Snapshot) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method UpdateSnapshot, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Snapshot.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void deleteSnapshot( + DeleteSnapshotRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + 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( + String.format( + "Unrecognized response type %s for method DeleteSnapshot, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + Empty.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void seek(SeekRequest request, StreamObserver responseObserver) { + Object response = responses.poll(); + if (response instanceof SeekResponse) { + requests.add(request); + responseObserver.onNext(((SeekResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method Seek, expected %s or %s", + response == null ? "null" : response.getClass().getName(), + SeekResponse.class.getName(), + Exception.class.getName()))); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SchemaServiceClient.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SchemaServiceClient.java new file mode 100644 index 0000000000..13acfd990c --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SchemaServiceClient.java @@ -0,0 +1,1033 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +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.cloud.pubsub.v1.stub.SchemaServiceStub; +import com.google.cloud.pubsub.v1.stub.SchemaServiceStubSettings; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.ProjectName; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.CreateSchemaRequest; +import com.google.pubsub.v1.DeleteSchemaRequest; +import com.google.pubsub.v1.GetSchemaRequest; +import com.google.pubsub.v1.ListSchemasRequest; +import com.google.pubsub.v1.ListSchemasResponse; +import com.google.pubsub.v1.Schema; +import com.google.pubsub.v1.SchemaName; +import com.google.pubsub.v1.ValidateMessageRequest; +import com.google.pubsub.v1.ValidateMessageResponse; +import com.google.pubsub.v1.ValidateSchemaRequest; +import com.google.pubsub.v1.ValidateSchemaResponse; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * This class provides the ability to make remote calls to the backing service through method calls + * that map to API methods. Sample code to get started: + * + *
{@code
+ * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+ *   ProjectName parent = ProjectName.of("[PROJECT]");
+ *   Schema schema = Schema.newBuilder().build();
+ *   String schemaId = "schemaId-697673060";
+ *   Schema response = schemaServiceClient.createSchema(parent, schema, schemaId);
+ * }
+ * }
+ * + *

Note: close() needs to be called on the SchemaServiceClient 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 SchemaServiceSettings to + * create(). For example: + * + *

To customize credentials: + * + *

{@code
+ * SchemaServiceSettings schemaServiceSettings =
+ *     SchemaServiceSettings.newBuilder()
+ *         .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
+ *         .build();
+ * SchemaServiceClient schemaServiceClient = SchemaServiceClient.create(schemaServiceSettings);
+ * }
+ * + *

To customize the endpoint: + * + *

{@code
+ * SchemaServiceSettings schemaServiceSettings =
+ *     SchemaServiceSettings.newBuilder().setEndpoint(myEndpoint).build();
+ * SchemaServiceClient schemaServiceClient = SchemaServiceClient.create(schemaServiceSettings);
+ * }
+ * + *

Please refer to the GitHub repository's samples for more quickstart code snippets. + */ +@Generated("by gapic-generator-java") +public class SchemaServiceClient implements BackgroundResource { + private final SchemaServiceSettings settings; + private final SchemaServiceStub stub; + + /** Constructs an instance of SchemaServiceClient with default settings. */ + public static final SchemaServiceClient create() throws IOException { + return create(SchemaServiceSettings.newBuilder().build()); + } + + /** + * Constructs an instance of SchemaServiceClient, 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 SchemaServiceClient create(SchemaServiceSettings settings) + throws IOException { + return new SchemaServiceClient(settings); + } + + /** + * Constructs an instance of SchemaServiceClient, using the given stub for making calls. This is + * for advanced usage - prefer using create(SchemaServiceSettings). + */ + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public static final SchemaServiceClient create(SchemaServiceStub stub) { + return new SchemaServiceClient(stub); + } + + /** + * Constructs an instance of SchemaServiceClient, 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 SchemaServiceClient(SchemaServiceSettings settings) throws IOException { + this.settings = settings; + this.stub = ((SchemaServiceStubSettings) settings.getStubSettings()).createStub(); + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + protected SchemaServiceClient(SchemaServiceStub stub) { + this.settings = null; + this.stub = stub; + } + + public final SchemaServiceSettings getSettings() { + return settings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public SchemaServiceStub getStub() { + return stub; + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   ProjectName parent = ProjectName.of("[PROJECT]");
+   *   Schema schema = Schema.newBuilder().build();
+   *   String schemaId = "schemaId-697673060";
+   *   Schema response = schemaServiceClient.createSchema(parent, schema, schemaId);
+   * }
+   * }
+ * + * @param parent Required. The name of the project in which to create the schema. Format is + * `projects/{project-id}`. + * @param schema Required. The schema object to create. + *

This schema's `name` parameter is ignored. The schema object returned by CreateSchema + * will have a `name` made using the given `parent` and `schema_id`. + * @param schemaId The ID to use for the schema, which will become the final component of the + * schema's resource name. + *

See https://cloud.google.com/pubsub/docs/admin#resource_names for resource name + * constraints. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Schema createSchema(ProjectName parent, Schema schema, String schemaId) { + CreateSchemaRequest request = + CreateSchemaRequest.newBuilder() + .setParent(parent == null ? null : parent.toString()) + .setSchema(schema) + .setSchemaId(schemaId) + .build(); + return createSchema(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   String parent = SchemaName.of("[PROJECT]", "[SCHEMA]").toString();
+   *   Schema schema = Schema.newBuilder().build();
+   *   String schemaId = "schemaId-697673060";
+   *   Schema response = schemaServiceClient.createSchema(parent, schema, schemaId);
+   * }
+   * }
+ * + * @param parent Required. The name of the project in which to create the schema. Format is + * `projects/{project-id}`. + * @param schema Required. The schema object to create. + *

This schema's `name` parameter is ignored. The schema object returned by CreateSchema + * will have a `name` made using the given `parent` and `schema_id`. + * @param schemaId The ID to use for the schema, which will become the final component of the + * schema's resource name. + *

See https://cloud.google.com/pubsub/docs/admin#resource_names for resource name + * constraints. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Schema createSchema(String parent, Schema schema, String schemaId) { + CreateSchemaRequest request = + CreateSchemaRequest.newBuilder() + .setParent(parent) + .setSchema(schema) + .setSchemaId(schemaId) + .build(); + return createSchema(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   CreateSchemaRequest request =
+   *       CreateSchemaRequest.newBuilder()
+   *           .setParent(SchemaName.of("[PROJECT]", "[SCHEMA]").toString())
+   *           .setSchema(Schema.newBuilder().build())
+   *           .setSchemaId("schemaId-697673060")
+   *           .build();
+   *   Schema response = schemaServiceClient.createSchema(request);
+   * }
+   * }
+ * + * @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 Schema createSchema(CreateSchemaRequest request) { + return createSchemaCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   CreateSchemaRequest request =
+   *       CreateSchemaRequest.newBuilder()
+   *           .setParent(SchemaName.of("[PROJECT]", "[SCHEMA]").toString())
+   *           .setSchema(Schema.newBuilder().build())
+   *           .setSchemaId("schemaId-697673060")
+   *           .build();
+   *   ApiFuture future = schemaServiceClient.createSchemaCallable().futureCall(request);
+   *   // Do something.
+   *   Schema response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable createSchemaCallable() { + return stub.createSchemaCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   SchemaName name = SchemaName.of("[PROJECT]", "[SCHEMA]");
+   *   Schema response = schemaServiceClient.getSchema(name);
+   * }
+   * }
+ * + * @param name Required. The name of the schema to get. Format is + * `projects/{project}/schemas/{schema}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Schema getSchema(SchemaName name) { + GetSchemaRequest request = + GetSchemaRequest.newBuilder().setName(name == null ? null : name.toString()).build(); + return getSchema(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   String name = SchemaName.of("[PROJECT]", "[SCHEMA]").toString();
+   *   Schema response = schemaServiceClient.getSchema(name);
+   * }
+   * }
+ * + * @param name Required. The name of the schema to get. Format is + * `projects/{project}/schemas/{schema}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Schema getSchema(String name) { + GetSchemaRequest request = GetSchemaRequest.newBuilder().setName(name).build(); + return getSchema(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   GetSchemaRequest request =
+   *       GetSchemaRequest.newBuilder()
+   *           .setName(SchemaName.of("[PROJECT]", "[SCHEMA]").toString())
+   *           .setView(SchemaView.forNumber(0))
+   *           .build();
+   *   Schema response = schemaServiceClient.getSchema(request);
+   * }
+   * }
+ * + * @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 Schema getSchema(GetSchemaRequest request) { + return getSchemaCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   GetSchemaRequest request =
+   *       GetSchemaRequest.newBuilder()
+   *           .setName(SchemaName.of("[PROJECT]", "[SCHEMA]").toString())
+   *           .setView(SchemaView.forNumber(0))
+   *           .build();
+   *   ApiFuture future = schemaServiceClient.getSchemaCallable().futureCall(request);
+   *   // Do something.
+   *   Schema response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable getSchemaCallable() { + return stub.getSchemaCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists schemas in a project. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   ProjectName parent = ProjectName.of("[PROJECT]");
+   *   for (Schema element : schemaServiceClient.listSchemas(parent).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param parent Required. The name of the project in which to list schemas. Format is + * `projects/{project-id}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSchemasPagedResponse listSchemas(ProjectName parent) { + ListSchemasRequest request = + ListSchemasRequest.newBuilder() + .setParent(parent == null ? null : parent.toString()) + .build(); + return listSchemas(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists schemas in a project. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   String parent = ProjectName.of("[PROJECT]").toString();
+   *   for (Schema element : schemaServiceClient.listSchemas(parent).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param parent Required. The name of the project in which to list schemas. Format is + * `projects/{project-id}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSchemasPagedResponse listSchemas(String parent) { + ListSchemasRequest request = ListSchemasRequest.newBuilder().setParent(parent).build(); + return listSchemas(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists schemas in a project. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   ListSchemasRequest request =
+   *       ListSchemasRequest.newBuilder()
+   *           .setParent(ProjectName.of("[PROJECT]").toString())
+   *           .setView(SchemaView.forNumber(0))
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   for (Schema element : schemaServiceClient.listSchemas(request).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @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 ListSchemasPagedResponse listSchemas(ListSchemasRequest request) { + return listSchemasPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists schemas in a project. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   ListSchemasRequest request =
+   *       ListSchemasRequest.newBuilder()
+   *           .setParent(ProjectName.of("[PROJECT]").toString())
+   *           .setView(SchemaView.forNumber(0))
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   ApiFuture future = schemaServiceClient.listSchemasPagedCallable().futureCall(request);
+   *   // Do something.
+   *   for (Schema element : future.get().iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable + listSchemasPagedCallable() { + return stub.listSchemasPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists schemas in a project. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   ListSchemasRequest request =
+   *       ListSchemasRequest.newBuilder()
+   *           .setParent(ProjectName.of("[PROJECT]").toString())
+   *           .setView(SchemaView.forNumber(0))
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   while (true) {
+   *     ListSchemasResponse response = schemaServiceClient.listSchemasCallable().call(request);
+   *     for (Schema element : response.getResponsesList()) {
+   *       // doThingsWith(element);
+   *     }
+   *     String nextPageToken = response.getNextPageToken();
+   *     if (!Strings.isNullOrEmpty(nextPageToken)) {
+   *       request = request.toBuilder().setPageToken(nextPageToken).build();
+   *     } else {
+   *       break;
+   *     }
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable listSchemasCallable() { + return stub.listSchemasCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   SchemaName name = SchemaName.of("[PROJECT]", "[SCHEMA]");
+   *   schemaServiceClient.deleteSchema(name);
+   * }
+   * }
+ * + * @param name Required. Name of the schema to delete. Format is + * `projects/{project}/schemas/{schema}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void deleteSchema(SchemaName name) { + DeleteSchemaRequest request = + DeleteSchemaRequest.newBuilder().setName(name == null ? null : name.toString()).build(); + deleteSchema(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   String name = SchemaName.of("[PROJECT]", "[SCHEMA]").toString();
+   *   schemaServiceClient.deleteSchema(name);
+   * }
+   * }
+ * + * @param name Required. Name of the schema to delete. Format is + * `projects/{project}/schemas/{schema}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void deleteSchema(String name) { + DeleteSchemaRequest request = DeleteSchemaRequest.newBuilder().setName(name).build(); + deleteSchema(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   DeleteSchemaRequest request =
+   *       DeleteSchemaRequest.newBuilder()
+   *           .setName(SchemaName.of("[PROJECT]", "[SCHEMA]").toString())
+   *           .build();
+   *   schemaServiceClient.deleteSchema(request);
+   * }
+   * }
+ * + * @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 void deleteSchema(DeleteSchemaRequest request) { + deleteSchemaCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   DeleteSchemaRequest request =
+   *       DeleteSchemaRequest.newBuilder()
+   *           .setName(SchemaName.of("[PROJECT]", "[SCHEMA]").toString())
+   *           .build();
+   *   ApiFuture future = schemaServiceClient.deleteSchemaCallable().futureCall(request);
+   *   // Do something.
+   *   future.get();
+   * }
+   * }
+ */ + public final UnaryCallable deleteSchemaCallable() { + return stub.deleteSchemaCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Validates a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   ProjectName parent = ProjectName.of("[PROJECT]");
+   *   Schema schema = Schema.newBuilder().build();
+   *   ValidateSchemaResponse response = schemaServiceClient.validateSchema(parent, schema);
+   * }
+   * }
+ * + * @param parent Required. The name of the project in which to validate schemas. Format is + * `projects/{project-id}`. + * @param schema Required. The schema object to validate. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ValidateSchemaResponse validateSchema(ProjectName parent, Schema schema) { + ValidateSchemaRequest request = + ValidateSchemaRequest.newBuilder() + .setParent(parent == null ? null : parent.toString()) + .setSchema(schema) + .build(); + return validateSchema(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Validates a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   String parent = ProjectName.of("[PROJECT]").toString();
+   *   Schema schema = Schema.newBuilder().build();
+   *   ValidateSchemaResponse response = schemaServiceClient.validateSchema(parent, schema);
+   * }
+   * }
+ * + * @param parent Required. The name of the project in which to validate schemas. Format is + * `projects/{project-id}`. + * @param schema Required. The schema object to validate. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ValidateSchemaResponse validateSchema(String parent, Schema schema) { + ValidateSchemaRequest request = + ValidateSchemaRequest.newBuilder().setParent(parent).setSchema(schema).build(); + return validateSchema(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Validates a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   ValidateSchemaRequest request =
+   *       ValidateSchemaRequest.newBuilder()
+   *           .setParent(ProjectName.of("[PROJECT]").toString())
+   *           .setSchema(Schema.newBuilder().build())
+   *           .build();
+   *   ValidateSchemaResponse response = schemaServiceClient.validateSchema(request);
+   * }
+   * }
+ * + * @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 ValidateSchemaResponse validateSchema(ValidateSchemaRequest request) { + return validateSchemaCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Validates a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   ValidateSchemaRequest request =
+   *       ValidateSchemaRequest.newBuilder()
+   *           .setParent(ProjectName.of("[PROJECT]").toString())
+   *           .setSchema(Schema.newBuilder().build())
+   *           .build();
+   *   ApiFuture future =
+   *       schemaServiceClient.validateSchemaCallable().futureCall(request);
+   *   // Do something.
+   *   ValidateSchemaResponse response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable + validateSchemaCallable() { + return stub.validateSchemaCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Validates a message against a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   ValidateMessageRequest request =
+   *       ValidateMessageRequest.newBuilder()
+   *           .setParent(ProjectName.of("[PROJECT]").toString())
+   *           .setMessage(ByteString.EMPTY)
+   *           .setEncoding(Encoding.forNumber(0))
+   *           .build();
+   *   ValidateMessageResponse response = schemaServiceClient.validateMessage(request);
+   * }
+   * }
+ * + * @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 ValidateMessageResponse validateMessage(ValidateMessageRequest request) { + return validateMessageCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Validates a message against a schema. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   ValidateMessageRequest request =
+   *       ValidateMessageRequest.newBuilder()
+   *           .setParent(ProjectName.of("[PROJECT]").toString())
+   *           .setMessage(ByteString.EMPTY)
+   *           .setEncoding(Encoding.forNumber(0))
+   *           .build();
+   *   ApiFuture future =
+   *       schemaServiceClient.validateMessageCallable().futureCall(request);
+   *   // Do something.
+   *   ValidateMessageResponse response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable + validateMessageCallable() { + return stub.validateMessageCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sets the access control policy on the specified resource. Replacesany existing policy. + * + *

Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   SetIamPolicyRequest request =
+   *       SetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setPolicy(Policy.newBuilder().build())
+   *           .build();
+   *   Policy response = schemaServiceClient.setIamPolicy(request);
+   * }
+   * }
+ * + * @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 Policy setIamPolicy(SetIamPolicyRequest request) { + return setIamPolicyCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sets the access control policy on the specified resource. Replacesany existing policy. + * + *

Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   SetIamPolicyRequest request =
+   *       SetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setPolicy(Policy.newBuilder().build())
+   *           .build();
+   *   ApiFuture future = schemaServiceClient.setIamPolicyCallable().futureCall(request);
+   *   // Do something.
+   *   Policy response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable setIamPolicyCallable() { + return stub.setIamPolicyCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the access control policy for a resource. Returns an empty policyif the resource exists + * and does not have a policy set. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   GetIamPolicyRequest request =
+   *       GetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setOptions(GetPolicyOptions.newBuilder().build())
+   *           .build();
+   *   Policy response = schemaServiceClient.getIamPolicy(request);
+   * }
+   * }
+ * + * @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 Policy getIamPolicy(GetIamPolicyRequest request) { + return getIamPolicyCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the access control policy for a resource. Returns an empty policyif the resource exists + * and does not have a policy set. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   GetIamPolicyRequest request =
+   *       GetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setOptions(GetPolicyOptions.newBuilder().build())
+   *           .build();
+   *   ApiFuture future = schemaServiceClient.getIamPolicyCallable().futureCall(request);
+   *   // Do something.
+   *   Policy response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable getIamPolicyCallable() { + return stub.getIamPolicyCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Returns permissions that a caller has on the specified resource. If theresource does not exist, + * this will return an empty set ofpermissions, not a `NOT_FOUND` error. + * + *

Note: This operation is designed to be used for buildingpermission-aware UIs and + * command-line tools, not for authorizationchecking. This operation may "fail open" without + * warning. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   TestIamPermissionsRequest request =
+   *       TestIamPermissionsRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .addAllPermissions(new ArrayList())
+   *           .build();
+   *   TestIamPermissionsResponse response = schemaServiceClient.testIamPermissions(request);
+   * }
+   * }
+ * + * @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 TestIamPermissionsResponse testIamPermissions(TestIamPermissionsRequest request) { + return testIamPermissionsCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Returns permissions that a caller has on the specified resource. If theresource does not exist, + * this will return an empty set ofpermissions, not a `NOT_FOUND` error. + * + *

Note: This operation is designed to be used for buildingpermission-aware UIs and + * command-line tools, not for authorizationchecking. This operation may "fail open" without + * warning. + * + *

Sample code: + * + *

{@code
+   * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+   *   TestIamPermissionsRequest request =
+   *       TestIamPermissionsRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .addAllPermissions(new ArrayList())
+   *           .build();
+   *   ApiFuture future =
+   *       schemaServiceClient.testIamPermissionsCallable().futureCall(request);
+   *   // Do something.
+   *   TestIamPermissionsResponse response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable + testIamPermissionsCallable() { + return stub.testIamPermissionsCallable(); + } + + @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 ListSchemasPagedResponse + extends AbstractPagedListResponse< + ListSchemasRequest, + ListSchemasResponse, + Schema, + ListSchemasPage, + ListSchemasFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListSchemasPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListSchemasPagedResponse apply(ListSchemasPage input) { + return new ListSchemasPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListSchemasPagedResponse(ListSchemasPage page) { + super(page, ListSchemasFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListSchemasPage + extends AbstractPage { + + private ListSchemasPage( + PageContext context, + ListSchemasResponse response) { + super(context, response); + } + + private static ListSchemasPage createEmptyPage() { + return new ListSchemasPage(null, null); + } + + @Override + protected ListSchemasPage createPage( + PageContext context, + ListSchemasResponse response) { + return new ListSchemasPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListSchemasFixedSizeCollection + extends AbstractFixedSizeCollection< + ListSchemasRequest, + ListSchemasResponse, + Schema, + ListSchemasPage, + ListSchemasFixedSizeCollection> { + + private ListSchemasFixedSizeCollection(List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListSchemasFixedSizeCollection createEmptyCollection() { + return new ListSchemasFixedSizeCollection(null, 0); + } + + @Override + protected ListSchemasFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListSchemasFixedSizeCollection(pages, collectionSize); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SchemaServiceClientTest.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SchemaServiceClientTest.java new file mode 100644 index 0000000000..9a2ce5e16b --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SchemaServiceClientTest.java @@ -0,0 +1,698 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +import static com.google.cloud.pubsub.v1.SchemaServiceClient.ListSchemasPagedResponse; + +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.iam.v1.Binding; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.GetPolicyOptions; +import com.google.iam.v1.Policy; +import com.google.iam.v1.ProjectName; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.ByteString; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.CreateSchemaRequest; +import com.google.pubsub.v1.DeleteSchemaRequest; +import com.google.pubsub.v1.Encoding; +import com.google.pubsub.v1.GetSchemaRequest; +import com.google.pubsub.v1.ListSchemasRequest; +import com.google.pubsub.v1.ListSchemasResponse; +import com.google.pubsub.v1.Schema; +import com.google.pubsub.v1.SchemaName; +import com.google.pubsub.v1.ValidateMessageRequest; +import com.google.pubsub.v1.ValidateMessageResponse; +import com.google.pubsub.v1.ValidateSchemaRequest; +import com.google.pubsub.v1.ValidateSchemaResponse; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.ArrayList; +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 SchemaServiceClientTest { + private static MockServiceHelper mockServiceHelper; + private static MockSchemaService mockSchemaService; + private SchemaServiceClient client; + private static MockIAMPolicy mockIAMPolicy; + private LocalChannelProvider channelProvider; + + @BeforeClass + public static void startStaticServer() { + mockSchemaService = new MockSchemaService(); + mockIAMPolicy = new MockIAMPolicy(); + mockServiceHelper = + new MockServiceHelper( + UUID.randomUUID().toString(), + Arrays.asList(mockSchemaService, mockIAMPolicy)); + mockServiceHelper.start(); + } + + @AfterClass + public static void stopServer() { + mockServiceHelper.stop(); + } + + @Before + public void setUp() throws IOException { + mockServiceHelper.reset(); + channelProvider = mockServiceHelper.createChannelProvider(); + SchemaServiceSettings settings = + SchemaServiceSettings.newBuilder() + .setTransportChannelProvider(channelProvider) + .setCredentialsProvider(NoCredentialsProvider.create()) + .build(); + client = SchemaServiceClient.create(settings); + } + + @After + public void tearDown() throws Exception { + client.close(); + } + + @Test + public void createSchemaTest() throws Exception { + Schema expectedResponse = + Schema.newBuilder() + .setName(SchemaName.of("[PROJECT]", "[SCHEMA]").toString()) + .setDefinition("definition-1014418093") + .build(); + mockSchemaService.addResponse(expectedResponse); + + ProjectName parent = ProjectName.of("[PROJECT]"); + Schema schema = Schema.newBuilder().build(); + String schemaId = "schemaId-697673060"; + + Schema actualResponse = client.createSchema(parent, schema, schemaId); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSchemaRequest actualRequest = ((CreateSchemaRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(schema, actualRequest.getSchema()); + Assert.assertEquals(schemaId, actualRequest.getSchemaId()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSchemaExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + ProjectName parent = ProjectName.of("[PROJECT]"); + Schema schema = Schema.newBuilder().build(); + String schemaId = "schemaId-697673060"; + client.createSchema(parent, schema, schemaId); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSchemaTest2() throws Exception { + Schema expectedResponse = + Schema.newBuilder() + .setName(SchemaName.of("[PROJECT]", "[SCHEMA]").toString()) + .setDefinition("definition-1014418093") + .build(); + mockSchemaService.addResponse(expectedResponse); + + String parent = "parent-995424086"; + Schema schema = Schema.newBuilder().build(); + String schemaId = "schemaId-697673060"; + + Schema actualResponse = client.createSchema(parent, schema, schemaId); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSchemaRequest actualRequest = ((CreateSchemaRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertEquals(schema, actualRequest.getSchema()); + Assert.assertEquals(schemaId, actualRequest.getSchemaId()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSchemaExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + String parent = "parent-995424086"; + Schema schema = Schema.newBuilder().build(); + String schemaId = "schemaId-697673060"; + client.createSchema(parent, schema, schemaId); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getSchemaTest() throws Exception { + Schema expectedResponse = + Schema.newBuilder() + .setName(SchemaName.of("[PROJECT]", "[SCHEMA]").toString()) + .setDefinition("definition-1014418093") + .build(); + mockSchemaService.addResponse(expectedResponse); + + SchemaName name = SchemaName.of("[PROJECT]", "[SCHEMA]"); + + Schema actualResponse = client.getSchema(name); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetSchemaRequest actualRequest = ((GetSchemaRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getSchemaExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + SchemaName name = SchemaName.of("[PROJECT]", "[SCHEMA]"); + client.getSchema(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getSchemaTest2() throws Exception { + Schema expectedResponse = + Schema.newBuilder() + .setName(SchemaName.of("[PROJECT]", "[SCHEMA]").toString()) + .setDefinition("definition-1014418093") + .build(); + mockSchemaService.addResponse(expectedResponse); + + String name = "name3373707"; + + Schema actualResponse = client.getSchema(name); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetSchemaRequest actualRequest = ((GetSchemaRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getSchemaExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + String name = "name3373707"; + client.getSchema(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSchemasTest() throws Exception { + Schema responsesElement = Schema.newBuilder().build(); + ListSchemasResponse expectedResponse = + ListSchemasResponse.newBuilder() + .setNextPageToken("") + .addAllSchemas(Arrays.asList(responsesElement)) + .build(); + mockSchemaService.addResponse(expectedResponse); + + ProjectName parent = ProjectName.of("[PROJECT]"); + + ListSchemasPagedResponse pagedListResponse = client.listSchemas(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSchemasList().get(0), resources.get(0)); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSchemasRequest actualRequest = ((ListSchemasRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSchemasExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + ProjectName parent = ProjectName.of("[PROJECT]"); + client.listSchemas(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSchemasTest2() throws Exception { + Schema responsesElement = Schema.newBuilder().build(); + ListSchemasResponse expectedResponse = + ListSchemasResponse.newBuilder() + .setNextPageToken("") + .addAllSchemas(Arrays.asList(responsesElement)) + .build(); + mockSchemaService.addResponse(expectedResponse); + + String parent = "parent-995424086"; + + ListSchemasPagedResponse pagedListResponse = client.listSchemas(parent); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSchemasList().get(0), resources.get(0)); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSchemasRequest actualRequest = ((ListSchemasRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSchemasExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + String parent = "parent-995424086"; + client.listSchemas(parent); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteSchemaTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSchemaService.addResponse(expectedResponse); + + SchemaName name = SchemaName.of("[PROJECT]", "[SCHEMA]"); + + client.deleteSchema(name); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteSchemaRequest actualRequest = ((DeleteSchemaRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteSchemaExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + SchemaName name = SchemaName.of("[PROJECT]", "[SCHEMA]"); + client.deleteSchema(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteSchemaTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSchemaService.addResponse(expectedResponse); + + String name = "name3373707"; + + client.deleteSchema(name); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteSchemaRequest actualRequest = ((DeleteSchemaRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteSchemaExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + String name = "name3373707"; + client.deleteSchema(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void validateSchemaTest() throws Exception { + ValidateSchemaResponse expectedResponse = ValidateSchemaResponse.newBuilder().build(); + mockSchemaService.addResponse(expectedResponse); + + ProjectName parent = ProjectName.of("[PROJECT]"); + Schema schema = Schema.newBuilder().build(); + + ValidateSchemaResponse actualResponse = client.validateSchema(parent, schema); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ValidateSchemaRequest actualRequest = ((ValidateSchemaRequest) actualRequests.get(0)); + + Assert.assertEquals(parent.toString(), actualRequest.getParent()); + Assert.assertEquals(schema, actualRequest.getSchema()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void validateSchemaExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + ProjectName parent = ProjectName.of("[PROJECT]"); + Schema schema = Schema.newBuilder().build(); + client.validateSchema(parent, schema); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void validateSchemaTest2() throws Exception { + ValidateSchemaResponse expectedResponse = ValidateSchemaResponse.newBuilder().build(); + mockSchemaService.addResponse(expectedResponse); + + String parent = "parent-995424086"; + Schema schema = Schema.newBuilder().build(); + + ValidateSchemaResponse actualResponse = client.validateSchema(parent, schema); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ValidateSchemaRequest actualRequest = ((ValidateSchemaRequest) actualRequests.get(0)); + + Assert.assertEquals(parent, actualRequest.getParent()); + Assert.assertEquals(schema, actualRequest.getSchema()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void validateSchemaExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + String parent = "parent-995424086"; + Schema schema = Schema.newBuilder().build(); + client.validateSchema(parent, schema); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void validateMessageTest() throws Exception { + ValidateMessageResponse expectedResponse = ValidateMessageResponse.newBuilder().build(); + mockSchemaService.addResponse(expectedResponse); + + ValidateMessageRequest request = + ValidateMessageRequest.newBuilder() + .setParent(ProjectName.of("[PROJECT]").toString()) + .setMessage(ByteString.EMPTY) + .setEncoding(Encoding.forNumber(0)) + .build(); + + ValidateMessageResponse actualResponse = client.validateMessage(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSchemaService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ValidateMessageRequest actualRequest = ((ValidateMessageRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getParent(), actualRequest.getParent()); + Assert.assertEquals(request.getName(), actualRequest.getName()); + Assert.assertEquals(request.getSchema(), actualRequest.getSchema()); + Assert.assertEquals(request.getMessage(), actualRequest.getMessage()); + Assert.assertEquals(request.getEncoding(), actualRequest.getEncoding()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void validateMessageExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSchemaService.addException(exception); + + try { + ValidateMessageRequest request = + ValidateMessageRequest.newBuilder() + .setParent(ProjectName.of("[PROJECT]").toString()) + .setMessage(ByteString.EMPTY) + .setEncoding(Encoding.forNumber(0)) + .build(); + client.validateMessage(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void setIamPolicyTest() throws Exception { + Policy expectedResponse = + Policy.newBuilder() + .setVersion(351608024) + .addAllBindings(new ArrayList()) + .setEtag(ByteString.EMPTY) + .build(); + mockIAMPolicy.addResponse(expectedResponse); + + SetIamPolicyRequest request = + SetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setPolicy(Policy.newBuilder().build()) + .build(); + + Policy actualResponse = client.setIamPolicy(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + SetIamPolicyRequest actualRequest = ((SetIamPolicyRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getPolicy(), actualRequest.getPolicy()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void setIamPolicyExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + SetIamPolicyRequest request = + SetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setPolicy(Policy.newBuilder().build()) + .build(); + client.setIamPolicy(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getIamPolicyTest() throws Exception { + Policy expectedResponse = + Policy.newBuilder() + .setVersion(351608024) + .addAllBindings(new ArrayList()) + .setEtag(ByteString.EMPTY) + .build(); + mockIAMPolicy.addResponse(expectedResponse); + + GetIamPolicyRequest request = + GetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setOptions(GetPolicyOptions.newBuilder().build()) + .build(); + + Policy actualResponse = client.getIamPolicy(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetIamPolicyRequest actualRequest = ((GetIamPolicyRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getOptions(), actualRequest.getOptions()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getIamPolicyExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + GetIamPolicyRequest request = + GetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setOptions(GetPolicyOptions.newBuilder().build()) + .build(); + client.getIamPolicy(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void testIamPermissionsTest() throws Exception { + TestIamPermissionsResponse expectedResponse = + TestIamPermissionsResponse.newBuilder().addAllPermissions(new ArrayList()).build(); + mockIAMPolicy.addResponse(expectedResponse); + + TestIamPermissionsRequest request = + TestIamPermissionsRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .addAllPermissions(new ArrayList()) + .build(); + + TestIamPermissionsResponse actualResponse = client.testIamPermissions(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + TestIamPermissionsRequest actualRequest = ((TestIamPermissionsRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getPermissionsList(), actualRequest.getPermissionsList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void testIamPermissionsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + TestIamPermissionsRequest request = + TestIamPermissionsRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .addAllPermissions(new ArrayList()) + .build(); + client.testIamPermissions(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SchemaServiceSettings.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SchemaServiceSettings.java new file mode 100644 index 0000000000..da29b9f2de --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SchemaServiceSettings.java @@ -0,0 +1,289 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +import static com.google.cloud.pubsub.v1.SchemaServiceClient.ListSchemasPagedResponse; + +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.cloud.pubsub.v1.stub.SchemaServiceStubSettings; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.CreateSchemaRequest; +import com.google.pubsub.v1.DeleteSchemaRequest; +import com.google.pubsub.v1.GetSchemaRequest; +import com.google.pubsub.v1.ListSchemasRequest; +import com.google.pubsub.v1.ListSchemasResponse; +import com.google.pubsub.v1.Schema; +import com.google.pubsub.v1.ValidateMessageRequest; +import com.google.pubsub.v1.ValidateMessageResponse; +import com.google.pubsub.v1.ValidateSchemaRequest; +import com.google.pubsub.v1.ValidateSchemaResponse; +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 SchemaServiceClient}. + * + *

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

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

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

For example, to set the total timeout of createSchema to 30 seconds: + * + *

{@code
+ * SchemaServiceSettings.Builder schemaServiceSettingsBuilder = SchemaServiceSettings.newBuilder();
+ * schemaServiceSettingsBuilder
+ *     .createSchemaSettings()
+ *     .setRetrySettings(
+ *         schemaServiceSettingsBuilder
+ *             .createSchemaSettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * SchemaServiceSettings schemaServiceSettings = schemaServiceSettingsBuilder.build();
+ * }
+ */ +@Generated("by gapic-generator-java") +public class SchemaServiceSettings extends ClientSettings { + + /** Returns the object with the settings used for calls to createSchema. */ + public UnaryCallSettings createSchemaSettings() { + return ((SchemaServiceStubSettings) getStubSettings()).createSchemaSettings(); + } + + /** Returns the object with the settings used for calls to getSchema. */ + public UnaryCallSettings getSchemaSettings() { + return ((SchemaServiceStubSettings) getStubSettings()).getSchemaSettings(); + } + + /** Returns the object with the settings used for calls to listSchemas. */ + public PagedCallSettings + listSchemasSettings() { + return ((SchemaServiceStubSettings) getStubSettings()).listSchemasSettings(); + } + + /** Returns the object with the settings used for calls to deleteSchema. */ + public UnaryCallSettings deleteSchemaSettings() { + return ((SchemaServiceStubSettings) getStubSettings()).deleteSchemaSettings(); + } + + /** Returns the object with the settings used for calls to validateSchema. */ + public UnaryCallSettings validateSchemaSettings() { + return ((SchemaServiceStubSettings) getStubSettings()).validateSchemaSettings(); + } + + /** Returns the object with the settings used for calls to validateMessage. */ + public UnaryCallSettings + validateMessageSettings() { + return ((SchemaServiceStubSettings) getStubSettings()).validateMessageSettings(); + } + + /** Returns the object with the settings used for calls to setIamPolicy. */ + public UnaryCallSettings setIamPolicySettings() { + return ((SchemaServiceStubSettings) getStubSettings()).setIamPolicySettings(); + } + + /** Returns the object with the settings used for calls to getIamPolicy. */ + public UnaryCallSettings getIamPolicySettings() { + return ((SchemaServiceStubSettings) getStubSettings()).getIamPolicySettings(); + } + + /** Returns the object with the settings used for calls to testIamPermissions. */ + public UnaryCallSettings + testIamPermissionsSettings() { + return ((SchemaServiceStubSettings) getStubSettings()).testIamPermissionsSettings(); + } + + public static final SchemaServiceSettings create(SchemaServiceStubSettings stub) + throws IOException { + return new SchemaServiceSettings.Builder(stub.toBuilder()).build(); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return SchemaServiceStubSettings.defaultExecutorProviderBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return SchemaServiceStubSettings.getDefaultEndpoint(); + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return SchemaServiceStubSettings.getDefaultServiceScopes(); + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return SchemaServiceStubSettings.defaultCredentialsProviderBuilder(); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return SchemaServiceStubSettings.defaultGrpcTransportProviderBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return SchemaServiceStubSettings.defaultTransportChannelProvider(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return SchemaServiceStubSettings.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 SchemaServiceSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + } + + /** Builder for SchemaServiceSettings. */ + public static class Builder extends ClientSettings.Builder { + + protected Builder() throws IOException { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(SchemaServiceStubSettings.newBuilder(clientContext)); + } + + protected Builder(SchemaServiceSettings settings) { + super(settings.getStubSettings().toBuilder()); + } + + protected Builder(SchemaServiceStubSettings.Builder stubSettings) { + super(stubSettings); + } + + private static Builder createDefault() { + return new Builder(SchemaServiceStubSettings.newBuilder()); + } + + public SchemaServiceStubSettings.Builder getStubSettingsBuilder() { + return ((SchemaServiceStubSettings.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 createSchema. */ + public UnaryCallSettings.Builder createSchemaSettings() { + return getStubSettingsBuilder().createSchemaSettings(); + } + + /** Returns the builder for the settings used for calls to getSchema. */ + public UnaryCallSettings.Builder getSchemaSettings() { + return getStubSettingsBuilder().getSchemaSettings(); + } + + /** Returns the builder for the settings used for calls to listSchemas. */ + public PagedCallSettings.Builder< + ListSchemasRequest, ListSchemasResponse, ListSchemasPagedResponse> + listSchemasSettings() { + return getStubSettingsBuilder().listSchemasSettings(); + } + + /** Returns the builder for the settings used for calls to deleteSchema. */ + public UnaryCallSettings.Builder deleteSchemaSettings() { + return getStubSettingsBuilder().deleteSchemaSettings(); + } + + /** Returns the builder for the settings used for calls to validateSchema. */ + public UnaryCallSettings.Builder + validateSchemaSettings() { + return getStubSettingsBuilder().validateSchemaSettings(); + } + + /** Returns the builder for the settings used for calls to validateMessage. */ + public UnaryCallSettings.Builder + validateMessageSettings() { + return getStubSettingsBuilder().validateMessageSettings(); + } + + /** Returns the builder for the settings used for calls to setIamPolicy. */ + public UnaryCallSettings.Builder setIamPolicySettings() { + return getStubSettingsBuilder().setIamPolicySettings(); + } + + /** Returns the builder for the settings used for calls to getIamPolicy. */ + public UnaryCallSettings.Builder getIamPolicySettings() { + return getStubSettingsBuilder().getIamPolicySettings(); + } + + /** Returns the builder for the settings used for calls to testIamPermissions. */ + public UnaryCallSettings.Builder + testIamPermissionsSettings() { + return getStubSettingsBuilder().testIamPermissionsSettings(); + } + + @Override + public SchemaServiceSettings build() throws IOException { + return new SchemaServiceSettings(this); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SubscriptionAdminClient.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SubscriptionAdminClient.java new file mode 100644 index 0000000000..c7d77041cb --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SubscriptionAdminClient.java @@ -0,0 +1,2593 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +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.BidiStreamingCallable; +import com.google.api.gax.rpc.PageContext; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.cloud.pubsub.v1.stub.SubscriberStub; +import com.google.cloud.pubsub.v1.stub.SubscriberStubSettings; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.ProjectName; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.AcknowledgeRequest; +import com.google.pubsub.v1.CreateSnapshotRequest; +import com.google.pubsub.v1.DeleteSnapshotRequest; +import com.google.pubsub.v1.DeleteSubscriptionRequest; +import com.google.pubsub.v1.GetSnapshotRequest; +import com.google.pubsub.v1.GetSubscriptionRequest; +import com.google.pubsub.v1.ListSnapshotsRequest; +import com.google.pubsub.v1.ListSnapshotsResponse; +import com.google.pubsub.v1.ListSubscriptionsRequest; +import com.google.pubsub.v1.ListSubscriptionsResponse; +import com.google.pubsub.v1.ModifyAckDeadlineRequest; +import com.google.pubsub.v1.ModifyPushConfigRequest; +import com.google.pubsub.v1.PullRequest; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.PushConfig; +import com.google.pubsub.v1.SeekRequest; +import com.google.pubsub.v1.SeekResponse; +import com.google.pubsub.v1.Snapshot; +import com.google.pubsub.v1.SnapshotName; +import com.google.pubsub.v1.StreamingPullRequest; +import com.google.pubsub.v1.StreamingPullResponse; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.SubscriptionName; +import com.google.pubsub.v1.TopicName; +import com.google.pubsub.v1.UpdateSnapshotRequest; +import com.google.pubsub.v1.UpdateSubscriptionRequest; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Service Description: The service that an application uses to manipulate subscriptions and to + * consume messages from a subscription via the `Pull` method or by establishing a bi-directional + * stream using the `StreamingPull` method. + * + *

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

{@code
+ * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ *   SubscriptionName name = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+ *   TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+ *   PushConfig pushConfig = PushConfig.newBuilder().build();
+ *   int ackDeadlineSeconds = 2135351438;
+ *   Subscription response =
+ *       subscriptionAdminClient.createSubscription(name, topic, pushConfig, ackDeadlineSeconds);
+ * }
+ * }
+ * + *

Note: close() needs to be called on the SubscriptionAdminClient 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 SubscriptionAdminSettings to + * create(). For example: + * + *

To customize credentials: + * + *

{@code
+ * SubscriptionAdminSettings subscriptionAdminSettings =
+ *     SubscriptionAdminSettings.newBuilder()
+ *         .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
+ *         .build();
+ * SubscriptionAdminClient subscriptionAdminClient =
+ *     SubscriptionAdminClient.create(subscriptionAdminSettings);
+ * }
+ * + *

To customize the endpoint: + * + *

{@code
+ * SubscriptionAdminSettings subscriptionAdminSettings =
+ *     SubscriptionAdminSettings.newBuilder().setEndpoint(myEndpoint).build();
+ * SubscriptionAdminClient subscriptionAdminClient =
+ *     SubscriptionAdminClient.create(subscriptionAdminSettings);
+ * }
+ * + *

Please refer to the GitHub repository's samples for more quickstart code snippets. + */ +@Generated("by gapic-generator-java") +public class SubscriptionAdminClient implements BackgroundResource { + private final SubscriptionAdminSettings settings; + private final SubscriberStub stub; + + /** Constructs an instance of SubscriptionAdminClient with default settings. */ + public static final SubscriptionAdminClient create() throws IOException { + return create(SubscriptionAdminSettings.newBuilder().build()); + } + + /** + * Constructs an instance of SubscriptionAdminClient, 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 SubscriptionAdminClient create(SubscriptionAdminSettings settings) + throws IOException { + return new SubscriptionAdminClient(settings); + } + + /** + * Constructs an instance of SubscriptionAdminClient, using the given stub for making calls. This + * is for advanced usage - prefer using create(SubscriptionAdminSettings). + */ + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public static final SubscriptionAdminClient create(SubscriberStub stub) { + return new SubscriptionAdminClient(stub); + } + + /** + * Constructs an instance of SubscriptionAdminClient, 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 SubscriptionAdminClient(SubscriptionAdminSettings settings) throws IOException { + this.settings = settings; + this.stub = ((SubscriberStubSettings) settings.getStubSettings()).createStub(); + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + protected SubscriptionAdminClient(SubscriberStub stub) { + this.settings = null; + this.stub = stub; + } + + public final SubscriptionAdminSettings getSettings() { + return settings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public SubscriberStub getStub() { + return stub; + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a subscription to a given topic. See the [resource name rules] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). If the subscription already + * exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns + * `NOT_FOUND`. + * + *

If the name is not provided in the request, the server will assign a random name for this + * subscription on the same project as the topic, conforming to the [resource name format] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). The generated name is populated in + * the returned Subscription object. Note that for REST API requests, you must specify a name in + * the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SubscriptionName name = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+   *   TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+   *   PushConfig pushConfig = PushConfig.newBuilder().build();
+   *   int ackDeadlineSeconds = 2135351438;
+   *   Subscription response =
+   *       subscriptionAdminClient.createSubscription(name, topic, pushConfig, ackDeadlineSeconds);
+   * }
+   * }
+ * + * @param name Required. The name of the subscription. It must have the format + * `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a + * letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores + * (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 + * and 255 characters in length, and it must not start with `"goog"`. + * @param topic Required. The name of the topic from which this subscription is receiving + * messages. Format is `projects/{project}/topics/{topic}`. The value of this field will be + * `_deleted-topic_` if the topic has been deleted. + * @param pushConfig If push delivery is used with this subscription, this field is used to + * configure it. An empty `pushConfig` signifies that the subscriber will pull and ack + * messages using API methods. + * @param ackDeadlineSeconds The approximate amount of time (on a best-effort basis) Pub/Sub waits + * for the subscriber to acknowledge receipt before resending the message. In the interval + * after the message is delivered and before it is acknowledged, it is considered to be + * <i>outstanding</i>. During that time period, the message will not be + * redelivered (on a best-effort basis). + *

For pull subscriptions, this value is used as the initial value for the ack deadline. To + * override this value for a given message, call `ModifyAckDeadline` with the corresponding + * `ack_id` if using non-streaming pull or send the `ack_id` in a + * `StreamingModifyAckDeadlineRequest` if using streaming pull. The minimum custom deadline + * you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds + * (10 minutes). If this parameter is 0, a default value of 10 seconds is used. + *

For push delivery, this value is also used to set the request timeout for the call to + * the push endpoint. + *

If the subscriber never acknowledges the message, the Pub/Sub system will eventually + * redeliver the message. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Subscription createSubscription( + SubscriptionName name, TopicName topic, PushConfig pushConfig, int ackDeadlineSeconds) { + Subscription request = + Subscription.newBuilder() + .setName(name == null ? null : name.toString()) + .setTopic(topic == null ? null : topic.toString()) + .setPushConfig(pushConfig) + .setAckDeadlineSeconds(ackDeadlineSeconds) + .build(); + return createSubscription(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a subscription to a given topic. See the [resource name rules] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). If the subscription already + * exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns + * `NOT_FOUND`. + * + *

If the name is not provided in the request, the server will assign a random name for this + * subscription on the same project as the topic, conforming to the [resource name format] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). The generated name is populated in + * the returned Subscription object. Note that for REST API requests, you must specify a name in + * the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SubscriptionName name = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+   *   String topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString();
+   *   PushConfig pushConfig = PushConfig.newBuilder().build();
+   *   int ackDeadlineSeconds = 2135351438;
+   *   Subscription response =
+   *       subscriptionAdminClient.createSubscription(name, topic, pushConfig, ackDeadlineSeconds);
+   * }
+   * }
+ * + * @param name Required. The name of the subscription. It must have the format + * `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a + * letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores + * (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 + * and 255 characters in length, and it must not start with `"goog"`. + * @param topic Required. The name of the topic from which this subscription is receiving + * messages. Format is `projects/{project}/topics/{topic}`. The value of this field will be + * `_deleted-topic_` if the topic has been deleted. + * @param pushConfig If push delivery is used with this subscription, this field is used to + * configure it. An empty `pushConfig` signifies that the subscriber will pull and ack + * messages using API methods. + * @param ackDeadlineSeconds The approximate amount of time (on a best-effort basis) Pub/Sub waits + * for the subscriber to acknowledge receipt before resending the message. In the interval + * after the message is delivered and before it is acknowledged, it is considered to be + * <i>outstanding</i>. During that time period, the message will not be + * redelivered (on a best-effort basis). + *

For pull subscriptions, this value is used as the initial value for the ack deadline. To + * override this value for a given message, call `ModifyAckDeadline` with the corresponding + * `ack_id` if using non-streaming pull or send the `ack_id` in a + * `StreamingModifyAckDeadlineRequest` if using streaming pull. The minimum custom deadline + * you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds + * (10 minutes). If this parameter is 0, a default value of 10 seconds is used. + *

For push delivery, this value is also used to set the request timeout for the call to + * the push endpoint. + *

If the subscriber never acknowledges the message, the Pub/Sub system will eventually + * redeliver the message. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Subscription createSubscription( + SubscriptionName name, String topic, PushConfig pushConfig, int ackDeadlineSeconds) { + Subscription request = + Subscription.newBuilder() + .setName(name == null ? null : name.toString()) + .setTopic(topic) + .setPushConfig(pushConfig) + .setAckDeadlineSeconds(ackDeadlineSeconds) + .build(); + return createSubscription(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a subscription to a given topic. See the [resource name rules] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). If the subscription already + * exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns + * `NOT_FOUND`. + * + *

If the name is not provided in the request, the server will assign a random name for this + * subscription on the same project as the topic, conforming to the [resource name format] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). The generated name is populated in + * the returned Subscription object. Note that for REST API requests, you must specify a name in + * the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String name = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString();
+   *   TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+   *   PushConfig pushConfig = PushConfig.newBuilder().build();
+   *   int ackDeadlineSeconds = 2135351438;
+   *   Subscription response =
+   *       subscriptionAdminClient.createSubscription(name, topic, pushConfig, ackDeadlineSeconds);
+   * }
+   * }
+ * + * @param name Required. The name of the subscription. It must have the format + * `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a + * letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores + * (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 + * and 255 characters in length, and it must not start with `"goog"`. + * @param topic Required. The name of the topic from which this subscription is receiving + * messages. Format is `projects/{project}/topics/{topic}`. The value of this field will be + * `_deleted-topic_` if the topic has been deleted. + * @param pushConfig If push delivery is used with this subscription, this field is used to + * configure it. An empty `pushConfig` signifies that the subscriber will pull and ack + * messages using API methods. + * @param ackDeadlineSeconds The approximate amount of time (on a best-effort basis) Pub/Sub waits + * for the subscriber to acknowledge receipt before resending the message. In the interval + * after the message is delivered and before it is acknowledged, it is considered to be + * <i>outstanding</i>. During that time period, the message will not be + * redelivered (on a best-effort basis). + *

For pull subscriptions, this value is used as the initial value for the ack deadline. To + * override this value for a given message, call `ModifyAckDeadline` with the corresponding + * `ack_id` if using non-streaming pull or send the `ack_id` in a + * `StreamingModifyAckDeadlineRequest` if using streaming pull. The minimum custom deadline + * you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds + * (10 minutes). If this parameter is 0, a default value of 10 seconds is used. + *

For push delivery, this value is also used to set the request timeout for the call to + * the push endpoint. + *

If the subscriber never acknowledges the message, the Pub/Sub system will eventually + * redeliver the message. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Subscription createSubscription( + String name, TopicName topic, PushConfig pushConfig, int ackDeadlineSeconds) { + Subscription request = + Subscription.newBuilder() + .setName(name) + .setTopic(topic == null ? null : topic.toString()) + .setPushConfig(pushConfig) + .setAckDeadlineSeconds(ackDeadlineSeconds) + .build(); + return createSubscription(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a subscription to a given topic. See the [resource name rules] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). If the subscription already + * exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns + * `NOT_FOUND`. + * + *

If the name is not provided in the request, the server will assign a random name for this + * subscription on the same project as the topic, conforming to the [resource name format] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). The generated name is populated in + * the returned Subscription object. Note that for REST API requests, you must specify a name in + * the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String name = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString();
+   *   String topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString();
+   *   PushConfig pushConfig = PushConfig.newBuilder().build();
+   *   int ackDeadlineSeconds = 2135351438;
+   *   Subscription response =
+   *       subscriptionAdminClient.createSubscription(name, topic, pushConfig, ackDeadlineSeconds);
+   * }
+   * }
+ * + * @param name Required. The name of the subscription. It must have the format + * `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a + * letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores + * (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 + * and 255 characters in length, and it must not start with `"goog"`. + * @param topic Required. The name of the topic from which this subscription is receiving + * messages. Format is `projects/{project}/topics/{topic}`. The value of this field will be + * `_deleted-topic_` if the topic has been deleted. + * @param pushConfig If push delivery is used with this subscription, this field is used to + * configure it. An empty `pushConfig` signifies that the subscriber will pull and ack + * messages using API methods. + * @param ackDeadlineSeconds The approximate amount of time (on a best-effort basis) Pub/Sub waits + * for the subscriber to acknowledge receipt before resending the message. In the interval + * after the message is delivered and before it is acknowledged, it is considered to be + * <i>outstanding</i>. During that time period, the message will not be + * redelivered (on a best-effort basis). + *

For pull subscriptions, this value is used as the initial value for the ack deadline. To + * override this value for a given message, call `ModifyAckDeadline` with the corresponding + * `ack_id` if using non-streaming pull or send the `ack_id` in a + * `StreamingModifyAckDeadlineRequest` if using streaming pull. The minimum custom deadline + * you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds + * (10 minutes). If this parameter is 0, a default value of 10 seconds is used. + *

For push delivery, this value is also used to set the request timeout for the call to + * the push endpoint. + *

If the subscriber never acknowledges the message, the Pub/Sub system will eventually + * redeliver the message. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Subscription createSubscription( + String name, String topic, PushConfig pushConfig, int ackDeadlineSeconds) { + Subscription request = + Subscription.newBuilder() + .setName(name) + .setTopic(topic) + .setPushConfig(pushConfig) + .setAckDeadlineSeconds(ackDeadlineSeconds) + .build(); + return createSubscription(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a subscription to a given topic. See the [resource name rules] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). If the subscription already + * exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns + * `NOT_FOUND`. + * + *

If the name is not provided in the request, the server will assign a random name for this + * subscription on the same project as the topic, conforming to the [resource name format] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). The generated name is populated in + * the returned Subscription object. Note that for REST API requests, you must specify a name in + * the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   Subscription request =
+   *       Subscription.newBuilder()
+   *           .setName(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .setPushConfig(PushConfig.newBuilder().build())
+   *           .setAckDeadlineSeconds(2135351438)
+   *           .setRetainAckedMessages(true)
+   *           .setMessageRetentionDuration(Duration.newBuilder().build())
+   *           .putAllLabels(new HashMap())
+   *           .setEnableMessageOrdering(true)
+   *           .setExpirationPolicy(ExpirationPolicy.newBuilder().build())
+   *           .setFilter("filter-1274492040")
+   *           .setDeadLetterPolicy(DeadLetterPolicy.newBuilder().build())
+   *           .setRetryPolicy(RetryPolicy.newBuilder().build())
+   *           .setDetached(true)
+   *           .build();
+   *   Subscription response = subscriptionAdminClient.createSubscription(request);
+   * }
+   * }
+ * + * @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 Subscription createSubscription(Subscription request) { + return createSubscriptionCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a subscription to a given topic. See the [resource name rules] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). If the subscription already + * exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns + * `NOT_FOUND`. + * + *

If the name is not provided in the request, the server will assign a random name for this + * subscription on the same project as the topic, conforming to the [resource name format] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). The generated name is populated in + * the returned Subscription object. Note that for REST API requests, you must specify a name in + * the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   Subscription request =
+   *       Subscription.newBuilder()
+   *           .setName(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .setPushConfig(PushConfig.newBuilder().build())
+   *           .setAckDeadlineSeconds(2135351438)
+   *           .setRetainAckedMessages(true)
+   *           .setMessageRetentionDuration(Duration.newBuilder().build())
+   *           .putAllLabels(new HashMap())
+   *           .setEnableMessageOrdering(true)
+   *           .setExpirationPolicy(ExpirationPolicy.newBuilder().build())
+   *           .setFilter("filter-1274492040")
+   *           .setDeadLetterPolicy(DeadLetterPolicy.newBuilder().build())
+   *           .setRetryPolicy(RetryPolicy.newBuilder().build())
+   *           .setDetached(true)
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.createSubscriptionCallable().futureCall(request);
+   *   // Do something.
+   *   Subscription response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable createSubscriptionCallable() { + return stub.createSubscriptionCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration details of a subscription. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+   *   Subscription response = subscriptionAdminClient.getSubscription(subscription);
+   * }
+   * }
+ * + * @param subscription Required. The name of the subscription to get. Format is + * `projects/{project}/subscriptions/{sub}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Subscription getSubscription(SubscriptionName subscription) { + GetSubscriptionRequest request = + GetSubscriptionRequest.newBuilder() + .setSubscription(subscription == null ? null : subscription.toString()) + .build(); + return getSubscription(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration details of a subscription. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString();
+   *   Subscription response = subscriptionAdminClient.getSubscription(subscription);
+   * }
+   * }
+ * + * @param subscription Required. The name of the subscription to get. Format is + * `projects/{project}/subscriptions/{sub}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Subscription getSubscription(String subscription) { + GetSubscriptionRequest request = + GetSubscriptionRequest.newBuilder().setSubscription(subscription).build(); + return getSubscription(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration details of a subscription. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   GetSubscriptionRequest request =
+   *       GetSubscriptionRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .build();
+   *   Subscription response = subscriptionAdminClient.getSubscription(request);
+   * }
+   * }
+ * + * @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 Subscription getSubscription(GetSubscriptionRequest request) { + return getSubscriptionCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration details of a subscription. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   GetSubscriptionRequest request =
+   *       GetSubscriptionRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.getSubscriptionCallable().futureCall(request);
+   *   // Do something.
+   *   Subscription response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable getSubscriptionCallable() { + return stub.getSubscriptionCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates an existing subscription. Note that certain properties of a subscription, such as its + * topic, are not modifiable. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   UpdateSubscriptionRequest request =
+   *       UpdateSubscriptionRequest.newBuilder()
+   *           .setSubscription(Subscription.newBuilder().build())
+   *           .setUpdateMask(FieldMask.newBuilder().build())
+   *           .build();
+   *   Subscription response = subscriptionAdminClient.updateSubscription(request);
+   * }
+   * }
+ * + * @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 Subscription updateSubscription(UpdateSubscriptionRequest request) { + return updateSubscriptionCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates an existing subscription. Note that certain properties of a subscription, such as its + * topic, are not modifiable. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   UpdateSubscriptionRequest request =
+   *       UpdateSubscriptionRequest.newBuilder()
+   *           .setSubscription(Subscription.newBuilder().build())
+   *           .setUpdateMask(FieldMask.newBuilder().build())
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.updateSubscriptionCallable().futureCall(request);
+   *   // Do something.
+   *   Subscription response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable updateSubscriptionCallable() { + return stub.updateSubscriptionCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists matching subscriptions. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ProjectName project = ProjectName.of("[PROJECT]");
+   *   for (Subscription element : subscriptionAdminClient.listSubscriptions(project).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param project Required. The name of the project in which to list subscriptions. Format is + * `projects/{project-id}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSubscriptionsPagedResponse listSubscriptions(ProjectName project) { + ListSubscriptionsRequest request = + ListSubscriptionsRequest.newBuilder() + .setProject(project == null ? null : project.toString()) + .build(); + return listSubscriptions(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists matching subscriptions. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String project = ProjectName.of("[PROJECT]").toString();
+   *   for (Subscription element : subscriptionAdminClient.listSubscriptions(project).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param project Required. The name of the project in which to list subscriptions. Format is + * `projects/{project-id}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSubscriptionsPagedResponse listSubscriptions(String project) { + ListSubscriptionsRequest request = + ListSubscriptionsRequest.newBuilder().setProject(project).build(); + return listSubscriptions(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists matching subscriptions. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ListSubscriptionsRequest request =
+   *       ListSubscriptionsRequest.newBuilder()
+   *           .setProject(ProjectName.of("[PROJECT]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   for (Subscription element : subscriptionAdminClient.listSubscriptions(request).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @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 ListSubscriptionsPagedResponse listSubscriptions(ListSubscriptionsRequest request) { + return listSubscriptionsPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists matching subscriptions. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ListSubscriptionsRequest request =
+   *       ListSubscriptionsRequest.newBuilder()
+   *           .setProject(ProjectName.of("[PROJECT]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.listSubscriptionsPagedCallable().futureCall(request);
+   *   // Do something.
+   *   for (Subscription element : future.get().iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable + listSubscriptionsPagedCallable() { + return stub.listSubscriptionsPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists matching subscriptions. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ListSubscriptionsRequest request =
+   *       ListSubscriptionsRequest.newBuilder()
+   *           .setProject(ProjectName.of("[PROJECT]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   while (true) {
+   *     ListSubscriptionsResponse response =
+   *         subscriptionAdminClient.listSubscriptionsCallable().call(request);
+   *     for (Subscription element : response.getResponsesList()) {
+   *       // doThingsWith(element);
+   *     }
+   *     String nextPageToken = response.getNextPageToken();
+   *     if (!Strings.isNullOrEmpty(nextPageToken)) {
+   *       request = request.toBuilder().setPageToken(nextPageToken).build();
+   *     } else {
+   *       break;
+   *     }
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable + listSubscriptionsCallable() { + return stub.listSubscriptionsCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes an existing subscription. All messages retained in the subscription are immediately + * dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is + * deleted, a new one may be created with the same name, but the new one has no association with + * the old subscription or its topic unless the same topic is specified. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+   *   subscriptionAdminClient.deleteSubscription(subscription);
+   * }
+   * }
+ * + * @param subscription Required. The subscription to delete. Format is + * `projects/{project}/subscriptions/{sub}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void deleteSubscription(SubscriptionName subscription) { + DeleteSubscriptionRequest request = + DeleteSubscriptionRequest.newBuilder() + .setSubscription(subscription == null ? null : subscription.toString()) + .build(); + deleteSubscription(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes an existing subscription. All messages retained in the subscription are immediately + * dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is + * deleted, a new one may be created with the same name, but the new one has no association with + * the old subscription or its topic unless the same topic is specified. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString();
+   *   subscriptionAdminClient.deleteSubscription(subscription);
+   * }
+   * }
+ * + * @param subscription Required. The subscription to delete. Format is + * `projects/{project}/subscriptions/{sub}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void deleteSubscription(String subscription) { + DeleteSubscriptionRequest request = + DeleteSubscriptionRequest.newBuilder().setSubscription(subscription).build(); + deleteSubscription(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes an existing subscription. All messages retained in the subscription are immediately + * dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is + * deleted, a new one may be created with the same name, but the new one has no association with + * the old subscription or its topic unless the same topic is specified. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   DeleteSubscriptionRequest request =
+   *       DeleteSubscriptionRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .build();
+   *   subscriptionAdminClient.deleteSubscription(request);
+   * }
+   * }
+ * + * @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 void deleteSubscription(DeleteSubscriptionRequest request) { + deleteSubscriptionCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes an existing subscription. All messages retained in the subscription are immediately + * dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is + * deleted, a new one may be created with the same name, but the new one has no association with + * the old subscription or its topic unless the same topic is specified. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   DeleteSubscriptionRequest request =
+   *       DeleteSubscriptionRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.deleteSubscriptionCallable().futureCall(request);
+   *   // Do something.
+   *   future.get();
+   * }
+   * }
+ */ + public final UnaryCallable deleteSubscriptionCallable() { + return stub.deleteSubscriptionCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Modifies the ack deadline for a specific message. This method is useful to indicate that more + * time is needed to process a message by the subscriber, or to make the message available for + * redelivery if the processing was interrupted. Note that this does not modify the + * subscription-level `ackDeadlineSeconds` used for subsequent messages. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+   *   List ackIds = new ArrayList<>();
+   *   int ackDeadlineSeconds = 2135351438;
+   *   subscriptionAdminClient.modifyAckDeadline(subscription, ackIds, ackDeadlineSeconds);
+   * }
+   * }
+ * + * @param subscription Required. The name of the subscription. Format is + * `projects/{project}/subscriptions/{sub}`. + * @param ackIds Required. List of acknowledgment IDs. + * @param ackDeadlineSeconds Required. The new ack deadline with respect to the time this request + * was sent to the Pub/Sub system. For example, if the value is 10, the new ack deadline will + * expire 10 seconds after the `ModifyAckDeadline` call was made. Specifying zero might + * immediately make the message available for delivery to another subscriber client. This + * typically results in an increase in the rate of message redeliveries (that is, duplicates). + * The minimum deadline you can specify is 0 seconds. The maximum deadline you can specify is + * 600 seconds (10 minutes). + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void modifyAckDeadline( + SubscriptionName subscription, List ackIds, int ackDeadlineSeconds) { + ModifyAckDeadlineRequest request = + ModifyAckDeadlineRequest.newBuilder() + .setSubscription(subscription == null ? null : subscription.toString()) + .addAllAckIds(ackIds) + .setAckDeadlineSeconds(ackDeadlineSeconds) + .build(); + modifyAckDeadline(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Modifies the ack deadline for a specific message. This method is useful to indicate that more + * time is needed to process a message by the subscriber, or to make the message available for + * redelivery if the processing was interrupted. Note that this does not modify the + * subscription-level `ackDeadlineSeconds` used for subsequent messages. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString();
+   *   List ackIds = new ArrayList<>();
+   *   int ackDeadlineSeconds = 2135351438;
+   *   subscriptionAdminClient.modifyAckDeadline(subscription, ackIds, ackDeadlineSeconds);
+   * }
+   * }
+ * + * @param subscription Required. The name of the subscription. Format is + * `projects/{project}/subscriptions/{sub}`. + * @param ackIds Required. List of acknowledgment IDs. + * @param ackDeadlineSeconds Required. The new ack deadline with respect to the time this request + * was sent to the Pub/Sub system. For example, if the value is 10, the new ack deadline will + * expire 10 seconds after the `ModifyAckDeadline` call was made. Specifying zero might + * immediately make the message available for delivery to another subscriber client. This + * typically results in an increase in the rate of message redeliveries (that is, duplicates). + * The minimum deadline you can specify is 0 seconds. The maximum deadline you can specify is + * 600 seconds (10 minutes). + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void modifyAckDeadline( + String subscription, List ackIds, int ackDeadlineSeconds) { + ModifyAckDeadlineRequest request = + ModifyAckDeadlineRequest.newBuilder() + .setSubscription(subscription) + .addAllAckIds(ackIds) + .setAckDeadlineSeconds(ackDeadlineSeconds) + .build(); + modifyAckDeadline(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Modifies the ack deadline for a specific message. This method is useful to indicate that more + * time is needed to process a message by the subscriber, or to make the message available for + * redelivery if the processing was interrupted. Note that this does not modify the + * subscription-level `ackDeadlineSeconds` used for subsequent messages. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ModifyAckDeadlineRequest request =
+   *       ModifyAckDeadlineRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .addAllAckIds(new ArrayList())
+   *           .setAckDeadlineSeconds(2135351438)
+   *           .build();
+   *   subscriptionAdminClient.modifyAckDeadline(request);
+   * }
+   * }
+ * + * @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 void modifyAckDeadline(ModifyAckDeadlineRequest request) { + modifyAckDeadlineCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Modifies the ack deadline for a specific message. This method is useful to indicate that more + * time is needed to process a message by the subscriber, or to make the message available for + * redelivery if the processing was interrupted. Note that this does not modify the + * subscription-level `ackDeadlineSeconds` used for subsequent messages. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ModifyAckDeadlineRequest request =
+   *       ModifyAckDeadlineRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .addAllAckIds(new ArrayList())
+   *           .setAckDeadlineSeconds(2135351438)
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.modifyAckDeadlineCallable().futureCall(request);
+   *   // Do something.
+   *   future.get();
+   * }
+   * }
+ */ + public final UnaryCallable modifyAckDeadlineCallable() { + return stub.modifyAckDeadlineCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The + * Pub/Sub system can remove the relevant messages from the subscription. + * + *

Acknowledging a message whose ack deadline has expired may succeed, but such a message may + * be redelivered later. Acknowledging a message more than once will not result in an error. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+   *   List ackIds = new ArrayList<>();
+   *   subscriptionAdminClient.acknowledge(subscription, ackIds);
+   * }
+   * }
+ * + * @param subscription Required. The subscription whose message is being acknowledged. Format is + * `projects/{project}/subscriptions/{sub}`. + * @param ackIds Required. The acknowledgment ID for the messages being acknowledged that was + * returned by the Pub/Sub system in the `Pull` response. Must not be empty. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void acknowledge(SubscriptionName subscription, List ackIds) { + AcknowledgeRequest request = + AcknowledgeRequest.newBuilder() + .setSubscription(subscription == null ? null : subscription.toString()) + .addAllAckIds(ackIds) + .build(); + acknowledge(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The + * Pub/Sub system can remove the relevant messages from the subscription. + * + *

Acknowledging a message whose ack deadline has expired may succeed, but such a message may + * be redelivered later. Acknowledging a message more than once will not result in an error. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString();
+   *   List ackIds = new ArrayList<>();
+   *   subscriptionAdminClient.acknowledge(subscription, ackIds);
+   * }
+   * }
+ * + * @param subscription Required. The subscription whose message is being acknowledged. Format is + * `projects/{project}/subscriptions/{sub}`. + * @param ackIds Required. The acknowledgment ID for the messages being acknowledged that was + * returned by the Pub/Sub system in the `Pull` response. Must not be empty. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void acknowledge(String subscription, List ackIds) { + AcknowledgeRequest request = + AcknowledgeRequest.newBuilder().setSubscription(subscription).addAllAckIds(ackIds).build(); + acknowledge(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The + * Pub/Sub system can remove the relevant messages from the subscription. + * + *

Acknowledging a message whose ack deadline has expired may succeed, but such a message may + * be redelivered later. Acknowledging a message more than once will not result in an error. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   AcknowledgeRequest request =
+   *       AcknowledgeRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .addAllAckIds(new ArrayList())
+   *           .build();
+   *   subscriptionAdminClient.acknowledge(request);
+   * }
+   * }
+ * + * @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 void acknowledge(AcknowledgeRequest request) { + acknowledgeCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The + * Pub/Sub system can remove the relevant messages from the subscription. + * + *

Acknowledging a message whose ack deadline has expired may succeed, but such a message may + * be redelivered later. Acknowledging a message more than once will not result in an error. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   AcknowledgeRequest request =
+   *       AcknowledgeRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .addAllAckIds(new ArrayList())
+   *           .build();
+   *   ApiFuture future = subscriptionAdminClient.acknowledgeCallable().futureCall(request);
+   *   // Do something.
+   *   future.get();
+   * }
+   * }
+ */ + public final UnaryCallable acknowledgeCallable() { + return stub.acknowledgeCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Pulls messages from the server. The server may return `UNAVAILABLE` if there are too many + * concurrent pull requests pending for the given subscription. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+   *   boolean returnImmediately = true;
+   *   int maxMessages = 496131527;
+   *   PullResponse response =
+   *       subscriptionAdminClient.pull(subscription, returnImmediately, maxMessages);
+   * }
+   * }
+ * + * @param subscription Required. The subscription from which messages should be pulled. Format is + * `projects/{project}/subscriptions/{sub}`. + * @param returnImmediately Optional. If this field set to true, the system will respond + * immediately even if it there are no messages available to return in the `Pull` response. + * Otherwise, the system may wait (for a bounded amount of time) until at least one message is + * available, rather than returning no messages. Warning: setting this field to `true` is + * discouraged because it adversely impacts the performance of `Pull` operations. We recommend + * that users do not set this field. + * @param maxMessages Required. The maximum number of messages to return for this request. Must be + * a positive integer. The Pub/Sub system may return fewer than the number specified. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final PullResponse pull( + SubscriptionName subscription, boolean returnImmediately, int maxMessages) { + PullRequest request = + PullRequest.newBuilder() + .setSubscription(subscription == null ? null : subscription.toString()) + .setReturnImmediately(returnImmediately) + .setMaxMessages(maxMessages) + .build(); + return pull(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Pulls messages from the server. The server may return `UNAVAILABLE` if there are too many + * concurrent pull requests pending for the given subscription. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString();
+   *   boolean returnImmediately = true;
+   *   int maxMessages = 496131527;
+   *   PullResponse response =
+   *       subscriptionAdminClient.pull(subscription, returnImmediately, maxMessages);
+   * }
+   * }
+ * + * @param subscription Required. The subscription from which messages should be pulled. Format is + * `projects/{project}/subscriptions/{sub}`. + * @param returnImmediately Optional. If this field set to true, the system will respond + * immediately even if it there are no messages available to return in the `Pull` response. + * Otherwise, the system may wait (for a bounded amount of time) until at least one message is + * available, rather than returning no messages. Warning: setting this field to `true` is + * discouraged because it adversely impacts the performance of `Pull` operations. We recommend + * that users do not set this field. + * @param maxMessages Required. The maximum number of messages to return for this request. Must be + * a positive integer. The Pub/Sub system may return fewer than the number specified. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final PullResponse pull(String subscription, boolean returnImmediately, int maxMessages) { + PullRequest request = + PullRequest.newBuilder() + .setSubscription(subscription) + .setReturnImmediately(returnImmediately) + .setMaxMessages(maxMessages) + .build(); + return pull(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Pulls messages from the server. The server may return `UNAVAILABLE` if there are too many + * concurrent pull requests pending for the given subscription. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   PullRequest request =
+   *       PullRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .setReturnImmediately(true)
+   *           .setMaxMessages(496131527)
+   *           .build();
+   *   PullResponse response = subscriptionAdminClient.pull(request);
+   * }
+   * }
+ * + * @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 PullResponse pull(PullRequest request) { + return pullCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Pulls messages from the server. The server may return `UNAVAILABLE` if there are too many + * concurrent pull requests pending for the given subscription. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   PullRequest request =
+   *       PullRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .setReturnImmediately(true)
+   *           .setMaxMessages(496131527)
+   *           .build();
+   *   ApiFuture future = subscriptionAdminClient.pullCallable().futureCall(request);
+   *   // Do something.
+   *   PullResponse response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable pullCallable() { + return stub.pullCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Establishes a stream with the server, which sends messages down to the client. The client + * streams acknowledgements and ack deadline modifications back to the server. The server will + * close the stream and return the status on any error. The server may close the stream with + * status `UNAVAILABLE` to reassign server-side resources, in which case, the client should + * re-establish the stream. Flow control can be achieved by configuring the underlying RPC + * channel. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   BidiStream bidiStream =
+   *       subscriptionAdminClient.streamingPullCallable().call();
+   *   StreamingPullRequest request =
+   *       StreamingPullRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .addAllAckIds(new ArrayList())
+   *           .addAllModifyDeadlineSeconds(new ArrayList())
+   *           .addAllModifyDeadlineAckIds(new ArrayList())
+   *           .setStreamAckDeadlineSeconds(1875467245)
+   *           .setClientId("clientId908408390")
+   *           .setMaxOutstandingMessages(-1315266996)
+   *           .setMaxOutstandingBytes(-2103098517)
+   *           .build();
+   *   bidiStream.send(request);
+   *   for (StreamingPullResponse response : bidiStream) {
+   *     // Do something when a response is received.
+   *   }
+   * }
+   * }
+ */ + public final BidiStreamingCallable + streamingPullCallable() { + return stub.streamingPullCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Modifies the `PushConfig` for a specified subscription. + * + *

This may be used to change a push subscription to a pull one (signified by an empty + * `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push + * subscription. Messages will accumulate for delivery continuously through the call regardless of + * changes to the `PushConfig`. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+   *   PushConfig pushConfig = PushConfig.newBuilder().build();
+   *   subscriptionAdminClient.modifyPushConfig(subscription, pushConfig);
+   * }
+   * }
+ * + * @param subscription Required. The name of the subscription. Format is + * `projects/{project}/subscriptions/{sub}`. + * @param pushConfig Required. The push configuration for future deliveries. + *

An empty `pushConfig` indicates that the Pub/Sub system should stop pushing messages + * from the given subscription and allow messages to be pulled and acknowledged - effectively + * pausing the subscription if `Pull` or `StreamingPull` is not called. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void modifyPushConfig(SubscriptionName subscription, PushConfig pushConfig) { + ModifyPushConfigRequest request = + ModifyPushConfigRequest.newBuilder() + .setSubscription(subscription == null ? null : subscription.toString()) + .setPushConfig(pushConfig) + .build(); + modifyPushConfig(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Modifies the `PushConfig` for a specified subscription. + * + *

This may be used to change a push subscription to a pull one (signified by an empty + * `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push + * subscription. Messages will accumulate for delivery continuously through the call regardless of + * changes to the `PushConfig`. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString();
+   *   PushConfig pushConfig = PushConfig.newBuilder().build();
+   *   subscriptionAdminClient.modifyPushConfig(subscription, pushConfig);
+   * }
+   * }
+ * + * @param subscription Required. The name of the subscription. Format is + * `projects/{project}/subscriptions/{sub}`. + * @param pushConfig Required. The push configuration for future deliveries. + *

An empty `pushConfig` indicates that the Pub/Sub system should stop pushing messages + * from the given subscription and allow messages to be pulled and acknowledged - effectively + * pausing the subscription if `Pull` or `StreamingPull` is not called. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void modifyPushConfig(String subscription, PushConfig pushConfig) { + ModifyPushConfigRequest request = + ModifyPushConfigRequest.newBuilder() + .setSubscription(subscription) + .setPushConfig(pushConfig) + .build(); + modifyPushConfig(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Modifies the `PushConfig` for a specified subscription. + * + *

This may be used to change a push subscription to a pull one (signified by an empty + * `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push + * subscription. Messages will accumulate for delivery continuously through the call regardless of + * changes to the `PushConfig`. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ModifyPushConfigRequest request =
+   *       ModifyPushConfigRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .setPushConfig(PushConfig.newBuilder().build())
+   *           .build();
+   *   subscriptionAdminClient.modifyPushConfig(request);
+   * }
+   * }
+ * + * @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 void modifyPushConfig(ModifyPushConfigRequest request) { + modifyPushConfigCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Modifies the `PushConfig` for a specified subscription. + * + *

This may be used to change a push subscription to a pull one (signified by an empty + * `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push + * subscription. Messages will accumulate for delivery continuously through the call regardless of + * changes to the `PushConfig`. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ModifyPushConfigRequest request =
+   *       ModifyPushConfigRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .setPushConfig(PushConfig.newBuilder().build())
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.modifyPushConfigCallable().futureCall(request);
+   *   // Do something.
+   *   future.get();
+   * }
+   * }
+ */ + public final UnaryCallable modifyPushConfigCallable() { + return stub.modifyPushConfigCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration details of a snapshot. Snapshots are used in <a + * href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which + * allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment + * state of messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SnapshotName snapshot = SnapshotName.of("[PROJECT]", "[SNAPSHOT]");
+   *   Snapshot response = subscriptionAdminClient.getSnapshot(snapshot);
+   * }
+   * }
+ * + * @param snapshot Required. The name of the snapshot to get. Format is + * `projects/{project}/snapshots/{snap}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Snapshot getSnapshot(SnapshotName snapshot) { + GetSnapshotRequest request = + GetSnapshotRequest.newBuilder() + .setSnapshot(snapshot == null ? null : snapshot.toString()) + .build(); + return getSnapshot(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration details of a snapshot. Snapshots are used in <a + * href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which + * allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment + * state of messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String snapshot = SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString();
+   *   Snapshot response = subscriptionAdminClient.getSnapshot(snapshot);
+   * }
+   * }
+ * + * @param snapshot Required. The name of the snapshot to get. Format is + * `projects/{project}/snapshots/{snap}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Snapshot getSnapshot(String snapshot) { + GetSnapshotRequest request = GetSnapshotRequest.newBuilder().setSnapshot(snapshot).build(); + return getSnapshot(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration details of a snapshot. Snapshots are used in <a + * href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which + * allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment + * state of messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   GetSnapshotRequest request =
+   *       GetSnapshotRequest.newBuilder()
+   *           .setSnapshot(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
+   *           .build();
+   *   Snapshot response = subscriptionAdminClient.getSnapshot(request);
+   * }
+   * }
+ * + * @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 Snapshot getSnapshot(GetSnapshotRequest request) { + return getSnapshotCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration details of a snapshot. Snapshots are used in <a + * href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which + * allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment + * state of messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   GetSnapshotRequest request =
+   *       GetSnapshotRequest.newBuilder()
+   *           .setSnapshot(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.getSnapshotCallable().futureCall(request);
+   *   // Do something.
+   *   Snapshot response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable getSnapshotCallable() { + return stub.getSnapshotCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the existing snapshots. Snapshots are used in [Seek]( + * https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ProjectName project = ProjectName.of("[PROJECT]");
+   *   for (Snapshot element : subscriptionAdminClient.listSnapshots(project).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param project Required. The name of the project in which to list snapshots. Format is + * `projects/{project-id}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSnapshotsPagedResponse listSnapshots(ProjectName project) { + ListSnapshotsRequest request = + ListSnapshotsRequest.newBuilder() + .setProject(project == null ? null : project.toString()) + .build(); + return listSnapshots(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the existing snapshots. Snapshots are used in [Seek]( + * https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String project = ProjectName.of("[PROJECT]").toString();
+   *   for (Snapshot element : subscriptionAdminClient.listSnapshots(project).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param project Required. The name of the project in which to list snapshots. Format is + * `projects/{project-id}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListSnapshotsPagedResponse listSnapshots(String project) { + ListSnapshotsRequest request = ListSnapshotsRequest.newBuilder().setProject(project).build(); + return listSnapshots(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the existing snapshots. Snapshots are used in [Seek]( + * https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ListSnapshotsRequest request =
+   *       ListSnapshotsRequest.newBuilder()
+   *           .setProject(ProjectName.of("[PROJECT]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   for (Snapshot element : subscriptionAdminClient.listSnapshots(request).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @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 ListSnapshotsPagedResponse listSnapshots(ListSnapshotsRequest request) { + return listSnapshotsPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the existing snapshots. Snapshots are used in [Seek]( + * https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ListSnapshotsRequest request =
+   *       ListSnapshotsRequest.newBuilder()
+   *           .setProject(ProjectName.of("[PROJECT]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.listSnapshotsPagedCallable().futureCall(request);
+   *   // Do something.
+   *   for (Snapshot element : future.get().iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable + listSnapshotsPagedCallable() { + return stub.listSnapshotsPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the existing snapshots. Snapshots are used in [Seek]( + * https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   ListSnapshotsRequest request =
+   *       ListSnapshotsRequest.newBuilder()
+   *           .setProject(ProjectName.of("[PROJECT]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   while (true) {
+   *     ListSnapshotsResponse response =
+   *         subscriptionAdminClient.listSnapshotsCallable().call(request);
+   *     for (Snapshot element : response.getResponsesList()) {
+   *       // doThingsWith(element);
+   *     }
+   *     String nextPageToken = response.getNextPageToken();
+   *     if (!Strings.isNullOrEmpty(nextPageToken)) {
+   *       request = request.toBuilder().setPageToken(nextPageToken).build();
+   *     } else {
+   *       break;
+   *     }
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable listSnapshotsCallable() { + return stub.listSnapshotsCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a snapshot from the requested subscription. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. If the snapshot + * already exists, returns `ALREADY_EXISTS`. If the requested subscription doesn't exist, returns + * `NOT_FOUND`. If the backlog in the subscription is too old -- and the resulting snapshot would + * expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. See also the + * `Snapshot.expire_time` field. If the name is not provided in the request, the server will + * assign a random name for this snapshot on the same project as the subscription, conforming to + * the [resource name format] (https://cloud.google.com/pubsub/docs/admin#resource_names). The + * generated name is populated in the returned Snapshot object. Note that for REST API requests, + * you must specify a name in the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SnapshotName name = SnapshotName.of("[PROJECT]", "[SNAPSHOT]");
+   *   SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+   *   Snapshot response = subscriptionAdminClient.createSnapshot(name, subscription);
+   * }
+   * }
+ * + * @param name Required. User-provided name for this snapshot. If the name is not provided in the + * request, the server will assign a random name for this snapshot on the same project as the + * subscription. Note that for REST API requests, you must specify a name. See the <a + * href="https://cloud.google.com/pubsub/docs/admin#resource_names"> resource name + * rules</a>. Format is `projects/{project}/snapshots/{snap}`. + * @param subscription Required. The subscription whose backlog the snapshot retains. + * Specifically, the created snapshot is guaranteed to retain: (a) The existing backlog on the + * subscription. More precisely, this is defined as the messages in the subscription's backlog + * that are unacknowledged upon the successful completion of the `CreateSnapshot` request; as + * well as: (b) Any messages published to the subscription's topic following the successful + * completion of the CreateSnapshot request. Format is + * `projects/{project}/subscriptions/{sub}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Snapshot createSnapshot(SnapshotName name, SubscriptionName subscription) { + CreateSnapshotRequest request = + CreateSnapshotRequest.newBuilder() + .setName(name == null ? null : name.toString()) + .setSubscription(subscription == null ? null : subscription.toString()) + .build(); + return createSnapshot(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a snapshot from the requested subscription. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. If the snapshot + * already exists, returns `ALREADY_EXISTS`. If the requested subscription doesn't exist, returns + * `NOT_FOUND`. If the backlog in the subscription is too old -- and the resulting snapshot would + * expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. See also the + * `Snapshot.expire_time` field. If the name is not provided in the request, the server will + * assign a random name for this snapshot on the same project as the subscription, conforming to + * the [resource name format] (https://cloud.google.com/pubsub/docs/admin#resource_names). The + * generated name is populated in the returned Snapshot object. Note that for REST API requests, + * you must specify a name in the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SnapshotName name = SnapshotName.of("[PROJECT]", "[SNAPSHOT]");
+   *   String subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString();
+   *   Snapshot response = subscriptionAdminClient.createSnapshot(name, subscription);
+   * }
+   * }
+ * + * @param name Required. User-provided name for this snapshot. If the name is not provided in the + * request, the server will assign a random name for this snapshot on the same project as the + * subscription. Note that for REST API requests, you must specify a name. See the <a + * href="https://cloud.google.com/pubsub/docs/admin#resource_names"> resource name + * rules</a>. Format is `projects/{project}/snapshots/{snap}`. + * @param subscription Required. The subscription whose backlog the snapshot retains. + * Specifically, the created snapshot is guaranteed to retain: (a) The existing backlog on the + * subscription. More precisely, this is defined as the messages in the subscription's backlog + * that are unacknowledged upon the successful completion of the `CreateSnapshot` request; as + * well as: (b) Any messages published to the subscription's topic following the successful + * completion of the CreateSnapshot request. Format is + * `projects/{project}/subscriptions/{sub}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Snapshot createSnapshot(SnapshotName name, String subscription) { + CreateSnapshotRequest request = + CreateSnapshotRequest.newBuilder() + .setName(name == null ? null : name.toString()) + .setSubscription(subscription) + .build(); + return createSnapshot(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a snapshot from the requested subscription. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. If the snapshot + * already exists, returns `ALREADY_EXISTS`. If the requested subscription doesn't exist, returns + * `NOT_FOUND`. If the backlog in the subscription is too old -- and the resulting snapshot would + * expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. See also the + * `Snapshot.expire_time` field. If the name is not provided in the request, the server will + * assign a random name for this snapshot on the same project as the subscription, conforming to + * the [resource name format] (https://cloud.google.com/pubsub/docs/admin#resource_names). The + * generated name is populated in the returned Snapshot object. Note that for REST API requests, + * you must specify a name in the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String name = SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString();
+   *   SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+   *   Snapshot response = subscriptionAdminClient.createSnapshot(name, subscription);
+   * }
+   * }
+ * + * @param name Required. User-provided name for this snapshot. If the name is not provided in the + * request, the server will assign a random name for this snapshot on the same project as the + * subscription. Note that for REST API requests, you must specify a name. See the <a + * href="https://cloud.google.com/pubsub/docs/admin#resource_names"> resource name + * rules</a>. Format is `projects/{project}/snapshots/{snap}`. + * @param subscription Required. The subscription whose backlog the snapshot retains. + * Specifically, the created snapshot is guaranteed to retain: (a) The existing backlog on the + * subscription. More precisely, this is defined as the messages in the subscription's backlog + * that are unacknowledged upon the successful completion of the `CreateSnapshot` request; as + * well as: (b) Any messages published to the subscription's topic following the successful + * completion of the CreateSnapshot request. Format is + * `projects/{project}/subscriptions/{sub}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Snapshot createSnapshot(String name, SubscriptionName subscription) { + CreateSnapshotRequest request = + CreateSnapshotRequest.newBuilder() + .setName(name) + .setSubscription(subscription == null ? null : subscription.toString()) + .build(); + return createSnapshot(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a snapshot from the requested subscription. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. If the snapshot + * already exists, returns `ALREADY_EXISTS`. If the requested subscription doesn't exist, returns + * `NOT_FOUND`. If the backlog in the subscription is too old -- and the resulting snapshot would + * expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. See also the + * `Snapshot.expire_time` field. If the name is not provided in the request, the server will + * assign a random name for this snapshot on the same project as the subscription, conforming to + * the [resource name format] (https://cloud.google.com/pubsub/docs/admin#resource_names). The + * generated name is populated in the returned Snapshot object. Note that for REST API requests, + * you must specify a name in the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String name = SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString();
+   *   String subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString();
+   *   Snapshot response = subscriptionAdminClient.createSnapshot(name, subscription);
+   * }
+   * }
+ * + * @param name Required. User-provided name for this snapshot. If the name is not provided in the + * request, the server will assign a random name for this snapshot on the same project as the + * subscription. Note that for REST API requests, you must specify a name. See the <a + * href="https://cloud.google.com/pubsub/docs/admin#resource_names"> resource name + * rules</a>. Format is `projects/{project}/snapshots/{snap}`. + * @param subscription Required. The subscription whose backlog the snapshot retains. + * Specifically, the created snapshot is guaranteed to retain: (a) The existing backlog on the + * subscription. More precisely, this is defined as the messages in the subscription's backlog + * that are unacknowledged upon the successful completion of the `CreateSnapshot` request; as + * well as: (b) Any messages published to the subscription's topic following the successful + * completion of the CreateSnapshot request. Format is + * `projects/{project}/subscriptions/{sub}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Snapshot createSnapshot(String name, String subscription) { + CreateSnapshotRequest request = + CreateSnapshotRequest.newBuilder().setName(name).setSubscription(subscription).build(); + return createSnapshot(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a snapshot from the requested subscription. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. If the snapshot + * already exists, returns `ALREADY_EXISTS`. If the requested subscription doesn't exist, returns + * `NOT_FOUND`. If the backlog in the subscription is too old -- and the resulting snapshot would + * expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. See also the + * `Snapshot.expire_time` field. If the name is not provided in the request, the server will + * assign a random name for this snapshot on the same project as the subscription, conforming to + * the [resource name format] (https://cloud.google.com/pubsub/docs/admin#resource_names). The + * generated name is populated in the returned Snapshot object. Note that for REST API requests, + * you must specify a name in the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   CreateSnapshotRequest request =
+   *       CreateSnapshotRequest.newBuilder()
+   *           .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .putAllLabels(new HashMap())
+   *           .build();
+   *   Snapshot response = subscriptionAdminClient.createSnapshot(request);
+   * }
+   * }
+ * + * @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 Snapshot createSnapshot(CreateSnapshotRequest request) { + return createSnapshotCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates a snapshot from the requested subscription. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. If the snapshot + * already exists, returns `ALREADY_EXISTS`. If the requested subscription doesn't exist, returns + * `NOT_FOUND`. If the backlog in the subscription is too old -- and the resulting snapshot would + * expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. See also the + * `Snapshot.expire_time` field. If the name is not provided in the request, the server will + * assign a random name for this snapshot on the same project as the subscription, conforming to + * the [resource name format] (https://cloud.google.com/pubsub/docs/admin#resource_names). The + * generated name is populated in the returned Snapshot object. Note that for REST API requests, + * you must specify a name in the request. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   CreateSnapshotRequest request =
+   *       CreateSnapshotRequest.newBuilder()
+   *           .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .putAllLabels(new HashMap())
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.createSnapshotCallable().futureCall(request);
+   *   // Do something.
+   *   Snapshot response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable createSnapshotCallable() { + return stub.createSnapshotCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates an existing snapshot. Snapshots are used in <a + * href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which + * allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment + * state of messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   UpdateSnapshotRequest request =
+   *       UpdateSnapshotRequest.newBuilder()
+   *           .setSnapshot(Snapshot.newBuilder().build())
+   *           .setUpdateMask(FieldMask.newBuilder().build())
+   *           .build();
+   *   Snapshot response = subscriptionAdminClient.updateSnapshot(request);
+   * }
+   * }
+ * + * @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 Snapshot updateSnapshot(UpdateSnapshotRequest request) { + return updateSnapshotCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates an existing snapshot. Snapshots are used in <a + * href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which + * allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment + * state of messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   UpdateSnapshotRequest request =
+   *       UpdateSnapshotRequest.newBuilder()
+   *           .setSnapshot(Snapshot.newBuilder().build())
+   *           .setUpdateMask(FieldMask.newBuilder().build())
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.updateSnapshotCallable().futureCall(request);
+   *   // Do something.
+   *   Snapshot response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable updateSnapshotCallable() { + return stub.updateSnapshotCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Removes an existing snapshot. Snapshots are used in [Seek] + * (https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. When the snapshot is deleted, all + * messages retained in the snapshot are immediately dropped. After a snapshot is deleted, a new + * one may be created with the same name, but the new one has no association with the old snapshot + * or its subscription, unless the same subscription is specified. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SnapshotName snapshot = SnapshotName.of("[PROJECT]", "[SNAPSHOT]");
+   *   subscriptionAdminClient.deleteSnapshot(snapshot);
+   * }
+   * }
+ * + * @param snapshot Required. The name of the snapshot to delete. Format is + * `projects/{project}/snapshots/{snap}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void deleteSnapshot(SnapshotName snapshot) { + DeleteSnapshotRequest request = + DeleteSnapshotRequest.newBuilder() + .setSnapshot(snapshot == null ? null : snapshot.toString()) + .build(); + deleteSnapshot(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Removes an existing snapshot. Snapshots are used in [Seek] + * (https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. When the snapshot is deleted, all + * messages retained in the snapshot are immediately dropped. After a snapshot is deleted, a new + * one may be created with the same name, but the new one has no association with the old snapshot + * or its subscription, unless the same subscription is specified. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   String snapshot = SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString();
+   *   subscriptionAdminClient.deleteSnapshot(snapshot);
+   * }
+   * }
+ * + * @param snapshot Required. The name of the snapshot to delete. Format is + * `projects/{project}/snapshots/{snap}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void deleteSnapshot(String snapshot) { + DeleteSnapshotRequest request = + DeleteSnapshotRequest.newBuilder().setSnapshot(snapshot).build(); + deleteSnapshot(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Removes an existing snapshot. Snapshots are used in [Seek] + * (https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. When the snapshot is deleted, all + * messages retained in the snapshot are immediately dropped. After a snapshot is deleted, a new + * one may be created with the same name, but the new one has no association with the old snapshot + * or its subscription, unless the same subscription is specified. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   DeleteSnapshotRequest request =
+   *       DeleteSnapshotRequest.newBuilder()
+   *           .setSnapshot(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
+   *           .build();
+   *   subscriptionAdminClient.deleteSnapshot(request);
+   * }
+   * }
+ * + * @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 void deleteSnapshot(DeleteSnapshotRequest request) { + deleteSnapshotCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Removes an existing snapshot. Snapshots are used in [Seek] + * (https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. When the snapshot is deleted, all + * messages retained in the snapshot are immediately dropped. After a snapshot is deleted, a new + * one may be created with the same name, but the new one has no association with the old snapshot + * or its subscription, unless the same subscription is specified. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   DeleteSnapshotRequest request =
+   *       DeleteSnapshotRequest.newBuilder()
+   *           .setSnapshot(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.deleteSnapshotCallable().futureCall(request);
+   *   // Do something.
+   *   future.get();
+   * }
+   * }
+ */ + public final UnaryCallable deleteSnapshotCallable() { + return stub.deleteSnapshotCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Seeks an existing subscription to a point in time or to a given snapshot, whichever is provided + * in the request. Snapshots are used in [Seek] + * (https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. Note that both the subscription + * and the snapshot must be on the same topic. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SeekRequest request =
+   *       SeekRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .build();
+   *   SeekResponse response = subscriptionAdminClient.seek(request);
+   * }
+   * }
+ * + * @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 SeekResponse seek(SeekRequest request) { + return seekCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Seeks an existing subscription to a point in time or to a given snapshot, whichever is provided + * in the request. Snapshots are used in [Seek] + * (https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to manage + * message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in + * an existing subscription to the state captured by a snapshot. Note that both the subscription + * and the snapshot must be on the same topic. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SeekRequest request =
+   *       SeekRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .build();
+   *   ApiFuture future = subscriptionAdminClient.seekCallable().futureCall(request);
+   *   // Do something.
+   *   SeekResponse response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable seekCallable() { + return stub.seekCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sets the access control policy on the specified resource. Replacesany existing policy. + * + *

Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SetIamPolicyRequest request =
+   *       SetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setPolicy(Policy.newBuilder().build())
+   *           .build();
+   *   Policy response = subscriptionAdminClient.setIamPolicy(request);
+   * }
+   * }
+ * + * @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 Policy setIamPolicy(SetIamPolicyRequest request) { + return setIamPolicyCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sets the access control policy on the specified resource. Replacesany existing policy. + * + *

Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   SetIamPolicyRequest request =
+   *       SetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setPolicy(Policy.newBuilder().build())
+   *           .build();
+   *   ApiFuture future = subscriptionAdminClient.setIamPolicyCallable().futureCall(request);
+   *   // Do something.
+   *   Policy response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable setIamPolicyCallable() { + return stub.setIamPolicyCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the access control policy for a resource. Returns an empty policyif the resource exists + * and does not have a policy set. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   GetIamPolicyRequest request =
+   *       GetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setOptions(GetPolicyOptions.newBuilder().build())
+   *           .build();
+   *   Policy response = subscriptionAdminClient.getIamPolicy(request);
+   * }
+   * }
+ * + * @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 Policy getIamPolicy(GetIamPolicyRequest request) { + return getIamPolicyCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the access control policy for a resource. Returns an empty policyif the resource exists + * and does not have a policy set. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   GetIamPolicyRequest request =
+   *       GetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setOptions(GetPolicyOptions.newBuilder().build())
+   *           .build();
+   *   ApiFuture future = subscriptionAdminClient.getIamPolicyCallable().futureCall(request);
+   *   // Do something.
+   *   Policy response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable getIamPolicyCallable() { + return stub.getIamPolicyCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Returns permissions that a caller has on the specified resource. If theresource does not exist, + * this will return an empty set ofpermissions, not a `NOT_FOUND` error. + * + *

Note: This operation is designed to be used for buildingpermission-aware UIs and + * command-line tools, not for authorizationchecking. This operation may "fail open" without + * warning. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   TestIamPermissionsRequest request =
+   *       TestIamPermissionsRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .addAllPermissions(new ArrayList())
+   *           .build();
+   *   TestIamPermissionsResponse response = subscriptionAdminClient.testIamPermissions(request);
+   * }
+   * }
+ * + * @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 TestIamPermissionsResponse testIamPermissions(TestIamPermissionsRequest request) { + return testIamPermissionsCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Returns permissions that a caller has on the specified resource. If theresource does not exist, + * this will return an empty set ofpermissions, not a `NOT_FOUND` error. + * + *

Note: This operation is designed to be used for buildingpermission-aware UIs and + * command-line tools, not for authorizationchecking. This operation may "fail open" without + * warning. + * + *

Sample code: + * + *

{@code
+   * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+   *   TestIamPermissionsRequest request =
+   *       TestIamPermissionsRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .addAllPermissions(new ArrayList())
+   *           .build();
+   *   ApiFuture future =
+   *       subscriptionAdminClient.testIamPermissionsCallable().futureCall(request);
+   *   // Do something.
+   *   TestIamPermissionsResponse response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable + testIamPermissionsCallable() { + return stub.testIamPermissionsCallable(); + } + + @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 ListSubscriptionsPagedResponse + extends AbstractPagedListResponse< + ListSubscriptionsRequest, + ListSubscriptionsResponse, + Subscription, + ListSubscriptionsPage, + ListSubscriptionsFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListSubscriptionsPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListSubscriptionsPagedResponse apply(ListSubscriptionsPage input) { + return new ListSubscriptionsPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListSubscriptionsPagedResponse(ListSubscriptionsPage page) { + super(page, ListSubscriptionsFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListSubscriptionsPage + extends AbstractPage< + ListSubscriptionsRequest, + ListSubscriptionsResponse, + Subscription, + ListSubscriptionsPage> { + + private ListSubscriptionsPage( + PageContext context, + ListSubscriptionsResponse response) { + super(context, response); + } + + private static ListSubscriptionsPage createEmptyPage() { + return new ListSubscriptionsPage(null, null); + } + + @Override + protected ListSubscriptionsPage createPage( + PageContext context, + ListSubscriptionsResponse response) { + return new ListSubscriptionsPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListSubscriptionsFixedSizeCollection + extends AbstractFixedSizeCollection< + ListSubscriptionsRequest, + ListSubscriptionsResponse, + Subscription, + ListSubscriptionsPage, + ListSubscriptionsFixedSizeCollection> { + + private ListSubscriptionsFixedSizeCollection( + List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListSubscriptionsFixedSizeCollection createEmptyCollection() { + return new ListSubscriptionsFixedSizeCollection(null, 0); + } + + @Override + protected ListSubscriptionsFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListSubscriptionsFixedSizeCollection(pages, collectionSize); + } + } + + public static class ListSnapshotsPagedResponse + extends AbstractPagedListResponse< + ListSnapshotsRequest, + ListSnapshotsResponse, + Snapshot, + ListSnapshotsPage, + ListSnapshotsFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListSnapshotsPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListSnapshotsPagedResponse apply(ListSnapshotsPage input) { + return new ListSnapshotsPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListSnapshotsPagedResponse(ListSnapshotsPage page) { + super(page, ListSnapshotsFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListSnapshotsPage + extends AbstractPage< + ListSnapshotsRequest, ListSnapshotsResponse, Snapshot, ListSnapshotsPage> { + + private ListSnapshotsPage( + PageContext context, + ListSnapshotsResponse response) { + super(context, response); + } + + private static ListSnapshotsPage createEmptyPage() { + return new ListSnapshotsPage(null, null); + } + + @Override + protected ListSnapshotsPage createPage( + PageContext context, + ListSnapshotsResponse response) { + return new ListSnapshotsPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListSnapshotsFixedSizeCollection + extends AbstractFixedSizeCollection< + ListSnapshotsRequest, + ListSnapshotsResponse, + Snapshot, + ListSnapshotsPage, + ListSnapshotsFixedSizeCollection> { + + private ListSnapshotsFixedSizeCollection(List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListSnapshotsFixedSizeCollection createEmptyCollection() { + return new ListSnapshotsFixedSizeCollection(null, 0); + } + + @Override + protected ListSnapshotsFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListSnapshotsFixedSizeCollection(pages, collectionSize); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SubscriptionAdminClientTest.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SubscriptionAdminClientTest.java new file mode 100644 index 0000000000..2686f5316f --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SubscriptionAdminClientTest.java @@ -0,0 +1,1720 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSnapshotsPagedResponse; +import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSubscriptionsPagedResponse; + +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.grpc.testing.MockStreamObserver; +import com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.ApiStreamObserver; +import com.google.api.gax.rpc.BidiStreamingCallable; +import com.google.api.gax.rpc.InvalidArgumentException; +import com.google.api.gax.rpc.StatusCode; +import com.google.common.collect.Lists; +import com.google.iam.v1.Binding; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.GetPolicyOptions; +import com.google.iam.v1.Policy; +import com.google.iam.v1.ProjectName; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.ByteString; +import com.google.protobuf.Duration; +import com.google.protobuf.Empty; +import com.google.protobuf.FieldMask; +import com.google.protobuf.Timestamp; +import com.google.pubsub.v1.AcknowledgeRequest; +import com.google.pubsub.v1.CreateSnapshotRequest; +import com.google.pubsub.v1.DeadLetterPolicy; +import com.google.pubsub.v1.DeleteSnapshotRequest; +import com.google.pubsub.v1.DeleteSubscriptionRequest; +import com.google.pubsub.v1.ExpirationPolicy; +import com.google.pubsub.v1.GetSnapshotRequest; +import com.google.pubsub.v1.GetSubscriptionRequest; +import com.google.pubsub.v1.ListSnapshotsRequest; +import com.google.pubsub.v1.ListSnapshotsResponse; +import com.google.pubsub.v1.ListSubscriptionsRequest; +import com.google.pubsub.v1.ListSubscriptionsResponse; +import com.google.pubsub.v1.ModifyAckDeadlineRequest; +import com.google.pubsub.v1.ModifyPushConfigRequest; +import com.google.pubsub.v1.PullRequest; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.PushConfig; +import com.google.pubsub.v1.ReceivedMessage; +import com.google.pubsub.v1.RetryPolicy; +import com.google.pubsub.v1.SeekRequest; +import com.google.pubsub.v1.SeekResponse; +import com.google.pubsub.v1.Snapshot; +import com.google.pubsub.v1.SnapshotName; +import com.google.pubsub.v1.StreamingPullRequest; +import com.google.pubsub.v1.StreamingPullResponse; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.SubscriptionName; +import com.google.pubsub.v1.TopicName; +import com.google.pubsub.v1.UpdateSnapshotRequest; +import com.google.pubsub.v1.UpdateSubscriptionRequest; +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.UUID; +import java.util.concurrent.ExecutionException; +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 SubscriptionAdminClientTest { + private static MockServiceHelper mockServiceHelper; + private static MockSubscriber mockSubscriber; + private SubscriptionAdminClient client; + private static MockIAMPolicy mockIAMPolicy; + private LocalChannelProvider channelProvider; + + @BeforeClass + public static void startStaticServer() { + mockSubscriber = new MockSubscriber(); + mockIAMPolicy = new MockIAMPolicy(); + mockServiceHelper = + new MockServiceHelper( + UUID.randomUUID().toString(), + Arrays.asList(mockSubscriber, mockIAMPolicy)); + mockServiceHelper.start(); + } + + @AfterClass + public static void stopServer() { + mockServiceHelper.stop(); + } + + @Before + public void setUp() throws IOException { + mockServiceHelper.reset(); + channelProvider = mockServiceHelper.createChannelProvider(); + SubscriptionAdminSettings settings = + SubscriptionAdminSettings.newBuilder() + .setTransportChannelProvider(channelProvider) + .setCredentialsProvider(NoCredentialsProvider.create()) + .build(); + client = SubscriptionAdminClient.create(settings); + } + + @After + public void tearDown() throws Exception { + client.close(); + } + + @Test + public void createSubscriptionTest() throws Exception { + Subscription expectedResponse = + Subscription.newBuilder() + .setName(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setPushConfig(PushConfig.newBuilder().build()) + .setAckDeadlineSeconds(2135351438) + .setRetainAckedMessages(true) + .setMessageRetentionDuration(Duration.newBuilder().build()) + .putAllLabels(new HashMap()) + .setEnableMessageOrdering(true) + .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) + .setFilter("filter-1274492040") + .setDeadLetterPolicy(DeadLetterPolicy.newBuilder().build()) + .setRetryPolicy(RetryPolicy.newBuilder().build()) + .setDetached(true) + .build(); + mockSubscriber.addResponse(expectedResponse); + + SubscriptionName name = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + PushConfig pushConfig = PushConfig.newBuilder().build(); + int ackDeadlineSeconds = 2135351438; + + Subscription actualResponse = + client.createSubscription(name, topic, pushConfig, ackDeadlineSeconds); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + Subscription actualRequest = ((Subscription) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertEquals(topic.toString(), actualRequest.getTopic()); + Assert.assertEquals(pushConfig, actualRequest.getPushConfig()); + Assert.assertEquals(ackDeadlineSeconds, actualRequest.getAckDeadlineSeconds()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSubscriptionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SubscriptionName name = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + PushConfig pushConfig = PushConfig.newBuilder().build(); + int ackDeadlineSeconds = 2135351438; + client.createSubscription(name, topic, pushConfig, ackDeadlineSeconds); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSubscriptionTest2() throws Exception { + Subscription expectedResponse = + Subscription.newBuilder() + .setName(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setPushConfig(PushConfig.newBuilder().build()) + .setAckDeadlineSeconds(2135351438) + .setRetainAckedMessages(true) + .setMessageRetentionDuration(Duration.newBuilder().build()) + .putAllLabels(new HashMap()) + .setEnableMessageOrdering(true) + .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) + .setFilter("filter-1274492040") + .setDeadLetterPolicy(DeadLetterPolicy.newBuilder().build()) + .setRetryPolicy(RetryPolicy.newBuilder().build()) + .setDetached(true) + .build(); + mockSubscriber.addResponse(expectedResponse); + + SubscriptionName name = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + String topic = "topic110546223"; + PushConfig pushConfig = PushConfig.newBuilder().build(); + int ackDeadlineSeconds = 2135351438; + + Subscription actualResponse = + client.createSubscription(name, topic, pushConfig, ackDeadlineSeconds); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + Subscription actualRequest = ((Subscription) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertEquals(topic, actualRequest.getTopic()); + Assert.assertEquals(pushConfig, actualRequest.getPushConfig()); + Assert.assertEquals(ackDeadlineSeconds, actualRequest.getAckDeadlineSeconds()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSubscriptionExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SubscriptionName name = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + String topic = "topic110546223"; + PushConfig pushConfig = PushConfig.newBuilder().build(); + int ackDeadlineSeconds = 2135351438; + client.createSubscription(name, topic, pushConfig, ackDeadlineSeconds); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSubscriptionTest3() throws Exception { + Subscription expectedResponse = + Subscription.newBuilder() + .setName(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setPushConfig(PushConfig.newBuilder().build()) + .setAckDeadlineSeconds(2135351438) + .setRetainAckedMessages(true) + .setMessageRetentionDuration(Duration.newBuilder().build()) + .putAllLabels(new HashMap()) + .setEnableMessageOrdering(true) + .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) + .setFilter("filter-1274492040") + .setDeadLetterPolicy(DeadLetterPolicy.newBuilder().build()) + .setRetryPolicy(RetryPolicy.newBuilder().build()) + .setDetached(true) + .build(); + mockSubscriber.addResponse(expectedResponse); + + String name = "name3373707"; + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + PushConfig pushConfig = PushConfig.newBuilder().build(); + int ackDeadlineSeconds = 2135351438; + + Subscription actualResponse = + client.createSubscription(name, topic, pushConfig, ackDeadlineSeconds); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + Subscription actualRequest = ((Subscription) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertEquals(topic.toString(), actualRequest.getTopic()); + Assert.assertEquals(pushConfig, actualRequest.getPushConfig()); + Assert.assertEquals(ackDeadlineSeconds, actualRequest.getAckDeadlineSeconds()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSubscriptionExceptionTest3() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String name = "name3373707"; + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + PushConfig pushConfig = PushConfig.newBuilder().build(); + int ackDeadlineSeconds = 2135351438; + client.createSubscription(name, topic, pushConfig, ackDeadlineSeconds); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSubscriptionTest4() throws Exception { + Subscription expectedResponse = + Subscription.newBuilder() + .setName(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setPushConfig(PushConfig.newBuilder().build()) + .setAckDeadlineSeconds(2135351438) + .setRetainAckedMessages(true) + .setMessageRetentionDuration(Duration.newBuilder().build()) + .putAllLabels(new HashMap()) + .setEnableMessageOrdering(true) + .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) + .setFilter("filter-1274492040") + .setDeadLetterPolicy(DeadLetterPolicy.newBuilder().build()) + .setRetryPolicy(RetryPolicy.newBuilder().build()) + .setDetached(true) + .build(); + mockSubscriber.addResponse(expectedResponse); + + String name = "name3373707"; + String topic = "topic110546223"; + PushConfig pushConfig = PushConfig.newBuilder().build(); + int ackDeadlineSeconds = 2135351438; + + Subscription actualResponse = + client.createSubscription(name, topic, pushConfig, ackDeadlineSeconds); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + Subscription actualRequest = ((Subscription) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertEquals(topic, actualRequest.getTopic()); + Assert.assertEquals(pushConfig, actualRequest.getPushConfig()); + Assert.assertEquals(ackDeadlineSeconds, actualRequest.getAckDeadlineSeconds()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSubscriptionExceptionTest4() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String name = "name3373707"; + String topic = "topic110546223"; + PushConfig pushConfig = PushConfig.newBuilder().build(); + int ackDeadlineSeconds = 2135351438; + client.createSubscription(name, topic, pushConfig, ackDeadlineSeconds); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getSubscriptionTest() throws Exception { + Subscription expectedResponse = + Subscription.newBuilder() + .setName(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setPushConfig(PushConfig.newBuilder().build()) + .setAckDeadlineSeconds(2135351438) + .setRetainAckedMessages(true) + .setMessageRetentionDuration(Duration.newBuilder().build()) + .putAllLabels(new HashMap()) + .setEnableMessageOrdering(true) + .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) + .setFilter("filter-1274492040") + .setDeadLetterPolicy(DeadLetterPolicy.newBuilder().build()) + .setRetryPolicy(RetryPolicy.newBuilder().build()) + .setDetached(true) + .build(); + mockSubscriber.addResponse(expectedResponse); + + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + + Subscription actualResponse = client.getSubscription(subscription); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetSubscriptionRequest actualRequest = ((GetSubscriptionRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription.toString(), actualRequest.getSubscription()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getSubscriptionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + client.getSubscription(subscription); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getSubscriptionTest2() throws Exception { + Subscription expectedResponse = + Subscription.newBuilder() + .setName(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setPushConfig(PushConfig.newBuilder().build()) + .setAckDeadlineSeconds(2135351438) + .setRetainAckedMessages(true) + .setMessageRetentionDuration(Duration.newBuilder().build()) + .putAllLabels(new HashMap()) + .setEnableMessageOrdering(true) + .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) + .setFilter("filter-1274492040") + .setDeadLetterPolicy(DeadLetterPolicy.newBuilder().build()) + .setRetryPolicy(RetryPolicy.newBuilder().build()) + .setDetached(true) + .build(); + mockSubscriber.addResponse(expectedResponse); + + String subscription = "subscription341203229"; + + Subscription actualResponse = client.getSubscription(subscription); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetSubscriptionRequest actualRequest = ((GetSubscriptionRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription, actualRequest.getSubscription()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getSubscriptionExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String subscription = "subscription341203229"; + client.getSubscription(subscription); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateSubscriptionTest() throws Exception { + Subscription expectedResponse = + Subscription.newBuilder() + .setName(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setPushConfig(PushConfig.newBuilder().build()) + .setAckDeadlineSeconds(2135351438) + .setRetainAckedMessages(true) + .setMessageRetentionDuration(Duration.newBuilder().build()) + .putAllLabels(new HashMap()) + .setEnableMessageOrdering(true) + .setExpirationPolicy(ExpirationPolicy.newBuilder().build()) + .setFilter("filter-1274492040") + .setDeadLetterPolicy(DeadLetterPolicy.newBuilder().build()) + .setRetryPolicy(RetryPolicy.newBuilder().build()) + .setDetached(true) + .build(); + mockSubscriber.addResponse(expectedResponse); + + UpdateSubscriptionRequest request = + UpdateSubscriptionRequest.newBuilder() + .setSubscription(Subscription.newBuilder().build()) + .setUpdateMask(FieldMask.newBuilder().build()) + .build(); + + Subscription actualResponse = client.updateSubscription(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateSubscriptionRequest actualRequest = ((UpdateSubscriptionRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getSubscription(), actualRequest.getSubscription()); + Assert.assertEquals(request.getUpdateMask(), actualRequest.getUpdateMask()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateSubscriptionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + UpdateSubscriptionRequest request = + UpdateSubscriptionRequest.newBuilder() + .setSubscription(Subscription.newBuilder().build()) + .setUpdateMask(FieldMask.newBuilder().build()) + .build(); + client.updateSubscription(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSubscriptionsTest() throws Exception { + Subscription responsesElement = Subscription.newBuilder().build(); + ListSubscriptionsResponse expectedResponse = + ListSubscriptionsResponse.newBuilder() + .setNextPageToken("") + .addAllSubscriptions(Arrays.asList(responsesElement)) + .build(); + mockSubscriber.addResponse(expectedResponse); + + ProjectName project = ProjectName.of("[PROJECT]"); + + ListSubscriptionsPagedResponse pagedListResponse = client.listSubscriptions(project); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSubscriptionsList().get(0), resources.get(0)); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSubscriptionsRequest actualRequest = ((ListSubscriptionsRequest) actualRequests.get(0)); + + Assert.assertEquals(project.toString(), actualRequest.getProject()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSubscriptionsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + ProjectName project = ProjectName.of("[PROJECT]"); + client.listSubscriptions(project); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSubscriptionsTest2() throws Exception { + Subscription responsesElement = Subscription.newBuilder().build(); + ListSubscriptionsResponse expectedResponse = + ListSubscriptionsResponse.newBuilder() + .setNextPageToken("") + .addAllSubscriptions(Arrays.asList(responsesElement)) + .build(); + mockSubscriber.addResponse(expectedResponse); + + String project = "project-309310695"; + + ListSubscriptionsPagedResponse pagedListResponse = client.listSubscriptions(project); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSubscriptionsList().get(0), resources.get(0)); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSubscriptionsRequest actualRequest = ((ListSubscriptionsRequest) actualRequests.get(0)); + + Assert.assertEquals(project, actualRequest.getProject()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSubscriptionsExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String project = "project-309310695"; + client.listSubscriptions(project); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteSubscriptionTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + + client.deleteSubscription(subscription); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteSubscriptionRequest actualRequest = ((DeleteSubscriptionRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription.toString(), actualRequest.getSubscription()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteSubscriptionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + client.deleteSubscription(subscription); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteSubscriptionTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + String subscription = "subscription341203229"; + + client.deleteSubscription(subscription); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteSubscriptionRequest actualRequest = ((DeleteSubscriptionRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription, actualRequest.getSubscription()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteSubscriptionExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String subscription = "subscription341203229"; + client.deleteSubscription(subscription); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void modifyAckDeadlineTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + List ackIds = new ArrayList<>(); + int ackDeadlineSeconds = 2135351438; + + client.modifyAckDeadline(subscription, ackIds, ackDeadlineSeconds); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ModifyAckDeadlineRequest actualRequest = ((ModifyAckDeadlineRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription.toString(), actualRequest.getSubscription()); + Assert.assertEquals(ackIds, actualRequest.getAckIdsList()); + Assert.assertEquals(ackDeadlineSeconds, actualRequest.getAckDeadlineSeconds()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void modifyAckDeadlineExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + List ackIds = new ArrayList<>(); + int ackDeadlineSeconds = 2135351438; + client.modifyAckDeadline(subscription, ackIds, ackDeadlineSeconds); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void modifyAckDeadlineTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + String subscription = "subscription341203229"; + List ackIds = new ArrayList<>(); + int ackDeadlineSeconds = 2135351438; + + client.modifyAckDeadline(subscription, ackIds, ackDeadlineSeconds); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ModifyAckDeadlineRequest actualRequest = ((ModifyAckDeadlineRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription, actualRequest.getSubscription()); + Assert.assertEquals(ackIds, actualRequest.getAckIdsList()); + Assert.assertEquals(ackDeadlineSeconds, actualRequest.getAckDeadlineSeconds()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void modifyAckDeadlineExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String subscription = "subscription341203229"; + List ackIds = new ArrayList<>(); + int ackDeadlineSeconds = 2135351438; + client.modifyAckDeadline(subscription, ackIds, ackDeadlineSeconds); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void acknowledgeTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + List ackIds = new ArrayList<>(); + + client.acknowledge(subscription, ackIds); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + AcknowledgeRequest actualRequest = ((AcknowledgeRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription.toString(), actualRequest.getSubscription()); + Assert.assertEquals(ackIds, actualRequest.getAckIdsList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void acknowledgeExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + List ackIds = new ArrayList<>(); + client.acknowledge(subscription, ackIds); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void acknowledgeTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + String subscription = "subscription341203229"; + List ackIds = new ArrayList<>(); + + client.acknowledge(subscription, ackIds); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + AcknowledgeRequest actualRequest = ((AcknowledgeRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription, actualRequest.getSubscription()); + Assert.assertEquals(ackIds, actualRequest.getAckIdsList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void acknowledgeExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String subscription = "subscription341203229"; + List ackIds = new ArrayList<>(); + client.acknowledge(subscription, ackIds); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void pullTest() throws Exception { + PullResponse expectedResponse = + PullResponse.newBuilder().addAllReceivedMessages(new ArrayList()).build(); + mockSubscriber.addResponse(expectedResponse); + + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + boolean returnImmediately = true; + int maxMessages = 496131527; + + PullResponse actualResponse = client.pull(subscription, returnImmediately, maxMessages); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + PullRequest actualRequest = ((PullRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription.toString(), actualRequest.getSubscription()); + Assert.assertEquals(returnImmediately, actualRequest.getReturnImmediately()); + Assert.assertEquals(maxMessages, actualRequest.getMaxMessages()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void pullExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + boolean returnImmediately = true; + int maxMessages = 496131527; + client.pull(subscription, returnImmediately, maxMessages); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void pullTest2() throws Exception { + PullResponse expectedResponse = + PullResponse.newBuilder().addAllReceivedMessages(new ArrayList()).build(); + mockSubscriber.addResponse(expectedResponse); + + String subscription = "subscription341203229"; + boolean returnImmediately = true; + int maxMessages = 496131527; + + PullResponse actualResponse = client.pull(subscription, returnImmediately, maxMessages); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + PullRequest actualRequest = ((PullRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription, actualRequest.getSubscription()); + Assert.assertEquals(returnImmediately, actualRequest.getReturnImmediately()); + Assert.assertEquals(maxMessages, actualRequest.getMaxMessages()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void pullExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String subscription = "subscription341203229"; + boolean returnImmediately = true; + int maxMessages = 496131527; + client.pull(subscription, returnImmediately, maxMessages); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void streamingPullTest() throws Exception { + StreamingPullResponse expectedResponse = + 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()) + .setStreamAckDeadlineSeconds(1875467245) + .setClientId("clientId908408390") + .setMaxOutstandingMessages(-1315266996) + .setMaxOutstandingBytes(-2103098517) + .build(); + + MockStreamObserver responseObserver = new MockStreamObserver<>(); + + BidiStreamingCallable callable = + client.streamingPullCallable(); + ApiStreamObserver requestObserver = + callable.bidiStreamingCall(responseObserver); + + requestObserver.onNext(request); + requestObserver.onCompleted(); + + List actualResponses = responseObserver.future().get(); + Assert.assertEquals(1, actualResponses.size()); + Assert.assertEquals(expectedResponse, actualResponses.get(0)); + } + + @Test + public void streamingPullExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + StreamingPullRequest request = + StreamingPullRequest.newBuilder() + .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .addAllAckIds(new ArrayList()) + .addAllModifyDeadlineSeconds(new ArrayList()) + .addAllModifyDeadlineAckIds(new ArrayList()) + .setStreamAckDeadlineSeconds(1875467245) + .setClientId("clientId908408390") + .setMaxOutstandingMessages(-1315266996) + .setMaxOutstandingBytes(-2103098517) + .build(); + + MockStreamObserver responseObserver = new MockStreamObserver<>(); + + BidiStreamingCallable callable = + client.streamingPullCallable(); + ApiStreamObserver requestObserver = + callable.bidiStreamingCall(responseObserver); + + requestObserver.onNext(request); + + try { + List actualResponses = responseObserver.future().get(); + Assert.fail("No exception thrown"); + } catch (ExecutionException e) { + Assert.assertTrue(e.getCause() instanceof InvalidArgumentException); + InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); + Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); + } + } + + @Test + public void modifyPushConfigTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + PushConfig pushConfig = PushConfig.newBuilder().build(); + + client.modifyPushConfig(subscription, pushConfig); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ModifyPushConfigRequest actualRequest = ((ModifyPushConfigRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription.toString(), actualRequest.getSubscription()); + Assert.assertEquals(pushConfig, actualRequest.getPushConfig()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void modifyPushConfigExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + PushConfig pushConfig = PushConfig.newBuilder().build(); + client.modifyPushConfig(subscription, pushConfig); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void modifyPushConfigTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + String subscription = "subscription341203229"; + PushConfig pushConfig = PushConfig.newBuilder().build(); + + client.modifyPushConfig(subscription, pushConfig); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ModifyPushConfigRequest actualRequest = ((ModifyPushConfigRequest) actualRequests.get(0)); + + Assert.assertEquals(subscription, actualRequest.getSubscription()); + Assert.assertEquals(pushConfig, actualRequest.getPushConfig()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void modifyPushConfigExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String subscription = "subscription341203229"; + PushConfig pushConfig = PushConfig.newBuilder().build(); + client.modifyPushConfig(subscription, pushConfig); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getSnapshotTest() throws Exception { + Snapshot expectedResponse = + Snapshot.newBuilder() + .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setExpireTime(Timestamp.newBuilder().build()) + .putAllLabels(new HashMap()) + .build(); + mockSubscriber.addResponse(expectedResponse); + + SnapshotName snapshot = SnapshotName.of("[PROJECT]", "[SNAPSHOT]"); + + Snapshot actualResponse = client.getSnapshot(snapshot); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetSnapshotRequest actualRequest = ((GetSnapshotRequest) actualRequests.get(0)); + + Assert.assertEquals(snapshot.toString(), actualRequest.getSnapshot()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getSnapshotExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SnapshotName snapshot = SnapshotName.of("[PROJECT]", "[SNAPSHOT]"); + client.getSnapshot(snapshot); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getSnapshotTest2() throws Exception { + Snapshot expectedResponse = + Snapshot.newBuilder() + .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setExpireTime(Timestamp.newBuilder().build()) + .putAllLabels(new HashMap()) + .build(); + mockSubscriber.addResponse(expectedResponse); + + String snapshot = "snapshot284874180"; + + Snapshot actualResponse = client.getSnapshot(snapshot); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetSnapshotRequest actualRequest = ((GetSnapshotRequest) actualRequests.get(0)); + + Assert.assertEquals(snapshot, actualRequest.getSnapshot()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getSnapshotExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String snapshot = "snapshot284874180"; + client.getSnapshot(snapshot); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSnapshotsTest() throws Exception { + Snapshot responsesElement = Snapshot.newBuilder().build(); + ListSnapshotsResponse expectedResponse = + ListSnapshotsResponse.newBuilder() + .setNextPageToken("") + .addAllSnapshots(Arrays.asList(responsesElement)) + .build(); + mockSubscriber.addResponse(expectedResponse); + + ProjectName project = ProjectName.of("[PROJECT]"); + + ListSnapshotsPagedResponse pagedListResponse = client.listSnapshots(project); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSnapshotsList().get(0), resources.get(0)); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSnapshotsRequest actualRequest = ((ListSnapshotsRequest) actualRequests.get(0)); + + Assert.assertEquals(project.toString(), actualRequest.getProject()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSnapshotsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + ProjectName project = ProjectName.of("[PROJECT]"); + client.listSnapshots(project); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listSnapshotsTest2() throws Exception { + Snapshot responsesElement = Snapshot.newBuilder().build(); + ListSnapshotsResponse expectedResponse = + ListSnapshotsResponse.newBuilder() + .setNextPageToken("") + .addAllSnapshots(Arrays.asList(responsesElement)) + .build(); + mockSubscriber.addResponse(expectedResponse); + + String project = "project-309310695"; + + ListSnapshotsPagedResponse pagedListResponse = client.listSnapshots(project); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSnapshotsList().get(0), resources.get(0)); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListSnapshotsRequest actualRequest = ((ListSnapshotsRequest) actualRequests.get(0)); + + Assert.assertEquals(project, actualRequest.getProject()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listSnapshotsExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String project = "project-309310695"; + client.listSnapshots(project); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSnapshotTest() throws Exception { + Snapshot expectedResponse = + Snapshot.newBuilder() + .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setExpireTime(Timestamp.newBuilder().build()) + .putAllLabels(new HashMap()) + .build(); + mockSubscriber.addResponse(expectedResponse); + + SnapshotName name = SnapshotName.of("[PROJECT]", "[SNAPSHOT]"); + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + + Snapshot actualResponse = client.createSnapshot(name, subscription); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSnapshotRequest actualRequest = ((CreateSnapshotRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertEquals(subscription.toString(), actualRequest.getSubscription()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSnapshotExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SnapshotName name = SnapshotName.of("[PROJECT]", "[SNAPSHOT]"); + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + client.createSnapshot(name, subscription); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSnapshotTest2() throws Exception { + Snapshot expectedResponse = + Snapshot.newBuilder() + .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setExpireTime(Timestamp.newBuilder().build()) + .putAllLabels(new HashMap()) + .build(); + mockSubscriber.addResponse(expectedResponse); + + SnapshotName name = SnapshotName.of("[PROJECT]", "[SNAPSHOT]"); + String subscription = "subscription341203229"; + + Snapshot actualResponse = client.createSnapshot(name, subscription); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSnapshotRequest actualRequest = ((CreateSnapshotRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertEquals(subscription, actualRequest.getSubscription()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSnapshotExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SnapshotName name = SnapshotName.of("[PROJECT]", "[SNAPSHOT]"); + String subscription = "subscription341203229"; + client.createSnapshot(name, subscription); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSnapshotTest3() throws Exception { + Snapshot expectedResponse = + Snapshot.newBuilder() + .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setExpireTime(Timestamp.newBuilder().build()) + .putAllLabels(new HashMap()) + .build(); + mockSubscriber.addResponse(expectedResponse); + + String name = "name3373707"; + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + + Snapshot actualResponse = client.createSnapshot(name, subscription); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSnapshotRequest actualRequest = ((CreateSnapshotRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertEquals(subscription.toString(), actualRequest.getSubscription()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSnapshotExceptionTest3() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String name = "name3373707"; + SubscriptionName subscription = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); + client.createSnapshot(name, subscription); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createSnapshotTest4() throws Exception { + Snapshot expectedResponse = + Snapshot.newBuilder() + .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setExpireTime(Timestamp.newBuilder().build()) + .putAllLabels(new HashMap()) + .build(); + mockSubscriber.addResponse(expectedResponse); + + String name = "name3373707"; + String subscription = "subscription341203229"; + + Snapshot actualResponse = client.createSnapshot(name, subscription); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + CreateSnapshotRequest actualRequest = ((CreateSnapshotRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertEquals(subscription, actualRequest.getSubscription()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createSnapshotExceptionTest4() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String name = "name3373707"; + String subscription = "subscription341203229"; + client.createSnapshot(name, subscription); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateSnapshotTest() throws Exception { + Snapshot expectedResponse = + Snapshot.newBuilder() + .setName(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString()) + .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .setExpireTime(Timestamp.newBuilder().build()) + .putAllLabels(new HashMap()) + .build(); + mockSubscriber.addResponse(expectedResponse); + + UpdateSnapshotRequest request = + UpdateSnapshotRequest.newBuilder() + .setSnapshot(Snapshot.newBuilder().build()) + .setUpdateMask(FieldMask.newBuilder().build()) + .build(); + + Snapshot actualResponse = client.updateSnapshot(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateSnapshotRequest actualRequest = ((UpdateSnapshotRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getSnapshot(), actualRequest.getSnapshot()); + Assert.assertEquals(request.getUpdateMask(), actualRequest.getUpdateMask()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateSnapshotExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + UpdateSnapshotRequest request = + UpdateSnapshotRequest.newBuilder() + .setSnapshot(Snapshot.newBuilder().build()) + .setUpdateMask(FieldMask.newBuilder().build()) + .build(); + client.updateSnapshot(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteSnapshotTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + SnapshotName snapshot = SnapshotName.of("[PROJECT]", "[SNAPSHOT]"); + + client.deleteSnapshot(snapshot); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteSnapshotRequest actualRequest = ((DeleteSnapshotRequest) actualRequests.get(0)); + + Assert.assertEquals(snapshot.toString(), actualRequest.getSnapshot()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteSnapshotExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SnapshotName snapshot = SnapshotName.of("[PROJECT]", "[SNAPSHOT]"); + client.deleteSnapshot(snapshot); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteSnapshotTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + String snapshot = "snapshot284874180"; + + client.deleteSnapshot(snapshot); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteSnapshotRequest actualRequest = ((DeleteSnapshotRequest) actualRequests.get(0)); + + Assert.assertEquals(snapshot, actualRequest.getSnapshot()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteSnapshotExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + String snapshot = "snapshot284874180"; + client.deleteSnapshot(snapshot); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void seekTest() throws Exception { + SeekResponse expectedResponse = SeekResponse.newBuilder().build(); + mockSubscriber.addResponse(expectedResponse); + + SeekRequest request = + SeekRequest.newBuilder() + .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .build(); + + SeekResponse actualResponse = client.seek(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockSubscriber.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + SeekRequest actualRequest = ((SeekRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getSubscription(), actualRequest.getSubscription()); + Assert.assertEquals(request.getTime(), actualRequest.getTime()); + Assert.assertEquals(request.getSnapshot(), actualRequest.getSnapshot()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void seekExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockSubscriber.addException(exception); + + try { + SeekRequest request = + SeekRequest.newBuilder() + .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .build(); + client.seek(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void setIamPolicyTest() throws Exception { + Policy expectedResponse = + Policy.newBuilder() + .setVersion(351608024) + .addAllBindings(new ArrayList()) + .setEtag(ByteString.EMPTY) + .build(); + mockIAMPolicy.addResponse(expectedResponse); + + SetIamPolicyRequest request = + SetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setPolicy(Policy.newBuilder().build()) + .build(); + + Policy actualResponse = client.setIamPolicy(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + SetIamPolicyRequest actualRequest = ((SetIamPolicyRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getPolicy(), actualRequest.getPolicy()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void setIamPolicyExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + SetIamPolicyRequest request = + SetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setPolicy(Policy.newBuilder().build()) + .build(); + client.setIamPolicy(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getIamPolicyTest() throws Exception { + Policy expectedResponse = + Policy.newBuilder() + .setVersion(351608024) + .addAllBindings(new ArrayList()) + .setEtag(ByteString.EMPTY) + .build(); + mockIAMPolicy.addResponse(expectedResponse); + + GetIamPolicyRequest request = + GetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setOptions(GetPolicyOptions.newBuilder().build()) + .build(); + + Policy actualResponse = client.getIamPolicy(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetIamPolicyRequest actualRequest = ((GetIamPolicyRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getOptions(), actualRequest.getOptions()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getIamPolicyExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + GetIamPolicyRequest request = + GetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setOptions(GetPolicyOptions.newBuilder().build()) + .build(); + client.getIamPolicy(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void testIamPermissionsTest() throws Exception { + TestIamPermissionsResponse expectedResponse = + TestIamPermissionsResponse.newBuilder().addAllPermissions(new ArrayList()).build(); + mockIAMPolicy.addResponse(expectedResponse); + + TestIamPermissionsRequest request = + TestIamPermissionsRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .addAllPermissions(new ArrayList()) + .build(); + + TestIamPermissionsResponse actualResponse = client.testIamPermissions(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + TestIamPermissionsRequest actualRequest = ((TestIamPermissionsRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getPermissionsList(), actualRequest.getPermissionsList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void testIamPermissionsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + TestIamPermissionsRequest request = + TestIamPermissionsRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .addAllPermissions(new ArrayList()) + .build(); + client.testIamPermissions(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SubscriptionAdminSettings.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SubscriptionAdminSettings.java new file mode 100644 index 0000000000..e41dc3b133 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/SubscriptionAdminSettings.java @@ -0,0 +1,410 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSnapshotsPagedResponse; +import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSubscriptionsPagedResponse; + +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.StreamingCallSettings; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.cloud.pubsub.v1.stub.SubscriberStubSettings; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.AcknowledgeRequest; +import com.google.pubsub.v1.CreateSnapshotRequest; +import com.google.pubsub.v1.DeleteSnapshotRequest; +import com.google.pubsub.v1.DeleteSubscriptionRequest; +import com.google.pubsub.v1.GetSnapshotRequest; +import com.google.pubsub.v1.GetSubscriptionRequest; +import com.google.pubsub.v1.ListSnapshotsRequest; +import com.google.pubsub.v1.ListSnapshotsResponse; +import com.google.pubsub.v1.ListSubscriptionsRequest; +import com.google.pubsub.v1.ListSubscriptionsResponse; +import com.google.pubsub.v1.ModifyAckDeadlineRequest; +import com.google.pubsub.v1.ModifyPushConfigRequest; +import com.google.pubsub.v1.PullRequest; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.SeekRequest; +import com.google.pubsub.v1.SeekResponse; +import com.google.pubsub.v1.Snapshot; +import com.google.pubsub.v1.StreamingPullRequest; +import com.google.pubsub.v1.StreamingPullResponse; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.UpdateSnapshotRequest; +import com.google.pubsub.v1.UpdateSubscriptionRequest; +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 SubscriptionAdminClient}. + * + *

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

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

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

For example, to set the total timeout of createSubscription to 30 seconds: + * + *

{@code
+ * SubscriptionAdminSettings.Builder subscriptionAdminSettingsBuilder =
+ *     SubscriptionAdminSettings.newBuilder();
+ * subscriptionAdminSettingsBuilder
+ *     .createSubscriptionSettings()
+ *     .setRetrySettings(
+ *         subscriptionAdminSettingsBuilder
+ *             .createSubscriptionSettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * SubscriptionAdminSettings subscriptionAdminSettings = subscriptionAdminSettingsBuilder.build();
+ * }
+ */ +@Generated("by gapic-generator-java") +public class SubscriptionAdminSettings extends ClientSettings { + + /** Returns the object with the settings used for calls to createSubscription. */ + public UnaryCallSettings createSubscriptionSettings() { + return ((SubscriberStubSettings) getStubSettings()).createSubscriptionSettings(); + } + + /** Returns the object with the settings used for calls to getSubscription. */ + public UnaryCallSettings getSubscriptionSettings() { + return ((SubscriberStubSettings) getStubSettings()).getSubscriptionSettings(); + } + + /** Returns the object with the settings used for calls to updateSubscription. */ + public UnaryCallSettings updateSubscriptionSettings() { + return ((SubscriberStubSettings) getStubSettings()).updateSubscriptionSettings(); + } + + /** Returns the object with the settings used for calls to listSubscriptions. */ + public PagedCallSettings< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> + listSubscriptionsSettings() { + return ((SubscriberStubSettings) getStubSettings()).listSubscriptionsSettings(); + } + + /** Returns the object with the settings used for calls to deleteSubscription. */ + public UnaryCallSettings deleteSubscriptionSettings() { + return ((SubscriberStubSettings) getStubSettings()).deleteSubscriptionSettings(); + } + + /** Returns the object with the settings used for calls to modifyAckDeadline. */ + public UnaryCallSettings modifyAckDeadlineSettings() { + return ((SubscriberStubSettings) getStubSettings()).modifyAckDeadlineSettings(); + } + + /** Returns the object with the settings used for calls to acknowledge. */ + public UnaryCallSettings acknowledgeSettings() { + return ((SubscriberStubSettings) getStubSettings()).acknowledgeSettings(); + } + + /** Returns the object with the settings used for calls to pull. */ + public UnaryCallSettings pullSettings() { + return ((SubscriberStubSettings) getStubSettings()).pullSettings(); + } + + /** Returns the object with the settings used for calls to streamingPull. */ + public StreamingCallSettings + streamingPullSettings() { + return ((SubscriberStubSettings) getStubSettings()).streamingPullSettings(); + } + + /** Returns the object with the settings used for calls to modifyPushConfig. */ + public UnaryCallSettings modifyPushConfigSettings() { + return ((SubscriberStubSettings) getStubSettings()).modifyPushConfigSettings(); + } + + /** Returns the object with the settings used for calls to getSnapshot. */ + public UnaryCallSettings getSnapshotSettings() { + return ((SubscriberStubSettings) getStubSettings()).getSnapshotSettings(); + } + + /** Returns the object with the settings used for calls to listSnapshots. */ + public PagedCallSettings + listSnapshotsSettings() { + return ((SubscriberStubSettings) getStubSettings()).listSnapshotsSettings(); + } + + /** Returns the object with the settings used for calls to createSnapshot. */ + public UnaryCallSettings createSnapshotSettings() { + return ((SubscriberStubSettings) getStubSettings()).createSnapshotSettings(); + } + + /** Returns the object with the settings used for calls to updateSnapshot. */ + public UnaryCallSettings updateSnapshotSettings() { + return ((SubscriberStubSettings) getStubSettings()).updateSnapshotSettings(); + } + + /** Returns the object with the settings used for calls to deleteSnapshot. */ + public UnaryCallSettings deleteSnapshotSettings() { + return ((SubscriberStubSettings) getStubSettings()).deleteSnapshotSettings(); + } + + /** Returns the object with the settings used for calls to seek. */ + public UnaryCallSettings seekSettings() { + return ((SubscriberStubSettings) getStubSettings()).seekSettings(); + } + + /** Returns the object with the settings used for calls to setIamPolicy. */ + public UnaryCallSettings setIamPolicySettings() { + return ((SubscriberStubSettings) getStubSettings()).setIamPolicySettings(); + } + + /** Returns the object with the settings used for calls to getIamPolicy. */ + public UnaryCallSettings getIamPolicySettings() { + return ((SubscriberStubSettings) getStubSettings()).getIamPolicySettings(); + } + + /** Returns the object with the settings used for calls to testIamPermissions. */ + public UnaryCallSettings + testIamPermissionsSettings() { + return ((SubscriberStubSettings) getStubSettings()).testIamPermissionsSettings(); + } + + public static final SubscriptionAdminSettings create(SubscriberStubSettings stub) + throws IOException { + return new SubscriptionAdminSettings.Builder(stub.toBuilder()).build(); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return SubscriberStubSettings.defaultExecutorProviderBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return SubscriberStubSettings.getDefaultEndpoint(); + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return SubscriberStubSettings.getDefaultServiceScopes(); + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return SubscriberStubSettings.defaultCredentialsProviderBuilder(); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return SubscriberStubSettings.defaultGrpcTransportProviderBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return SubscriberStubSettings.defaultTransportChannelProvider(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return SubscriberStubSettings.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 SubscriptionAdminSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + } + + /** Builder for SubscriptionAdminSettings. */ + public static class Builder extends ClientSettings.Builder { + + protected Builder() throws IOException { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(SubscriberStubSettings.newBuilder(clientContext)); + } + + protected Builder(SubscriptionAdminSettings settings) { + super(settings.getStubSettings().toBuilder()); + } + + protected Builder(SubscriberStubSettings.Builder stubSettings) { + super(stubSettings); + } + + private static Builder createDefault() { + return new Builder(SubscriberStubSettings.newBuilder()); + } + + public SubscriberStubSettings.Builder getStubSettingsBuilder() { + return ((SubscriberStubSettings.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 createSubscription. */ + public UnaryCallSettings.Builder createSubscriptionSettings() { + return getStubSettingsBuilder().createSubscriptionSettings(); + } + + /** Returns the builder for the settings used for calls to getSubscription. */ + public UnaryCallSettings.Builder + getSubscriptionSettings() { + return getStubSettingsBuilder().getSubscriptionSettings(); + } + + /** Returns the builder for the settings used for calls to updateSubscription. */ + public UnaryCallSettings.Builder + updateSubscriptionSettings() { + return getStubSettingsBuilder().updateSubscriptionSettings(); + } + + /** Returns the builder for the settings used for calls to listSubscriptions. */ + public PagedCallSettings.Builder< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> + listSubscriptionsSettings() { + return getStubSettingsBuilder().listSubscriptionsSettings(); + } + + /** Returns the builder for the settings used for calls to deleteSubscription. */ + public UnaryCallSettings.Builder + deleteSubscriptionSettings() { + return getStubSettingsBuilder().deleteSubscriptionSettings(); + } + + /** Returns the builder for the settings used for calls to modifyAckDeadline. */ + public UnaryCallSettings.Builder modifyAckDeadlineSettings() { + return getStubSettingsBuilder().modifyAckDeadlineSettings(); + } + + /** Returns the builder for the settings used for calls to acknowledge. */ + public UnaryCallSettings.Builder acknowledgeSettings() { + return getStubSettingsBuilder().acknowledgeSettings(); + } + + /** Returns the builder for the settings used for calls to pull. */ + public UnaryCallSettings.Builder pullSettings() { + return getStubSettingsBuilder().pullSettings(); + } + + /** Returns the builder for the settings used for calls to streamingPull. */ + public StreamingCallSettings.Builder + streamingPullSettings() { + return getStubSettingsBuilder().streamingPullSettings(); + } + + /** Returns the builder for the settings used for calls to modifyPushConfig. */ + public UnaryCallSettings.Builder modifyPushConfigSettings() { + return getStubSettingsBuilder().modifyPushConfigSettings(); + } + + /** Returns the builder for the settings used for calls to getSnapshot. */ + public UnaryCallSettings.Builder getSnapshotSettings() { + return getStubSettingsBuilder().getSnapshotSettings(); + } + + /** Returns the builder for the settings used for calls to listSnapshots. */ + public PagedCallSettings.Builder< + ListSnapshotsRequest, ListSnapshotsResponse, ListSnapshotsPagedResponse> + listSnapshotsSettings() { + return getStubSettingsBuilder().listSnapshotsSettings(); + } + + /** Returns the builder for the settings used for calls to createSnapshot. */ + public UnaryCallSettings.Builder createSnapshotSettings() { + return getStubSettingsBuilder().createSnapshotSettings(); + } + + /** Returns the builder for the settings used for calls to updateSnapshot. */ + public UnaryCallSettings.Builder updateSnapshotSettings() { + return getStubSettingsBuilder().updateSnapshotSettings(); + } + + /** Returns the builder for the settings used for calls to deleteSnapshot. */ + public UnaryCallSettings.Builder deleteSnapshotSettings() { + return getStubSettingsBuilder().deleteSnapshotSettings(); + } + + /** Returns the builder for the settings used for calls to seek. */ + public UnaryCallSettings.Builder seekSettings() { + return getStubSettingsBuilder().seekSettings(); + } + + /** Returns the builder for the settings used for calls to setIamPolicy. */ + public UnaryCallSettings.Builder setIamPolicySettings() { + return getStubSettingsBuilder().setIamPolicySettings(); + } + + /** Returns the builder for the settings used for calls to getIamPolicy. */ + public UnaryCallSettings.Builder getIamPolicySettings() { + return getStubSettingsBuilder().getIamPolicySettings(); + } + + /** Returns the builder for the settings used for calls to testIamPermissions. */ + public UnaryCallSettings.Builder + testIamPermissionsSettings() { + return getStubSettingsBuilder().testIamPermissionsSettings(); + } + + @Override + public SubscriptionAdminSettings build() throws IOException { + return new SubscriptionAdminSettings(this); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/TopicAdminClient.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/TopicAdminClient.java new file mode 100644 index 0000000000..21cafd6f67 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/TopicAdminClient.java @@ -0,0 +1,1544 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +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.cloud.pubsub.v1.stub.PublisherStub; +import com.google.cloud.pubsub.v1.stub.PublisherStubSettings; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.ProjectName; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.DeleteTopicRequest; +import com.google.pubsub.v1.DetachSubscriptionRequest; +import com.google.pubsub.v1.DetachSubscriptionResponse; +import com.google.pubsub.v1.GetTopicRequest; +import com.google.pubsub.v1.ListTopicSnapshotsRequest; +import com.google.pubsub.v1.ListTopicSnapshotsResponse; +import com.google.pubsub.v1.ListTopicSubscriptionsRequest; +import com.google.pubsub.v1.ListTopicSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ListTopicsResponse; +import com.google.pubsub.v1.PublishRequest; +import com.google.pubsub.v1.PublishResponse; +import com.google.pubsub.v1.PubsubMessage; +import com.google.pubsub.v1.Topic; +import com.google.pubsub.v1.TopicName; +import com.google.pubsub.v1.UpdateTopicRequest; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Service Description: The service that an application uses to manipulate topics, and to send + * messages to a topic. + * + *

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

{@code
+ * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ *   TopicName name = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+ *   Topic response = topicAdminClient.createTopic(name);
+ * }
+ * }
+ * + *

Note: close() needs to be called on the TopicAdminClient 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 TopicAdminSettings to + * create(). For example: + * + *

To customize credentials: + * + *

{@code
+ * TopicAdminSettings topicAdminSettings =
+ *     TopicAdminSettings.newBuilder()
+ *         .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
+ *         .build();
+ * TopicAdminClient topicAdminClient = TopicAdminClient.create(topicAdminSettings);
+ * }
+ * + *

To customize the endpoint: + * + *

{@code
+ * TopicAdminSettings topicAdminSettings =
+ *     TopicAdminSettings.newBuilder().setEndpoint(myEndpoint).build();
+ * TopicAdminClient topicAdminClient = TopicAdminClient.create(topicAdminSettings);
+ * }
+ * + *

Please refer to the GitHub repository's samples for more quickstart code snippets. + */ +@Generated("by gapic-generator-java") +public class TopicAdminClient implements BackgroundResource { + private final TopicAdminSettings settings; + private final PublisherStub stub; + + /** Constructs an instance of TopicAdminClient with default settings. */ + public static final TopicAdminClient create() throws IOException { + return create(TopicAdminSettings.newBuilder().build()); + } + + /** + * Constructs an instance of TopicAdminClient, 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 TopicAdminClient create(TopicAdminSettings settings) throws IOException { + return new TopicAdminClient(settings); + } + + /** + * Constructs an instance of TopicAdminClient, using the given stub for making calls. This is for + * advanced usage - prefer using create(TopicAdminSettings). + */ + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public static final TopicAdminClient create(PublisherStub stub) { + return new TopicAdminClient(stub); + } + + /** + * Constructs an instance of TopicAdminClient, 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 TopicAdminClient(TopicAdminSettings settings) throws IOException { + this.settings = settings; + this.stub = ((PublisherStubSettings) settings.getStubSettings()).createStub(); + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + protected TopicAdminClient(PublisherStub stub) { + this.settings = null; + this.stub = stub; + } + + public final TopicAdminSettings getSettings() { + return settings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public PublisherStub getStub() { + return stub; + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates the given topic with the given name. See the [resource name rules] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   TopicName name = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+   *   Topic response = topicAdminClient.createTopic(name);
+   * }
+   * }
+ * + * @param name Required. The name of the topic. It must have the format + * `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, and contain only + * letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), + * tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in + * length, and it must not start with `"goog"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Topic createTopic(TopicName name) { + Topic request = Topic.newBuilder().setName(name == null ? null : name.toString()).build(); + return createTopic(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates the given topic with the given name. See the [resource name rules] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   String name = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString();
+   *   Topic response = topicAdminClient.createTopic(name);
+   * }
+   * }
+ * + * @param name Required. The name of the topic. It must have the format + * `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, and contain only + * letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), + * tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in + * length, and it must not start with `"goog"`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Topic createTopic(String name) { + Topic request = Topic.newBuilder().setName(name).build(); + return createTopic(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates the given topic with the given name. See the [resource name rules] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   Topic request =
+   *       Topic.newBuilder()
+   *           .setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .putAllLabels(new HashMap())
+   *           .setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build())
+   *           .setKmsKeyName("kmsKeyName412586233")
+   *           .setSchemaSettings(SchemaSettings.newBuilder().build())
+   *           .setSatisfiesPzs(true)
+   *           .build();
+   *   Topic response = topicAdminClient.createTopic(request);
+   * }
+   * }
+ * + * @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 Topic createTopic(Topic request) { + return createTopicCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Creates the given topic with the given name. See the [resource name rules] + * (https://cloud.google.com/pubsub/docs/admin#resource_names). + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   Topic request =
+   *       Topic.newBuilder()
+   *           .setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .putAllLabels(new HashMap())
+   *           .setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build())
+   *           .setKmsKeyName("kmsKeyName412586233")
+   *           .setSchemaSettings(SchemaSettings.newBuilder().build())
+   *           .setSatisfiesPzs(true)
+   *           .build();
+   *   ApiFuture future = topicAdminClient.createTopicCallable().futureCall(request);
+   *   // Do something.
+   *   Topic response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable createTopicCallable() { + return stub.createTopicCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates an existing topic. Note that certain properties of a topic are not modifiable. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   UpdateTopicRequest request =
+   *       UpdateTopicRequest.newBuilder()
+   *           .setTopic(Topic.newBuilder().build())
+   *           .setUpdateMask(FieldMask.newBuilder().build())
+   *           .build();
+   *   Topic response = topicAdminClient.updateTopic(request);
+   * }
+   * }
+ * + * @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 Topic updateTopic(UpdateTopicRequest request) { + return updateTopicCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Updates an existing topic. Note that certain properties of a topic are not modifiable. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   UpdateTopicRequest request =
+   *       UpdateTopicRequest.newBuilder()
+   *           .setTopic(Topic.newBuilder().build())
+   *           .setUpdateMask(FieldMask.newBuilder().build())
+   *           .build();
+   *   ApiFuture future = topicAdminClient.updateTopicCallable().futureCall(request);
+   *   // Do something.
+   *   Topic response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable updateTopicCallable() { + return stub.updateTopicCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+   *   List messages = new ArrayList<>();
+   *   PublishResponse response = topicAdminClient.publish(topic, messages);
+   * }
+   * }
+ * + * @param topic Required. The messages in the request will be published on this topic. Format is + * `projects/{project}/topics/{topic}`. + * @param messages Required. The messages to publish. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final PublishResponse publish(TopicName topic, List messages) { + PublishRequest request = + PublishRequest.newBuilder() + .setTopic(topic == null ? null : topic.toString()) + .addAllMessages(messages) + .build(); + return publish(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   String topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString();
+   *   List messages = new ArrayList<>();
+   *   PublishResponse response = topicAdminClient.publish(topic, messages);
+   * }
+   * }
+ * + * @param topic Required. The messages in the request will be published on this topic. Format is + * `projects/{project}/topics/{topic}`. + * @param messages Required. The messages to publish. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final PublishResponse publish(String topic, List messages) { + PublishRequest request = + PublishRequest.newBuilder().setTopic(topic).addAllMessages(messages).build(); + return publish(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   PublishRequest request =
+   *       PublishRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .addAllMessages(new ArrayList())
+   *           .build();
+   *   PublishResponse response = topicAdminClient.publish(request);
+   * }
+   * }
+ * + * @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 PublishResponse publish(PublishRequest request) { + return publishCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   PublishRequest request =
+   *       PublishRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .addAllMessages(new ArrayList())
+   *           .build();
+   *   ApiFuture future = topicAdminClient.publishCallable().futureCall(request);
+   *   // Do something.
+   *   PublishResponse response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable publishCallable() { + return stub.publishCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration of a topic. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+   *   Topic response = topicAdminClient.getTopic(topic);
+   * }
+   * }
+ * + * @param topic Required. The name of the topic to get. Format is + * `projects/{project}/topics/{topic}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Topic getTopic(TopicName topic) { + GetTopicRequest request = + GetTopicRequest.newBuilder().setTopic(topic == null ? null : topic.toString()).build(); + return getTopic(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration of a topic. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   String topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString();
+   *   Topic response = topicAdminClient.getTopic(topic);
+   * }
+   * }
+ * + * @param topic Required. The name of the topic to get. Format is + * `projects/{project}/topics/{topic}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Topic getTopic(String topic) { + GetTopicRequest request = GetTopicRequest.newBuilder().setTopic(topic).build(); + return getTopic(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration of a topic. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   GetTopicRequest request =
+   *       GetTopicRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .build();
+   *   Topic response = topicAdminClient.getTopic(request);
+   * }
+   * }
+ * + * @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 Topic getTopic(GetTopicRequest request) { + return getTopicCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the configuration of a topic. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   GetTopicRequest request =
+   *       GetTopicRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .build();
+   *   ApiFuture future = topicAdminClient.getTopicCallable().futureCall(request);
+   *   // Do something.
+   *   Topic response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable getTopicCallable() { + return stub.getTopicCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists matching topics. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   ProjectName project = ProjectName.of("[PROJECT]");
+   *   for (Topic element : topicAdminClient.listTopics(project).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param project Required. The name of the project in which to list topics. Format is + * `projects/{project-id}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListTopicsPagedResponse listTopics(ProjectName project) { + ListTopicsRequest request = + ListTopicsRequest.newBuilder() + .setProject(project == null ? null : project.toString()) + .build(); + return listTopics(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists matching topics. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   String project = ProjectName.of("[PROJECT]").toString();
+   *   for (Topic element : topicAdminClient.listTopics(project).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param project Required. The name of the project in which to list topics. Format is + * `projects/{project-id}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListTopicsPagedResponse listTopics(String project) { + ListTopicsRequest request = ListTopicsRequest.newBuilder().setProject(project).build(); + return listTopics(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists matching topics. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   ListTopicsRequest request =
+   *       ListTopicsRequest.newBuilder()
+   *           .setProject(ProjectName.of("[PROJECT]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   for (Topic element : topicAdminClient.listTopics(request).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @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 ListTopicsPagedResponse listTopics(ListTopicsRequest request) { + return listTopicsPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists matching topics. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   ListTopicsRequest request =
+   *       ListTopicsRequest.newBuilder()
+   *           .setProject(ProjectName.of("[PROJECT]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   ApiFuture future = topicAdminClient.listTopicsPagedCallable().futureCall(request);
+   *   // Do something.
+   *   for (Topic element : future.get().iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable listTopicsPagedCallable() { + return stub.listTopicsPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists matching topics. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   ListTopicsRequest request =
+   *       ListTopicsRequest.newBuilder()
+   *           .setProject(ProjectName.of("[PROJECT]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   while (true) {
+   *     ListTopicsResponse response = topicAdminClient.listTopicsCallable().call(request);
+   *     for (Topic element : response.getResponsesList()) {
+   *       // doThingsWith(element);
+   *     }
+   *     String nextPageToken = response.getNextPageToken();
+   *     if (!Strings.isNullOrEmpty(nextPageToken)) {
+   *       request = request.toBuilder().setPageToken(nextPageToken).build();
+   *     } else {
+   *       break;
+   *     }
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable listTopicsCallable() { + return stub.listTopicsCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the names of the attached subscriptions on this topic. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+   *   for (String element : topicAdminClient.listTopicSubscriptions(topic).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param topic Required. The name of the topic that subscriptions are attached to. Format is + * `projects/{project}/topics/{topic}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListTopicSubscriptionsPagedResponse listTopicSubscriptions(TopicName topic) { + ListTopicSubscriptionsRequest request = + ListTopicSubscriptionsRequest.newBuilder() + .setTopic(topic == null ? null : topic.toString()) + .build(); + return listTopicSubscriptions(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the names of the attached subscriptions on this topic. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   String topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString();
+   *   for (String element : topicAdminClient.listTopicSubscriptions(topic).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param topic Required. The name of the topic that subscriptions are attached to. Format is + * `projects/{project}/topics/{topic}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListTopicSubscriptionsPagedResponse listTopicSubscriptions(String topic) { + ListTopicSubscriptionsRequest request = + ListTopicSubscriptionsRequest.newBuilder().setTopic(topic).build(); + return listTopicSubscriptions(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the names of the attached subscriptions on this topic. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   ListTopicSubscriptionsRequest request =
+   *       ListTopicSubscriptionsRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   for (String element : topicAdminClient.listTopicSubscriptions(request).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @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 ListTopicSubscriptionsPagedResponse listTopicSubscriptions( + ListTopicSubscriptionsRequest request) { + return listTopicSubscriptionsPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the names of the attached subscriptions on this topic. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   ListTopicSubscriptionsRequest request =
+   *       ListTopicSubscriptionsRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   ApiFuture future =
+   *       topicAdminClient.listTopicSubscriptionsPagedCallable().futureCall(request);
+   *   // Do something.
+   *   for (String element : future.get().iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable + listTopicSubscriptionsPagedCallable() { + return stub.listTopicSubscriptionsPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the names of the attached subscriptions on this topic. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   ListTopicSubscriptionsRequest request =
+   *       ListTopicSubscriptionsRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   while (true) {
+   *     ListTopicSubscriptionsResponse response =
+   *         topicAdminClient.listTopicSubscriptionsCallable().call(request);
+   *     for (String element : response.getResponsesList()) {
+   *       // doThingsWith(element);
+   *     }
+   *     String nextPageToken = response.getNextPageToken();
+   *     if (!Strings.isNullOrEmpty(nextPageToken)) {
+   *       request = request.toBuilder().setPageToken(nextPageToken).build();
+   *     } else {
+   *       break;
+   *     }
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable + listTopicSubscriptionsCallable() { + return stub.listTopicSubscriptionsCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the names of the snapshots on this topic. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+   *   for (String element : topicAdminClient.listTopicSnapshots(topic).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param topic Required. The name of the topic that snapshots are attached to. Format is + * `projects/{project}/topics/{topic}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListTopicSnapshotsPagedResponse listTopicSnapshots(TopicName topic) { + ListTopicSnapshotsRequest request = + ListTopicSnapshotsRequest.newBuilder() + .setTopic(topic == null ? null : topic.toString()) + .build(); + return listTopicSnapshots(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the names of the snapshots on this topic. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   String topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString();
+   *   for (String element : topicAdminClient.listTopicSnapshots(topic).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @param topic Required. The name of the topic that snapshots are attached to. Format is + * `projects/{project}/topics/{topic}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final ListTopicSnapshotsPagedResponse listTopicSnapshots(String topic) { + ListTopicSnapshotsRequest request = + ListTopicSnapshotsRequest.newBuilder().setTopic(topic).build(); + return listTopicSnapshots(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the names of the snapshots on this topic. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   ListTopicSnapshotsRequest request =
+   *       ListTopicSnapshotsRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   for (String element : topicAdminClient.listTopicSnapshots(request).iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ * + * @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 ListTopicSnapshotsPagedResponse listTopicSnapshots( + ListTopicSnapshotsRequest request) { + return listTopicSnapshotsPagedCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the names of the snapshots on this topic. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   ListTopicSnapshotsRequest request =
+   *       ListTopicSnapshotsRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   ApiFuture future =
+   *       topicAdminClient.listTopicSnapshotsPagedCallable().futureCall(request);
+   *   // Do something.
+   *   for (String element : future.get().iterateAll()) {
+   *     // doThingsWith(element);
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable + listTopicSnapshotsPagedCallable() { + return stub.listTopicSnapshotsPagedCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Lists the names of the snapshots on this topic. Snapshots are used in + * [Seek](https://cloud.google.com/pubsub/docs/replay-overview) operations, which allow you to + * manage message acknowledgments in bulk. That is, you can set the acknowledgment state of + * messages in an existing subscription to the state captured by a snapshot. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   ListTopicSnapshotsRequest request =
+   *       ListTopicSnapshotsRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .setPageSize(883849137)
+   *           .setPageToken("pageToken873572522")
+   *           .build();
+   *   while (true) {
+   *     ListTopicSnapshotsResponse response =
+   *         topicAdminClient.listTopicSnapshotsCallable().call(request);
+   *     for (String element : response.getResponsesList()) {
+   *       // doThingsWith(element);
+   *     }
+   *     String nextPageToken = response.getNextPageToken();
+   *     if (!Strings.isNullOrEmpty(nextPageToken)) {
+   *       request = request.toBuilder().setPageToken(nextPageToken).build();
+   *     } else {
+   *       break;
+   *     }
+   *   }
+   * }
+   * }
+ */ + public final UnaryCallable + listTopicSnapshotsCallable() { + return stub.listTopicSnapshotsCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a + * topic is deleted, a new topic may be created with the same name; this is an entirely new topic + * with none of the old configuration or subscriptions. Existing subscriptions to this topic are + * not deleted, but their `topic` field is set to `_deleted-topic_`. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+   *   topicAdminClient.deleteTopic(topic);
+   * }
+   * }
+ * + * @param topic Required. Name of the topic to delete. Format is + * `projects/{project}/topics/{topic}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void deleteTopic(TopicName topic) { + DeleteTopicRequest request = + DeleteTopicRequest.newBuilder().setTopic(topic == null ? null : topic.toString()).build(); + deleteTopic(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a + * topic is deleted, a new topic may be created with the same name; this is an entirely new topic + * with none of the old configuration or subscriptions. Existing subscriptions to this topic are + * not deleted, but their `topic` field is set to `_deleted-topic_`. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   String topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString();
+   *   topicAdminClient.deleteTopic(topic);
+   * }
+   * }
+ * + * @param topic Required. Name of the topic to delete. Format is + * `projects/{project}/topics/{topic}`. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final void deleteTopic(String topic) { + DeleteTopicRequest request = DeleteTopicRequest.newBuilder().setTopic(topic).build(); + deleteTopic(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a + * topic is deleted, a new topic may be created with the same name; this is an entirely new topic + * with none of the old configuration or subscriptions. Existing subscriptions to this topic are + * not deleted, but their `topic` field is set to `_deleted-topic_`. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   DeleteTopicRequest request =
+   *       DeleteTopicRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .build();
+   *   topicAdminClient.deleteTopic(request);
+   * }
+   * }
+ * + * @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 void deleteTopic(DeleteTopicRequest request) { + deleteTopicCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a + * topic is deleted, a new topic may be created with the same name; this is an entirely new topic + * with none of the old configuration or subscriptions. Existing subscriptions to this topic are + * not deleted, but their `topic` field is set to `_deleted-topic_`. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   DeleteTopicRequest request =
+   *       DeleteTopicRequest.newBuilder()
+   *           .setTopic(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
+   *           .build();
+   *   ApiFuture future = topicAdminClient.deleteTopicCallable().futureCall(request);
+   *   // Do something.
+   *   future.get();
+   * }
+   * }
+ */ + public final UnaryCallable deleteTopicCallable() { + return stub.deleteTopicCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Detaches a subscription from this topic. All messages retained in the subscription are dropped. + * Subsequent `Pull` and `StreamingPull` requests will return FAILED_PRECONDITION. If the + * subscription is a push subscription, pushes to the endpoint will stop. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   DetachSubscriptionRequest request =
+   *       DetachSubscriptionRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .build();
+   *   DetachSubscriptionResponse response = topicAdminClient.detachSubscription(request);
+   * }
+   * }
+ * + * @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 DetachSubscriptionResponse detachSubscription(DetachSubscriptionRequest request) { + return detachSubscriptionCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Detaches a subscription from this topic. All messages retained in the subscription are dropped. + * Subsequent `Pull` and `StreamingPull` requests will return FAILED_PRECONDITION. If the + * subscription is a push subscription, pushes to the endpoint will stop. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   DetachSubscriptionRequest request =
+   *       DetachSubscriptionRequest.newBuilder()
+   *           .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
+   *           .build();
+   *   ApiFuture future =
+   *       topicAdminClient.detachSubscriptionCallable().futureCall(request);
+   *   // Do something.
+   *   DetachSubscriptionResponse response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable + detachSubscriptionCallable() { + return stub.detachSubscriptionCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sets the access control policy on the specified resource. Replacesany existing policy. + * + *

Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   SetIamPolicyRequest request =
+   *       SetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setPolicy(Policy.newBuilder().build())
+   *           .build();
+   *   Policy response = topicAdminClient.setIamPolicy(request);
+   * }
+   * }
+ * + * @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 Policy setIamPolicy(SetIamPolicyRequest request) { + return setIamPolicyCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sets the access control policy on the specified resource. Replacesany existing policy. + * + *

Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   SetIamPolicyRequest request =
+   *       SetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setPolicy(Policy.newBuilder().build())
+   *           .build();
+   *   ApiFuture future = topicAdminClient.setIamPolicyCallable().futureCall(request);
+   *   // Do something.
+   *   Policy response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable setIamPolicyCallable() { + return stub.setIamPolicyCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the access control policy for a resource. Returns an empty policyif the resource exists + * and does not have a policy set. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   GetIamPolicyRequest request =
+   *       GetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setOptions(GetPolicyOptions.newBuilder().build())
+   *           .build();
+   *   Policy response = topicAdminClient.getIamPolicy(request);
+   * }
+   * }
+ * + * @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 Policy getIamPolicy(GetIamPolicyRequest request) { + return getIamPolicyCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the access control policy for a resource. Returns an empty policyif the resource exists + * and does not have a policy set. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   GetIamPolicyRequest request =
+   *       GetIamPolicyRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .setOptions(GetPolicyOptions.newBuilder().build())
+   *           .build();
+   *   ApiFuture future = topicAdminClient.getIamPolicyCallable().futureCall(request);
+   *   // Do something.
+   *   Policy response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable getIamPolicyCallable() { + return stub.getIamPolicyCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Returns permissions that a caller has on the specified resource. If theresource does not exist, + * this will return an empty set ofpermissions, not a `NOT_FOUND` error. + * + *

Note: This operation is designed to be used for buildingpermission-aware UIs and + * command-line tools, not for authorizationchecking. This operation may "fail open" without + * warning. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   TestIamPermissionsRequest request =
+   *       TestIamPermissionsRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .addAllPermissions(new ArrayList())
+   *           .build();
+   *   TestIamPermissionsResponse response = topicAdminClient.testIamPermissions(request);
+   * }
+   * }
+ * + * @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 TestIamPermissionsResponse testIamPermissions(TestIamPermissionsRequest request) { + return testIamPermissionsCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Returns permissions that a caller has on the specified resource. If theresource does not exist, + * this will return an empty set ofpermissions, not a `NOT_FOUND` error. + * + *

Note: This operation is designed to be used for buildingpermission-aware UIs and + * command-line tools, not for authorizationchecking. This operation may "fail open" without + * warning. + * + *

Sample code: + * + *

{@code
+   * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+   *   TestIamPermissionsRequest request =
+   *       TestIamPermissionsRequest.newBuilder()
+   *           .setResource(ProjectName.of("[PROJECT]").toString())
+   *           .addAllPermissions(new ArrayList())
+   *           .build();
+   *   ApiFuture future =
+   *       topicAdminClient.testIamPermissionsCallable().futureCall(request);
+   *   // Do something.
+   *   TestIamPermissionsResponse response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable + testIamPermissionsCallable() { + return stub.testIamPermissionsCallable(); + } + + @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 ListTopicsPagedResponse + extends AbstractPagedListResponse< + ListTopicsRequest, + ListTopicsResponse, + Topic, + ListTopicsPage, + ListTopicsFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListTopicsPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListTopicsPagedResponse apply(ListTopicsPage input) { + return new ListTopicsPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListTopicsPagedResponse(ListTopicsPage page) { + super(page, ListTopicsFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListTopicsPage + extends AbstractPage { + + private ListTopicsPage( + PageContext context, + ListTopicsResponse response) { + super(context, response); + } + + private static ListTopicsPage createEmptyPage() { + return new ListTopicsPage(null, null); + } + + @Override + protected ListTopicsPage createPage( + PageContext context, + ListTopicsResponse response) { + return new ListTopicsPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListTopicsFixedSizeCollection + extends AbstractFixedSizeCollection< + ListTopicsRequest, + ListTopicsResponse, + Topic, + ListTopicsPage, + ListTopicsFixedSizeCollection> { + + private ListTopicsFixedSizeCollection(List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListTopicsFixedSizeCollection createEmptyCollection() { + return new ListTopicsFixedSizeCollection(null, 0); + } + + @Override + protected ListTopicsFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListTopicsFixedSizeCollection(pages, collectionSize); + } + } + + public static class ListTopicSubscriptionsPagedResponse + extends AbstractPagedListResponse< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + String, + ListTopicSubscriptionsPage, + ListTopicSubscriptionsFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListTopicSubscriptionsPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListTopicSubscriptionsPagedResponse apply(ListTopicSubscriptionsPage input) { + return new ListTopicSubscriptionsPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListTopicSubscriptionsPagedResponse(ListTopicSubscriptionsPage page) { + super(page, ListTopicSubscriptionsFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListTopicSubscriptionsPage + extends AbstractPage< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + String, + ListTopicSubscriptionsPage> { + + private ListTopicSubscriptionsPage( + PageContext context, + ListTopicSubscriptionsResponse response) { + super(context, response); + } + + private static ListTopicSubscriptionsPage createEmptyPage() { + return new ListTopicSubscriptionsPage(null, null); + } + + @Override + protected ListTopicSubscriptionsPage createPage( + PageContext context, + ListTopicSubscriptionsResponse response) { + return new ListTopicSubscriptionsPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListTopicSubscriptionsFixedSizeCollection + extends AbstractFixedSizeCollection< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + String, + ListTopicSubscriptionsPage, + ListTopicSubscriptionsFixedSizeCollection> { + + private ListTopicSubscriptionsFixedSizeCollection( + List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListTopicSubscriptionsFixedSizeCollection createEmptyCollection() { + return new ListTopicSubscriptionsFixedSizeCollection(null, 0); + } + + @Override + protected ListTopicSubscriptionsFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListTopicSubscriptionsFixedSizeCollection(pages, collectionSize); + } + } + + public static class ListTopicSnapshotsPagedResponse + extends AbstractPagedListResponse< + ListTopicSnapshotsRequest, + ListTopicSnapshotsResponse, + String, + ListTopicSnapshotsPage, + ListTopicSnapshotsFixedSizeCollection> { + + public static ApiFuture createAsync( + PageContext context, + ApiFuture futureResponse) { + ApiFuture futurePage = + ListTopicSnapshotsPage.createEmptyPage().createPageAsync(context, futureResponse); + return ApiFutures.transform( + futurePage, + new ApiFunction() { + @Override + public ListTopicSnapshotsPagedResponse apply(ListTopicSnapshotsPage input) { + return new ListTopicSnapshotsPagedResponse(input); + } + }, + MoreExecutors.directExecutor()); + } + + private ListTopicSnapshotsPagedResponse(ListTopicSnapshotsPage page) { + super(page, ListTopicSnapshotsFixedSizeCollection.createEmptyCollection()); + } + } + + public static class ListTopicSnapshotsPage + extends AbstractPage< + ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, String, ListTopicSnapshotsPage> { + + private ListTopicSnapshotsPage( + PageContext context, + ListTopicSnapshotsResponse response) { + super(context, response); + } + + private static ListTopicSnapshotsPage createEmptyPage() { + return new ListTopicSnapshotsPage(null, null); + } + + @Override + protected ListTopicSnapshotsPage createPage( + PageContext context, + ListTopicSnapshotsResponse response) { + return new ListTopicSnapshotsPage(context, response); + } + + @Override + public ApiFuture createPageAsync( + PageContext context, + ApiFuture futureResponse) { + return super.createPageAsync(context, futureResponse); + } + } + + public static class ListTopicSnapshotsFixedSizeCollection + extends AbstractFixedSizeCollection< + ListTopicSnapshotsRequest, + ListTopicSnapshotsResponse, + String, + ListTopicSnapshotsPage, + ListTopicSnapshotsFixedSizeCollection> { + + private ListTopicSnapshotsFixedSizeCollection( + List pages, int collectionSize) { + super(pages, collectionSize); + } + + private static ListTopicSnapshotsFixedSizeCollection createEmptyCollection() { + return new ListTopicSnapshotsFixedSizeCollection(null, 0); + } + + @Override + protected ListTopicSnapshotsFixedSizeCollection createCollection( + List pages, int collectionSize) { + return new ListTopicSnapshotsFixedSizeCollection(pages, collectionSize); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/TopicAdminClientTest.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/TopicAdminClientTest.java new file mode 100644 index 0000000000..94b7162fba --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/TopicAdminClientTest.java @@ -0,0 +1,937 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSnapshotsPagedResponse; +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSubscriptionsPagedResponse; +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicsPagedResponse; + +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.iam.v1.Binding; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.GetPolicyOptions; +import com.google.iam.v1.Policy; +import com.google.iam.v1.ProjectName; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.AbstractMessage; +import com.google.protobuf.ByteString; +import com.google.protobuf.Empty; +import com.google.protobuf.FieldMask; +import com.google.pubsub.v1.DeleteTopicRequest; +import com.google.pubsub.v1.DetachSubscriptionRequest; +import com.google.pubsub.v1.DetachSubscriptionResponse; +import com.google.pubsub.v1.GetTopicRequest; +import com.google.pubsub.v1.ListTopicSnapshotsRequest; +import com.google.pubsub.v1.ListTopicSnapshotsResponse; +import com.google.pubsub.v1.ListTopicSubscriptionsRequest; +import com.google.pubsub.v1.ListTopicSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ListTopicsResponse; +import com.google.pubsub.v1.MessageStoragePolicy; +import com.google.pubsub.v1.PublishRequest; +import com.google.pubsub.v1.PublishResponse; +import com.google.pubsub.v1.PubsubMessage; +import com.google.pubsub.v1.SchemaSettings; +import com.google.pubsub.v1.SubscriptionName; +import com.google.pubsub.v1.Topic; +import com.google.pubsub.v1.TopicName; +import com.google.pubsub.v1.UpdateTopicRequest; +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.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 TopicAdminClientTest { + private static MockServiceHelper mockServiceHelper; + private static MockPublisher mockPublisher; + private TopicAdminClient client; + private static MockIAMPolicy mockIAMPolicy; + private LocalChannelProvider channelProvider; + + @BeforeClass + public static void startStaticServer() { + mockPublisher = new MockPublisher(); + mockIAMPolicy = new MockIAMPolicy(); + mockServiceHelper = + new MockServiceHelper( + UUID.randomUUID().toString(), + Arrays.asList(mockPublisher, mockIAMPolicy)); + mockServiceHelper.start(); + } + + @AfterClass + public static void stopServer() { + mockServiceHelper.stop(); + } + + @Before + public void setUp() throws IOException { + mockServiceHelper.reset(); + channelProvider = mockServiceHelper.createChannelProvider(); + TopicAdminSettings settings = + TopicAdminSettings.newBuilder() + .setTransportChannelProvider(channelProvider) + .setCredentialsProvider(NoCredentialsProvider.create()) + .build(); + client = TopicAdminClient.create(settings); + } + + @After + public void tearDown() throws Exception { + client.close(); + } + + @Test + public void createTopicTest() throws Exception { + Topic expectedResponse = + Topic.newBuilder() + .setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .putAllLabels(new HashMap()) + .setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build()) + .setKmsKeyName("kmsKeyName412586233") + .setSchemaSettings(SchemaSettings.newBuilder().build()) + .setSatisfiesPzs(true) + .build(); + mockPublisher.addResponse(expectedResponse); + + TopicName name = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + + Topic actualResponse = client.createTopic(name); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + Topic actualRequest = ((Topic) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createTopicExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + TopicName name = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + client.createTopic(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void createTopicTest2() throws Exception { + Topic expectedResponse = + Topic.newBuilder() + .setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .putAllLabels(new HashMap()) + .setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build()) + .setKmsKeyName("kmsKeyName412586233") + .setSchemaSettings(SchemaSettings.newBuilder().build()) + .setSatisfiesPzs(true) + .build(); + mockPublisher.addResponse(expectedResponse); + + String name = "name3373707"; + + Topic actualResponse = client.createTopic(name); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + Topic actualRequest = ((Topic) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void createTopicExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + String name = "name3373707"; + client.createTopic(name); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void updateTopicTest() throws Exception { + Topic expectedResponse = + Topic.newBuilder() + .setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .putAllLabels(new HashMap()) + .setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build()) + .setKmsKeyName("kmsKeyName412586233") + .setSchemaSettings(SchemaSettings.newBuilder().build()) + .setSatisfiesPzs(true) + .build(); + mockPublisher.addResponse(expectedResponse); + + UpdateTopicRequest request = + UpdateTopicRequest.newBuilder() + .setTopic(Topic.newBuilder().build()) + .setUpdateMask(FieldMask.newBuilder().build()) + .build(); + + Topic actualResponse = client.updateTopic(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + UpdateTopicRequest actualRequest = ((UpdateTopicRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getTopic(), actualRequest.getTopic()); + Assert.assertEquals(request.getUpdateMask(), actualRequest.getUpdateMask()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void updateTopicExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + UpdateTopicRequest request = + UpdateTopicRequest.newBuilder() + .setTopic(Topic.newBuilder().build()) + .setUpdateMask(FieldMask.newBuilder().build()) + .build(); + client.updateTopic(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void publishTest() throws Exception { + PublishResponse expectedResponse = + PublishResponse.newBuilder().addAllMessageIds(new ArrayList()).build(); + mockPublisher.addResponse(expectedResponse); + + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + List messages = new ArrayList<>(); + + PublishResponse actualResponse = client.publish(topic, messages); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + PublishRequest actualRequest = ((PublishRequest) actualRequests.get(0)); + + Assert.assertEquals(topic.toString(), actualRequest.getTopic()); + Assert.assertEquals(messages, actualRequest.getMessagesList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void publishExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + List messages = new ArrayList<>(); + client.publish(topic, messages); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void publishTest2() throws Exception { + PublishResponse expectedResponse = + PublishResponse.newBuilder().addAllMessageIds(new ArrayList()).build(); + mockPublisher.addResponse(expectedResponse); + + String topic = "topic110546223"; + List messages = new ArrayList<>(); + + PublishResponse actualResponse = client.publish(topic, messages); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + PublishRequest actualRequest = ((PublishRequest) actualRequests.get(0)); + + Assert.assertEquals(topic, actualRequest.getTopic()); + Assert.assertEquals(messages, actualRequest.getMessagesList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void publishExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + String topic = "topic110546223"; + List messages = new ArrayList<>(); + client.publish(topic, messages); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getTopicTest() throws Exception { + Topic expectedResponse = + Topic.newBuilder() + .setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .putAllLabels(new HashMap()) + .setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build()) + .setKmsKeyName("kmsKeyName412586233") + .setSchemaSettings(SchemaSettings.newBuilder().build()) + .setSatisfiesPzs(true) + .build(); + mockPublisher.addResponse(expectedResponse); + + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + + Topic actualResponse = client.getTopic(topic); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetTopicRequest actualRequest = ((GetTopicRequest) actualRequests.get(0)); + + Assert.assertEquals(topic.toString(), actualRequest.getTopic()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getTopicExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + client.getTopic(topic); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getTopicTest2() throws Exception { + Topic expectedResponse = + Topic.newBuilder() + .setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString()) + .putAllLabels(new HashMap()) + .setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build()) + .setKmsKeyName("kmsKeyName412586233") + .setSchemaSettings(SchemaSettings.newBuilder().build()) + .setSatisfiesPzs(true) + .build(); + mockPublisher.addResponse(expectedResponse); + + String topic = "topic110546223"; + + Topic actualResponse = client.getTopic(topic); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetTopicRequest actualRequest = ((GetTopicRequest) actualRequests.get(0)); + + Assert.assertEquals(topic, actualRequest.getTopic()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getTopicExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + String topic = "topic110546223"; + client.getTopic(topic); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listTopicsTest() throws Exception { + Topic responsesElement = Topic.newBuilder().build(); + ListTopicsResponse expectedResponse = + ListTopicsResponse.newBuilder() + .setNextPageToken("") + .addAllTopics(Arrays.asList(responsesElement)) + .build(); + mockPublisher.addResponse(expectedResponse); + + ProjectName project = ProjectName.of("[PROJECT]"); + + ListTopicsPagedResponse pagedListResponse = client.listTopics(project); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getTopicsList().get(0), resources.get(0)); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListTopicsRequest actualRequest = ((ListTopicsRequest) actualRequests.get(0)); + + Assert.assertEquals(project.toString(), actualRequest.getProject()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listTopicsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + ProjectName project = ProjectName.of("[PROJECT]"); + client.listTopics(project); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listTopicsTest2() throws Exception { + Topic responsesElement = Topic.newBuilder().build(); + ListTopicsResponse expectedResponse = + ListTopicsResponse.newBuilder() + .setNextPageToken("") + .addAllTopics(Arrays.asList(responsesElement)) + .build(); + mockPublisher.addResponse(expectedResponse); + + String project = "project-309310695"; + + ListTopicsPagedResponse pagedListResponse = client.listTopics(project); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getTopicsList().get(0), resources.get(0)); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListTopicsRequest actualRequest = ((ListTopicsRequest) actualRequests.get(0)); + + Assert.assertEquals(project, actualRequest.getProject()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listTopicsExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + String project = "project-309310695"; + client.listTopics(project); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listTopicSubscriptionsTest() throws Exception { + String responsesElement = "responsesElement-318365110"; + ListTopicSubscriptionsResponse expectedResponse = + ListTopicSubscriptionsResponse.newBuilder() + .setNextPageToken("") + .addAllSubscriptions(Arrays.asList(responsesElement)) + .build(); + mockPublisher.addResponse(expectedResponse); + + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + + ListTopicSubscriptionsPagedResponse pagedListResponse = client.listTopicSubscriptions(topic); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSubscriptionsList().get(0), resources.get(0)); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListTopicSubscriptionsRequest actualRequest = + ((ListTopicSubscriptionsRequest) actualRequests.get(0)); + + Assert.assertEquals(topic.toString(), actualRequest.getTopic()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listTopicSubscriptionsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + client.listTopicSubscriptions(topic); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listTopicSubscriptionsTest2() throws Exception { + String responsesElement = "responsesElement-318365110"; + ListTopicSubscriptionsResponse expectedResponse = + ListTopicSubscriptionsResponse.newBuilder() + .setNextPageToken("") + .addAllSubscriptions(Arrays.asList(responsesElement)) + .build(); + mockPublisher.addResponse(expectedResponse); + + String topic = "topic110546223"; + + ListTopicSubscriptionsPagedResponse pagedListResponse = client.listTopicSubscriptions(topic); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSubscriptionsList().get(0), resources.get(0)); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListTopicSubscriptionsRequest actualRequest = + ((ListTopicSubscriptionsRequest) actualRequests.get(0)); + + Assert.assertEquals(topic, actualRequest.getTopic()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listTopicSubscriptionsExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + String topic = "topic110546223"; + client.listTopicSubscriptions(topic); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listTopicSnapshotsTest() throws Exception { + String responsesElement = "responsesElement-318365110"; + ListTopicSnapshotsResponse expectedResponse = + ListTopicSnapshotsResponse.newBuilder() + .setNextPageToken("") + .addAllSnapshots(Arrays.asList(responsesElement)) + .build(); + mockPublisher.addResponse(expectedResponse); + + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + + ListTopicSnapshotsPagedResponse pagedListResponse = client.listTopicSnapshots(topic); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSnapshotsList().get(0), resources.get(0)); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListTopicSnapshotsRequest actualRequest = ((ListTopicSnapshotsRequest) actualRequests.get(0)); + + Assert.assertEquals(topic.toString(), actualRequest.getTopic()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listTopicSnapshotsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + client.listTopicSnapshots(topic); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void listTopicSnapshotsTest2() throws Exception { + String responsesElement = "responsesElement-318365110"; + ListTopicSnapshotsResponse expectedResponse = + ListTopicSnapshotsResponse.newBuilder() + .setNextPageToken("") + .addAllSnapshots(Arrays.asList(responsesElement)) + .build(); + mockPublisher.addResponse(expectedResponse); + + String topic = "topic110546223"; + + ListTopicSnapshotsPagedResponse pagedListResponse = client.listTopicSnapshots(topic); + + List resources = Lists.newArrayList(pagedListResponse.iterateAll()); + + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getSnapshotsList().get(0), resources.get(0)); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListTopicSnapshotsRequest actualRequest = ((ListTopicSnapshotsRequest) actualRequests.get(0)); + + Assert.assertEquals(topic, actualRequest.getTopic()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void listTopicSnapshotsExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + String topic = "topic110546223"; + client.listTopicSnapshots(topic); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteTopicTest() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockPublisher.addResponse(expectedResponse); + + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + + client.deleteTopic(topic); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteTopicRequest actualRequest = ((DeleteTopicRequest) actualRequests.get(0)); + + Assert.assertEquals(topic.toString(), actualRequest.getTopic()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteTopicExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]"); + client.deleteTopic(topic); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void deleteTopicTest2() throws Exception { + Empty expectedResponse = Empty.newBuilder().build(); + mockPublisher.addResponse(expectedResponse); + + String topic = "topic110546223"; + + client.deleteTopic(topic); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DeleteTopicRequest actualRequest = ((DeleteTopicRequest) actualRequests.get(0)); + + Assert.assertEquals(topic, actualRequest.getTopic()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void deleteTopicExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + String topic = "topic110546223"; + client.deleteTopic(topic); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void detachSubscriptionTest() throws Exception { + DetachSubscriptionResponse expectedResponse = DetachSubscriptionResponse.newBuilder().build(); + mockPublisher.addResponse(expectedResponse); + + DetachSubscriptionRequest request = + DetachSubscriptionRequest.newBuilder() + .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .build(); + + DetachSubscriptionResponse actualResponse = client.detachSubscription(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockPublisher.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + DetachSubscriptionRequest actualRequest = ((DetachSubscriptionRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getSubscription(), actualRequest.getSubscription()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void detachSubscriptionExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockPublisher.addException(exception); + + try { + DetachSubscriptionRequest request = + DetachSubscriptionRequest.newBuilder() + .setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString()) + .build(); + client.detachSubscription(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void setIamPolicyTest() throws Exception { + Policy expectedResponse = + Policy.newBuilder() + .setVersion(351608024) + .addAllBindings(new ArrayList()) + .setEtag(ByteString.EMPTY) + .build(); + mockIAMPolicy.addResponse(expectedResponse); + + SetIamPolicyRequest request = + SetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setPolicy(Policy.newBuilder().build()) + .build(); + + Policy actualResponse = client.setIamPolicy(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + SetIamPolicyRequest actualRequest = ((SetIamPolicyRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getPolicy(), actualRequest.getPolicy()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void setIamPolicyExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + SetIamPolicyRequest request = + SetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setPolicy(Policy.newBuilder().build()) + .build(); + client.setIamPolicy(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getIamPolicyTest() throws Exception { + Policy expectedResponse = + Policy.newBuilder() + .setVersion(351608024) + .addAllBindings(new ArrayList()) + .setEtag(ByteString.EMPTY) + .build(); + mockIAMPolicy.addResponse(expectedResponse); + + GetIamPolicyRequest request = + GetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setOptions(GetPolicyOptions.newBuilder().build()) + .build(); + + Policy actualResponse = client.getIamPolicy(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetIamPolicyRequest actualRequest = ((GetIamPolicyRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getOptions(), actualRequest.getOptions()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getIamPolicyExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + GetIamPolicyRequest request = + GetIamPolicyRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .setOptions(GetPolicyOptions.newBuilder().build()) + .build(); + client.getIamPolicy(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void testIamPermissionsTest() throws Exception { + TestIamPermissionsResponse expectedResponse = + TestIamPermissionsResponse.newBuilder().addAllPermissions(new ArrayList()).build(); + mockIAMPolicy.addResponse(expectedResponse); + + TestIamPermissionsRequest request = + TestIamPermissionsRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .addAllPermissions(new ArrayList()) + .build(); + + TestIamPermissionsResponse actualResponse = client.testIamPermissions(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + TestIamPermissionsRequest actualRequest = ((TestIamPermissionsRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getPermissionsList(), actualRequest.getPermissionsList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void testIamPermissionsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + TestIamPermissionsRequest request = + TestIamPermissionsRequest.newBuilder() + .setResource(ProjectName.of("[PROJECT]").toString()) + .addAllPermissions(new ArrayList()) + .build(); + client.testIamPermissions(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/TopicAdminSettings.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/TopicAdminSettings.java new file mode 100644 index 0000000000..a402b3333d --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/TopicAdminSettings.java @@ -0,0 +1,335 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1; + +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSnapshotsPagedResponse; +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSubscriptionsPagedResponse; +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicsPagedResponse; + +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.BatchingCallSettings; +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.cloud.pubsub.v1.stub.PublisherStubSettings; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.DeleteTopicRequest; +import com.google.pubsub.v1.DetachSubscriptionRequest; +import com.google.pubsub.v1.DetachSubscriptionResponse; +import com.google.pubsub.v1.GetTopicRequest; +import com.google.pubsub.v1.ListTopicSnapshotsRequest; +import com.google.pubsub.v1.ListTopicSnapshotsResponse; +import com.google.pubsub.v1.ListTopicSubscriptionsRequest; +import com.google.pubsub.v1.ListTopicSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ListTopicsResponse; +import com.google.pubsub.v1.PublishRequest; +import com.google.pubsub.v1.PublishResponse; +import com.google.pubsub.v1.Topic; +import com.google.pubsub.v1.UpdateTopicRequest; +import java.io.IOException; +import java.util.List; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link TopicAdminClient}. + * + *

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

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

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

For example, to set the total timeout of createTopic to 30 seconds: + * + *

{@code
+ * TopicAdminSettings.Builder topicAdminSettingsBuilder = TopicAdminSettings.newBuilder();
+ * topicAdminSettingsBuilder
+ *     .createTopicSettings()
+ *     .setRetrySettings(
+ *         topicAdminSettingsBuilder
+ *             .createTopicSettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * TopicAdminSettings topicAdminSettings = topicAdminSettingsBuilder.build();
+ * }
+ */ +@Generated("by gapic-generator-java") +public class TopicAdminSettings extends ClientSettings { + + /** Returns the object with the settings used for calls to createTopic. */ + public UnaryCallSettings createTopicSettings() { + return ((PublisherStubSettings) getStubSettings()).createTopicSettings(); + } + + /** Returns the object with the settings used for calls to updateTopic. */ + public UnaryCallSettings updateTopicSettings() { + return ((PublisherStubSettings) getStubSettings()).updateTopicSettings(); + } + + /** Returns the object with the settings used for calls to publish. */ + public BatchingCallSettings publishSettings() { + return ((PublisherStubSettings) getStubSettings()).publishSettings(); + } + + /** Returns the object with the settings used for calls to getTopic. */ + public UnaryCallSettings getTopicSettings() { + return ((PublisherStubSettings) getStubSettings()).getTopicSettings(); + } + + /** Returns the object with the settings used for calls to listTopics. */ + public PagedCallSettings + listTopicsSettings() { + return ((PublisherStubSettings) getStubSettings()).listTopicsSettings(); + } + + /** Returns the object with the settings used for calls to listTopicSubscriptions. */ + public PagedCallSettings< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> + listTopicSubscriptionsSettings() { + return ((PublisherStubSettings) getStubSettings()).listTopicSubscriptionsSettings(); + } + + /** Returns the object with the settings used for calls to listTopicSnapshots. */ + public PagedCallSettings< + ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, ListTopicSnapshotsPagedResponse> + listTopicSnapshotsSettings() { + return ((PublisherStubSettings) getStubSettings()).listTopicSnapshotsSettings(); + } + + /** Returns the object with the settings used for calls to deleteTopic. */ + public UnaryCallSettings deleteTopicSettings() { + return ((PublisherStubSettings) getStubSettings()).deleteTopicSettings(); + } + + /** Returns the object with the settings used for calls to detachSubscription. */ + public UnaryCallSettings + detachSubscriptionSettings() { + return ((PublisherStubSettings) getStubSettings()).detachSubscriptionSettings(); + } + + /** Returns the object with the settings used for calls to setIamPolicy. */ + public UnaryCallSettings setIamPolicySettings() { + return ((PublisherStubSettings) getStubSettings()).setIamPolicySettings(); + } + + /** Returns the object with the settings used for calls to getIamPolicy. */ + public UnaryCallSettings getIamPolicySettings() { + return ((PublisherStubSettings) getStubSettings()).getIamPolicySettings(); + } + + /** Returns the object with the settings used for calls to testIamPermissions. */ + public UnaryCallSettings + testIamPermissionsSettings() { + return ((PublisherStubSettings) getStubSettings()).testIamPermissionsSettings(); + } + + public static final TopicAdminSettings create(PublisherStubSettings stub) throws IOException { + return new TopicAdminSettings.Builder(stub.toBuilder()).build(); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return PublisherStubSettings.defaultExecutorProviderBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return PublisherStubSettings.getDefaultEndpoint(); + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return PublisherStubSettings.getDefaultServiceScopes(); + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return PublisherStubSettings.defaultCredentialsProviderBuilder(); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return PublisherStubSettings.defaultGrpcTransportProviderBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return PublisherStubSettings.defaultTransportChannelProvider(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return PublisherStubSettings.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 TopicAdminSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + } + + /** Builder for TopicAdminSettings. */ + public static class Builder extends ClientSettings.Builder { + + protected Builder() throws IOException { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(PublisherStubSettings.newBuilder(clientContext)); + } + + protected Builder(TopicAdminSettings settings) { + super(settings.getStubSettings().toBuilder()); + } + + protected Builder(PublisherStubSettings.Builder stubSettings) { + super(stubSettings); + } + + private static Builder createDefault() { + return new Builder(PublisherStubSettings.newBuilder()); + } + + public PublisherStubSettings.Builder getStubSettingsBuilder() { + return ((PublisherStubSettings.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 createTopic. */ + public UnaryCallSettings.Builder createTopicSettings() { + return getStubSettingsBuilder().createTopicSettings(); + } + + /** Returns the builder for the settings used for calls to updateTopic. */ + public UnaryCallSettings.Builder updateTopicSettings() { + return getStubSettingsBuilder().updateTopicSettings(); + } + + /** Returns the builder for the settings used for calls to publish. */ + public BatchingCallSettings.Builder publishSettings() { + return getStubSettingsBuilder().publishSettings(); + } + + /** Returns the builder for the settings used for calls to getTopic. */ + public UnaryCallSettings.Builder getTopicSettings() { + return getStubSettingsBuilder().getTopicSettings(); + } + + /** Returns the builder for the settings used for calls to listTopics. */ + public PagedCallSettings.Builder + listTopicsSettings() { + return getStubSettingsBuilder().listTopicsSettings(); + } + + /** Returns the builder for the settings used for calls to listTopicSubscriptions. */ + public PagedCallSettings.Builder< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> + listTopicSubscriptionsSettings() { + return getStubSettingsBuilder().listTopicSubscriptionsSettings(); + } + + /** Returns the builder for the settings used for calls to listTopicSnapshots. */ + public PagedCallSettings.Builder< + ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, ListTopicSnapshotsPagedResponse> + listTopicSnapshotsSettings() { + return getStubSettingsBuilder().listTopicSnapshotsSettings(); + } + + /** Returns the builder for the settings used for calls to deleteTopic. */ + public UnaryCallSettings.Builder deleteTopicSettings() { + return getStubSettingsBuilder().deleteTopicSettings(); + } + + /** Returns the builder for the settings used for calls to detachSubscription. */ + public UnaryCallSettings.Builder + detachSubscriptionSettings() { + return getStubSettingsBuilder().detachSubscriptionSettings(); + } + + /** Returns the builder for the settings used for calls to setIamPolicy. */ + public UnaryCallSettings.Builder setIamPolicySettings() { + return getStubSettingsBuilder().setIamPolicySettings(); + } + + /** Returns the builder for the settings used for calls to getIamPolicy. */ + public UnaryCallSettings.Builder getIamPolicySettings() { + return getStubSettingsBuilder().getIamPolicySettings(); + } + + /** Returns the builder for the settings used for calls to testIamPermissions. */ + public UnaryCallSettings.Builder + testIamPermissionsSettings() { + return getStubSettingsBuilder().testIamPermissionsSettings(); + } + + @Override + public TopicAdminSettings build() throws IOException { + return new TopicAdminSettings(this); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/gapic_metadata.json b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/gapic_metadata.json new file mode 100644 index 0000000000..ec835fc74c --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/gapic_metadata.json @@ -0,0 +1,156 @@ +{ + "schema": "1.0", + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "java", + "protoPackage": "google.pubsub.v1", + "libraryPackage": "com.google.cloud.pubsub.v1", + "services": { + "Publisher": { + "clients": { + "grpc": { + "libraryClient": "TopicAdminClient", + "rpcs": { + "CreateTopic": { + "methods": ["createTopic", "createTopic", "createTopic", "createTopicCallable"] + }, + "DeleteTopic": { + "methods": ["deleteTopic", "deleteTopic", "deleteTopic", "deleteTopicCallable"] + }, + "DetachSubscription": { + "methods": ["detachSubscription", "detachSubscriptionCallable"] + }, + "GetIamPolicy": { + "methods": ["getIamPolicy", "getIamPolicyCallable"] + }, + "GetTopic": { + "methods": ["getTopic", "getTopic", "getTopic", "getTopicCallable"] + }, + "ListTopicSnapshots": { + "methods": ["listTopicSnapshots", "listTopicSnapshots", "listTopicSnapshots", "listTopicSnapshotsPagedCallable", "listTopicSnapshotsCallable"] + }, + "ListTopicSubscriptions": { + "methods": ["listTopicSubscriptions", "listTopicSubscriptions", "listTopicSubscriptions", "listTopicSubscriptionsPagedCallable", "listTopicSubscriptionsCallable"] + }, + "ListTopics": { + "methods": ["listTopics", "listTopics", "listTopics", "listTopicsPagedCallable", "listTopicsCallable"] + }, + "Publish": { + "methods": ["publish", "publish", "publish", "publishCallable"] + }, + "SetIamPolicy": { + "methods": ["setIamPolicy", "setIamPolicyCallable"] + }, + "TestIamPermissions": { + "methods": ["testIamPermissions", "testIamPermissionsCallable"] + }, + "UpdateTopic": { + "methods": ["updateTopic", "updateTopicCallable"] + } + } + } + } + }, + "Subscriber": { + "clients": { + "grpc": { + "libraryClient": "SubscriptionAdminClient", + "rpcs": { + "Acknowledge": { + "methods": ["acknowledge", "acknowledge", "acknowledge", "acknowledgeCallable"] + }, + "CreateSnapshot": { + "methods": ["createSnapshot", "createSnapshot", "createSnapshot", "createSnapshot", "createSnapshot", "createSnapshotCallable"] + }, + "CreateSubscription": { + "methods": ["createSubscription", "createSubscription", "createSubscription", "createSubscription", "createSubscription", "createSubscriptionCallable"] + }, + "DeleteSnapshot": { + "methods": ["deleteSnapshot", "deleteSnapshot", "deleteSnapshot", "deleteSnapshotCallable"] + }, + "DeleteSubscription": { + "methods": ["deleteSubscription", "deleteSubscription", "deleteSubscription", "deleteSubscriptionCallable"] + }, + "GetIamPolicy": { + "methods": ["getIamPolicy", "getIamPolicyCallable"] + }, + "GetSnapshot": { + "methods": ["getSnapshot", "getSnapshot", "getSnapshot", "getSnapshotCallable"] + }, + "GetSubscription": { + "methods": ["getSubscription", "getSubscription", "getSubscription", "getSubscriptionCallable"] + }, + "ListSnapshots": { + "methods": ["listSnapshots", "listSnapshots", "listSnapshots", "listSnapshotsPagedCallable", "listSnapshotsCallable"] + }, + "ListSubscriptions": { + "methods": ["listSubscriptions", "listSubscriptions", "listSubscriptions", "listSubscriptionsPagedCallable", "listSubscriptionsCallable"] + }, + "ModifyAckDeadline": { + "methods": ["modifyAckDeadline", "modifyAckDeadline", "modifyAckDeadline", "modifyAckDeadlineCallable"] + }, + "ModifyPushConfig": { + "methods": ["modifyPushConfig", "modifyPushConfig", "modifyPushConfig", "modifyPushConfigCallable"] + }, + "Pull": { + "methods": ["pull", "pull", "pull", "pullCallable"] + }, + "Seek": { + "methods": ["seek", "seekCallable"] + }, + "SetIamPolicy": { + "methods": ["setIamPolicy", "setIamPolicyCallable"] + }, + "StreamingPull": { + "methods": ["streamingPullCallable"] + }, + "TestIamPermissions": { + "methods": ["testIamPermissions", "testIamPermissionsCallable"] + }, + "UpdateSnapshot": { + "methods": ["updateSnapshot", "updateSnapshotCallable"] + }, + "UpdateSubscription": { + "methods": ["updateSubscription", "updateSubscriptionCallable"] + } + } + } + } + }, + "SchemaService": { + "clients": { + "grpc": { + "libraryClient": "SchemaServiceClient", + "rpcs": { + "CreateSchema": { + "methods": ["createSchema", "createSchema", "createSchema", "createSchemaCallable"] + }, + "DeleteSchema": { + "methods": ["deleteSchema", "deleteSchema", "deleteSchema", "deleteSchemaCallable"] + }, + "GetIamPolicy": { + "methods": ["getIamPolicy", "getIamPolicyCallable"] + }, + "GetSchema": { + "methods": ["getSchema", "getSchema", "getSchema", "getSchemaCallable"] + }, + "ListSchemas": { + "methods": ["listSchemas", "listSchemas", "listSchemas", "listSchemasPagedCallable", "listSchemasCallable"] + }, + "SetIamPolicy": { + "methods": ["setIamPolicy", "setIamPolicyCallable"] + }, + "TestIamPermissions": { + "methods": ["testIamPermissions", "testIamPermissionsCallable"] + }, + "ValidateMessage": { + "methods": ["validateMessage", "validateMessageCallable"] + }, + "ValidateSchema": { + "methods": ["validateSchema", "validateSchema", "validateSchema", "validateSchemaCallable"] + } + } + } + } + } + } +} \ No newline at end of file diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/package-info.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/package-info.java new file mode 100644 index 0000000000..776d93208b --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/package-info.java @@ -0,0 +1,71 @@ +/* + * Copyright 2021 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 Pub/Sub API + * + *

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

======================= TopicAdminClient ======================= + * + *

Service Description: The service that an application uses to manipulate topics, and to send + * messages to a topic. + * + *

Sample for TopicAdminClient: + * + *

{@code
+ * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ *   TopicName name = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+ *   Topic response = topicAdminClient.createTopic(name);
+ * }
+ * }
+ * + *

======================= SubscriptionAdminClient ======================= + * + *

Service Description: The service that an application uses to manipulate subscriptions and to + * consume messages from a subscription via the `Pull` method or by establishing a bi-directional + * stream using the `StreamingPull` method. + * + *

Sample for SubscriptionAdminClient: + * + *

{@code
+ * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ *   SubscriptionName name = SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
+ *   TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
+ *   PushConfig pushConfig = PushConfig.newBuilder().build();
+ *   int ackDeadlineSeconds = 2135351438;
+ *   Subscription response =
+ *       subscriptionAdminClient.createSubscription(name, topic, pushConfig, ackDeadlineSeconds);
+ * }
+ * }
+ * + *

======================= SchemaServiceClient ======================= + * + *

Sample for SchemaServiceClient: + * + *

{@code
+ * try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
+ *   ProjectName parent = ProjectName.of("[PROJECT]");
+ *   Schema schema = Schema.newBuilder().build();
+ *   String schemaId = "schemaId-697673060";
+ *   Schema response = schemaServiceClient.createSchema(parent, schema, schemaId);
+ * }
+ * }
+ */ +@Generated("by gapic-generator-java") +package com.google.cloud.pubsub.v1; + +import javax.annotation.Generated; diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcPublisherCallableFactory.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcPublisherCallableFactory.java new file mode 100644 index 0000000000..35e7f539aa --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcPublisherCallableFactory.java @@ -0,0 +1,113 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.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 Publisher service API. + * + *

This class is for advanced usage. + */ +@Generated("by gapic-generator-java") +public class GrpcPublisherCallableFactory 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/pubsub/com/google/cloud/pubsub/v1/stub/GrpcPublisherStub.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcPublisherStub.java new file mode 100644 index 0000000000..2b5ce28a06 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcPublisherStub.java @@ -0,0 +1,579 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.stub; + +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSnapshotsPagedResponse; +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSubscriptionsPagedResponse; +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicsPagedResponse; + +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.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.longrunning.stub.GrpcOperationsStub; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.DeleteTopicRequest; +import com.google.pubsub.v1.DetachSubscriptionRequest; +import com.google.pubsub.v1.DetachSubscriptionResponse; +import com.google.pubsub.v1.GetTopicRequest; +import com.google.pubsub.v1.ListTopicSnapshotsRequest; +import com.google.pubsub.v1.ListTopicSnapshotsResponse; +import com.google.pubsub.v1.ListTopicSubscriptionsRequest; +import com.google.pubsub.v1.ListTopicSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ListTopicsResponse; +import com.google.pubsub.v1.PublishRequest; +import com.google.pubsub.v1.PublishResponse; +import com.google.pubsub.v1.Topic; +import com.google.pubsub.v1.UpdateTopicRequest; +import 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 Publisher service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public class GrpcPublisherStub extends PublisherStub { + private static final MethodDescriptor createTopicMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Publisher/CreateTopic") + .setRequestMarshaller(ProtoUtils.marshaller(Topic.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Topic.getDefaultInstance())) + .build(); + + private static final MethodDescriptor updateTopicMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Publisher/UpdateTopic") + .setRequestMarshaller(ProtoUtils.marshaller(UpdateTopicRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Topic.getDefaultInstance())) + .build(); + + private static final MethodDescriptor publishMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Publisher/Publish") + .setRequestMarshaller(ProtoUtils.marshaller(PublishRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(PublishResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor getTopicMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Publisher/GetTopic") + .setRequestMarshaller(ProtoUtils.marshaller(GetTopicRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Topic.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + listTopicsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Publisher/ListTopics") + .setRequestMarshaller(ProtoUtils.marshaller(ListTopicsRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(ListTopicsResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor< + ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse> + listTopicSubscriptionsMethodDescriptor = + MethodDescriptor + .newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Publisher/ListTopicSubscriptions") + .setRequestMarshaller( + ProtoUtils.marshaller(ListTopicSubscriptionsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ListTopicSubscriptionsResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + listTopicSnapshotsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Publisher/ListTopicSnapshots") + .setRequestMarshaller( + ProtoUtils.marshaller(ListTopicSnapshotsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ListTopicSnapshotsResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor deleteTopicMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Publisher/DeleteTopic") + .setRequestMarshaller(ProtoUtils.marshaller(DeleteTopicRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + detachSubscriptionMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Publisher/DetachSubscription") + .setRequestMarshaller( + ProtoUtils.marshaller(DetachSubscriptionRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(DetachSubscriptionResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor setIamPolicyMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/SetIamPolicy") + .setRequestMarshaller(ProtoUtils.marshaller(SetIamPolicyRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) + .build(); + + private static final MethodDescriptor getIamPolicyMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/GetIamPolicy") + .setRequestMarshaller(ProtoUtils.marshaller(GetIamPolicyRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + testIamPermissionsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/TestIamPermissions") + .setRequestMarshaller( + ProtoUtils.marshaller(TestIamPermissionsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(TestIamPermissionsResponse.getDefaultInstance())) + .build(); + + private final UnaryCallable createTopicCallable; + private final UnaryCallable updateTopicCallable; + private final UnaryCallable publishCallable; + private final UnaryCallable getTopicCallable; + private final UnaryCallable listTopicsCallable; + private final UnaryCallable listTopicsPagedCallable; + private final UnaryCallable + listTopicSubscriptionsCallable; + private final UnaryCallable + listTopicSubscriptionsPagedCallable; + private final UnaryCallable + listTopicSnapshotsCallable; + private final UnaryCallable + listTopicSnapshotsPagedCallable; + private final UnaryCallable deleteTopicCallable; + private final UnaryCallable + detachSubscriptionCallable; + private final UnaryCallable setIamPolicyCallable; + private final UnaryCallable getIamPolicyCallable; + private final UnaryCallable + testIamPermissionsCallable; + + private final BackgroundResource backgroundResources; + private final GrpcOperationsStub operationsStub; + private final GrpcStubCallableFactory callableFactory; + + public static final GrpcPublisherStub create(PublisherStubSettings settings) throws IOException { + return new GrpcPublisherStub(settings, ClientContext.create(settings)); + } + + public static final GrpcPublisherStub create(ClientContext clientContext) throws IOException { + return new GrpcPublisherStub(PublisherStubSettings.newBuilder().build(), clientContext); + } + + public static final GrpcPublisherStub create( + ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { + return new GrpcPublisherStub( + PublisherStubSettings.newBuilder().build(), clientContext, callableFactory); + } + + /** + * Constructs an instance of GrpcPublisherStub, 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 GrpcPublisherStub(PublisherStubSettings settings, ClientContext clientContext) + throws IOException { + this(settings, clientContext, new GrpcPublisherCallableFactory()); + } + + /** + * Constructs an instance of GrpcPublisherStub, 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 GrpcPublisherStub( + PublisherStubSettings settings, + ClientContext clientContext, + GrpcStubCallableFactory callableFactory) + throws IOException { + this.callableFactory = callableFactory; + this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); + + GrpcCallSettings createTopicTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(createTopicMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(Topic request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings updateTopicTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(updateTopicMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(UpdateTopicRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("topic.name", String.valueOf(request.getTopic().getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings publishTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(publishMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(PublishRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("topic", String.valueOf(request.getTopic())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getTopicTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getTopicMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetTopicRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("topic", String.valueOf(request.getTopic())); + return params.build(); + } + }) + .build(); + GrpcCallSettings listTopicsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listTopicsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListTopicsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("project", String.valueOf(request.getProject())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + listTopicSubscriptionsTransportSettings = + GrpcCallSettings + .newBuilder() + .setMethodDescriptor(listTopicSubscriptionsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListTopicSubscriptionsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("topic", String.valueOf(request.getTopic())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + listTopicSnapshotsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listTopicSnapshotsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListTopicSnapshotsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("topic", String.valueOf(request.getTopic())); + return params.build(); + } + }) + .build(); + GrpcCallSettings deleteTopicTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(deleteTopicMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(DeleteTopicRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("topic", String.valueOf(request.getTopic())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + detachSubscriptionTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(detachSubscriptionMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(DetachSubscriptionRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("subscription", String.valueOf(request.getSubscription())); + return params.build(); + } + }) + .build(); + GrpcCallSettings setIamPolicyTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(setIamPolicyMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(SetIamPolicyRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getIamPolicyTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getIamPolicyMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetIamPolicyRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + testIamPermissionsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(testIamPermissionsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(TestIamPermissionsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + + this.createTopicCallable = + callableFactory.createUnaryCallable( + createTopicTransportSettings, settings.createTopicSettings(), clientContext); + this.updateTopicCallable = + callableFactory.createUnaryCallable( + updateTopicTransportSettings, settings.updateTopicSettings(), clientContext); + this.publishCallable = + callableFactory.createUnaryCallable( + publishTransportSettings, settings.publishSettings(), clientContext); + this.getTopicCallable = + callableFactory.createUnaryCallable( + getTopicTransportSettings, settings.getTopicSettings(), clientContext); + this.listTopicsCallable = + callableFactory.createUnaryCallable( + listTopicsTransportSettings, settings.listTopicsSettings(), clientContext); + this.listTopicsPagedCallable = + callableFactory.createPagedCallable( + listTopicsTransportSettings, settings.listTopicsSettings(), clientContext); + this.listTopicSubscriptionsCallable = + callableFactory.createUnaryCallable( + listTopicSubscriptionsTransportSettings, + settings.listTopicSubscriptionsSettings(), + clientContext); + this.listTopicSubscriptionsPagedCallable = + callableFactory.createPagedCallable( + listTopicSubscriptionsTransportSettings, + settings.listTopicSubscriptionsSettings(), + clientContext); + this.listTopicSnapshotsCallable = + callableFactory.createUnaryCallable( + listTopicSnapshotsTransportSettings, + settings.listTopicSnapshotsSettings(), + clientContext); + this.listTopicSnapshotsPagedCallable = + callableFactory.createPagedCallable( + listTopicSnapshotsTransportSettings, + settings.listTopicSnapshotsSettings(), + clientContext); + this.deleteTopicCallable = + callableFactory.createUnaryCallable( + deleteTopicTransportSettings, settings.deleteTopicSettings(), clientContext); + this.detachSubscriptionCallable = + callableFactory.createUnaryCallable( + detachSubscriptionTransportSettings, + settings.detachSubscriptionSettings(), + clientContext); + this.setIamPolicyCallable = + callableFactory.createUnaryCallable( + setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext); + this.getIamPolicyCallable = + callableFactory.createUnaryCallable( + getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext); + this.testIamPermissionsCallable = + callableFactory.createUnaryCallable( + testIamPermissionsTransportSettings, + settings.testIamPermissionsSettings(), + clientContext); + + this.backgroundResources = + new BackgroundResourceAggregation(clientContext.getBackgroundResources()); + } + + public GrpcOperationsStub getOperationsStub() { + return operationsStub; + } + + @Override + public UnaryCallable createTopicCallable() { + return createTopicCallable; + } + + @Override + public UnaryCallable updateTopicCallable() { + return updateTopicCallable; + } + + @Override + public UnaryCallable publishCallable() { + return publishCallable; + } + + @Override + public UnaryCallable getTopicCallable() { + return getTopicCallable; + } + + @Override + public UnaryCallable listTopicsCallable() { + return listTopicsCallable; + } + + @Override + public UnaryCallable listTopicsPagedCallable() { + return listTopicsPagedCallable; + } + + @Override + public UnaryCallable + listTopicSubscriptionsCallable() { + return listTopicSubscriptionsCallable; + } + + @Override + public UnaryCallable + listTopicSubscriptionsPagedCallable() { + return listTopicSubscriptionsPagedCallable; + } + + @Override + public UnaryCallable + listTopicSnapshotsCallable() { + return listTopicSnapshotsCallable; + } + + @Override + public UnaryCallable + listTopicSnapshotsPagedCallable() { + return listTopicSnapshotsPagedCallable; + } + + @Override + public UnaryCallable deleteTopicCallable() { + return deleteTopicCallable; + } + + @Override + public UnaryCallable + detachSubscriptionCallable() { + return detachSubscriptionCallable; + } + + @Override + public UnaryCallable setIamPolicyCallable() { + return setIamPolicyCallable; + } + + @Override + public UnaryCallable getIamPolicyCallable() { + return getIamPolicyCallable; + } + + @Override + public UnaryCallable + testIamPermissionsCallable() { + return testIamPermissionsCallable; + } + + @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/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSchemaServiceCallableFactory.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSchemaServiceCallableFactory.java new file mode 100644 index 0000000000..b1e3e27ccf --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSchemaServiceCallableFactory.java @@ -0,0 +1,113 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.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 SchemaService service API. + * + *

This class is for advanced usage. + */ +@Generated("by gapic-generator-java") +public class GrpcSchemaServiceCallableFactory 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/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSchemaServiceStub.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSchemaServiceStub.java new file mode 100644 index 0000000000..11bac90c7d --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSchemaServiceStub.java @@ -0,0 +1,442 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.stub; + +import static com.google.cloud.pubsub.v1.SchemaServiceClient.ListSchemasPagedResponse; + +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.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.longrunning.stub.GrpcOperationsStub; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.CreateSchemaRequest; +import com.google.pubsub.v1.DeleteSchemaRequest; +import com.google.pubsub.v1.GetSchemaRequest; +import com.google.pubsub.v1.ListSchemasRequest; +import com.google.pubsub.v1.ListSchemasResponse; +import com.google.pubsub.v1.Schema; +import com.google.pubsub.v1.ValidateMessageRequest; +import com.google.pubsub.v1.ValidateMessageResponse; +import com.google.pubsub.v1.ValidateSchemaRequest; +import com.google.pubsub.v1.ValidateSchemaResponse; +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 SchemaService service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public class GrpcSchemaServiceStub extends SchemaServiceStub { + private static final MethodDescriptor createSchemaMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.SchemaService/CreateSchema") + .setRequestMarshaller(ProtoUtils.marshaller(CreateSchemaRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Schema.getDefaultInstance())) + .build(); + + private static final MethodDescriptor getSchemaMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.SchemaService/GetSchema") + .setRequestMarshaller(ProtoUtils.marshaller(GetSchemaRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Schema.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + listSchemasMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.SchemaService/ListSchemas") + .setRequestMarshaller(ProtoUtils.marshaller(ListSchemasRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ListSchemasResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor deleteSchemaMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.SchemaService/DeleteSchema") + .setRequestMarshaller(ProtoUtils.marshaller(DeleteSchemaRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + validateSchemaMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.SchemaService/ValidateSchema") + .setRequestMarshaller( + ProtoUtils.marshaller(ValidateSchemaRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ValidateSchemaResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + validateMessageMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.SchemaService/ValidateMessage") + .setRequestMarshaller( + ProtoUtils.marshaller(ValidateMessageRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ValidateMessageResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor setIamPolicyMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/SetIamPolicy") + .setRequestMarshaller(ProtoUtils.marshaller(SetIamPolicyRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) + .build(); + + private static final MethodDescriptor getIamPolicyMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/GetIamPolicy") + .setRequestMarshaller(ProtoUtils.marshaller(GetIamPolicyRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + testIamPermissionsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/TestIamPermissions") + .setRequestMarshaller( + ProtoUtils.marshaller(TestIamPermissionsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(TestIamPermissionsResponse.getDefaultInstance())) + .build(); + + private final UnaryCallable createSchemaCallable; + private final UnaryCallable getSchemaCallable; + private final UnaryCallable listSchemasCallable; + private final UnaryCallable + listSchemasPagedCallable; + private final UnaryCallable deleteSchemaCallable; + private final UnaryCallable validateSchemaCallable; + private final UnaryCallable + validateMessageCallable; + private final UnaryCallable setIamPolicyCallable; + private final UnaryCallable getIamPolicyCallable; + private final UnaryCallable + testIamPermissionsCallable; + + private final BackgroundResource backgroundResources; + private final GrpcOperationsStub operationsStub; + private final GrpcStubCallableFactory callableFactory; + + public static final GrpcSchemaServiceStub create(SchemaServiceStubSettings settings) + throws IOException { + return new GrpcSchemaServiceStub(settings, ClientContext.create(settings)); + } + + public static final GrpcSchemaServiceStub create(ClientContext clientContext) throws IOException { + return new GrpcSchemaServiceStub(SchemaServiceStubSettings.newBuilder().build(), clientContext); + } + + public static final GrpcSchemaServiceStub create( + ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { + return new GrpcSchemaServiceStub( + SchemaServiceStubSettings.newBuilder().build(), clientContext, callableFactory); + } + + /** + * Constructs an instance of GrpcSchemaServiceStub, 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 GrpcSchemaServiceStub(SchemaServiceStubSettings settings, ClientContext clientContext) + throws IOException { + this(settings, clientContext, new GrpcSchemaServiceCallableFactory()); + } + + /** + * Constructs an instance of GrpcSchemaServiceStub, 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 GrpcSchemaServiceStub( + SchemaServiceStubSettings settings, + ClientContext clientContext, + GrpcStubCallableFactory callableFactory) + throws IOException { + this.callableFactory = callableFactory; + this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); + + GrpcCallSettings createSchemaTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(createSchemaMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(CreateSchemaRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getSchemaTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getSchemaMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetSchemaRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings listSchemasTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listSchemasMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListSchemasRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings deleteSchemaTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(deleteSchemaMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(DeleteSchemaRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + validateSchemaTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(validateSchemaMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ValidateSchemaRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + validateMessageTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(validateMessageMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ValidateMessageRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("parent", String.valueOf(request.getParent())); + return params.build(); + } + }) + .build(); + GrpcCallSettings setIamPolicyTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(setIamPolicyMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(SetIamPolicyRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getIamPolicyTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getIamPolicyMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetIamPolicyRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + testIamPermissionsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(testIamPermissionsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(TestIamPermissionsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + + this.createSchemaCallable = + callableFactory.createUnaryCallable( + createSchemaTransportSettings, settings.createSchemaSettings(), clientContext); + this.getSchemaCallable = + callableFactory.createUnaryCallable( + getSchemaTransportSettings, settings.getSchemaSettings(), clientContext); + this.listSchemasCallable = + callableFactory.createUnaryCallable( + listSchemasTransportSettings, settings.listSchemasSettings(), clientContext); + this.listSchemasPagedCallable = + callableFactory.createPagedCallable( + listSchemasTransportSettings, settings.listSchemasSettings(), clientContext); + this.deleteSchemaCallable = + callableFactory.createUnaryCallable( + deleteSchemaTransportSettings, settings.deleteSchemaSettings(), clientContext); + this.validateSchemaCallable = + callableFactory.createUnaryCallable( + validateSchemaTransportSettings, settings.validateSchemaSettings(), clientContext); + this.validateMessageCallable = + callableFactory.createUnaryCallable( + validateMessageTransportSettings, settings.validateMessageSettings(), clientContext); + this.setIamPolicyCallable = + callableFactory.createUnaryCallable( + setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext); + this.getIamPolicyCallable = + callableFactory.createUnaryCallable( + getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext); + this.testIamPermissionsCallable = + callableFactory.createUnaryCallable( + testIamPermissionsTransportSettings, + settings.testIamPermissionsSettings(), + clientContext); + + this.backgroundResources = + new BackgroundResourceAggregation(clientContext.getBackgroundResources()); + } + + public GrpcOperationsStub getOperationsStub() { + return operationsStub; + } + + @Override + public UnaryCallable createSchemaCallable() { + return createSchemaCallable; + } + + @Override + public UnaryCallable getSchemaCallable() { + return getSchemaCallable; + } + + @Override + public UnaryCallable listSchemasCallable() { + return listSchemasCallable; + } + + @Override + public UnaryCallable listSchemasPagedCallable() { + return listSchemasPagedCallable; + } + + @Override + public UnaryCallable deleteSchemaCallable() { + return deleteSchemaCallable; + } + + @Override + public UnaryCallable validateSchemaCallable() { + return validateSchemaCallable; + } + + @Override + public UnaryCallable validateMessageCallable() { + return validateMessageCallable; + } + + @Override + public UnaryCallable setIamPolicyCallable() { + return setIamPolicyCallable; + } + + @Override + public UnaryCallable getIamPolicyCallable() { + return getIamPolicyCallable; + } + + @Override + public UnaryCallable + testIamPermissionsCallable() { + return testIamPermissionsCallable; + } + + @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/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSubscriberCallableFactory.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSubscriberCallableFactory.java new file mode 100644 index 0000000000..97d867601d --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSubscriberCallableFactory.java @@ -0,0 +1,113 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.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 Subscriber service API. + * + *

This class is for advanced usage. + */ +@Generated("by gapic-generator-java") +public class GrpcSubscriberCallableFactory 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/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSubscriberStub.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSubscriberStub.java new file mode 100644 index 0000000000..8580e626f8 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/GrpcSubscriberStub.java @@ -0,0 +1,792 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.stub; + +import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSnapshotsPagedResponse; +import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSubscriptionsPagedResponse; + +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.core.BackgroundResourceAggregation; +import com.google.api.gax.grpc.GrpcCallSettings; +import com.google.api.gax.grpc.GrpcStubCallableFactory; +import com.google.api.gax.rpc.BidiStreamingCallable; +import com.google.api.gax.rpc.ClientContext; +import com.google.api.gax.rpc.RequestParamsExtractor; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.collect.ImmutableMap; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.longrunning.stub.GrpcOperationsStub; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.AcknowledgeRequest; +import com.google.pubsub.v1.CreateSnapshotRequest; +import com.google.pubsub.v1.DeleteSnapshotRequest; +import com.google.pubsub.v1.DeleteSubscriptionRequest; +import com.google.pubsub.v1.GetSnapshotRequest; +import com.google.pubsub.v1.GetSubscriptionRequest; +import com.google.pubsub.v1.ListSnapshotsRequest; +import com.google.pubsub.v1.ListSnapshotsResponse; +import com.google.pubsub.v1.ListSubscriptionsRequest; +import com.google.pubsub.v1.ListSubscriptionsResponse; +import com.google.pubsub.v1.ModifyAckDeadlineRequest; +import com.google.pubsub.v1.ModifyPushConfigRequest; +import com.google.pubsub.v1.PullRequest; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.SeekRequest; +import com.google.pubsub.v1.SeekResponse; +import com.google.pubsub.v1.Snapshot; +import com.google.pubsub.v1.StreamingPullRequest; +import com.google.pubsub.v1.StreamingPullResponse; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.UpdateSnapshotRequest; +import com.google.pubsub.v1.UpdateSubscriptionRequest; +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 Subscriber service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public class GrpcSubscriberStub extends SubscriberStub { + private static final MethodDescriptor + createSubscriptionMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/CreateSubscription") + .setRequestMarshaller(ProtoUtils.marshaller(Subscription.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Subscription.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + getSubscriptionMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/GetSubscription") + .setRequestMarshaller( + ProtoUtils.marshaller(GetSubscriptionRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Subscription.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + updateSubscriptionMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/UpdateSubscription") + .setRequestMarshaller( + ProtoUtils.marshaller(UpdateSubscriptionRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Subscription.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + listSubscriptionsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/ListSubscriptions") + .setRequestMarshaller( + ProtoUtils.marshaller(ListSubscriptionsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ListSubscriptionsResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + deleteSubscriptionMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/DeleteSubscription") + .setRequestMarshaller( + ProtoUtils.marshaller(DeleteSubscriptionRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + modifyAckDeadlineMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/ModifyAckDeadline") + .setRequestMarshaller( + ProtoUtils.marshaller(ModifyAckDeadlineRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private static final MethodDescriptor acknowledgeMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/Acknowledge") + .setRequestMarshaller(ProtoUtils.marshaller(AcknowledgeRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private static final MethodDescriptor pullMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/Pull") + .setRequestMarshaller(ProtoUtils.marshaller(PullRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(PullResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + streamingPullMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.BIDI_STREAMING) + .setFullMethodName("google.pubsub.v1.Subscriber/StreamingPull") + .setRequestMarshaller( + ProtoUtils.marshaller(StreamingPullRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(StreamingPullResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + modifyPushConfigMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/ModifyPushConfig") + .setRequestMarshaller( + ProtoUtils.marshaller(ModifyPushConfigRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private static final MethodDescriptor getSnapshotMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/GetSnapshot") + .setRequestMarshaller(ProtoUtils.marshaller(GetSnapshotRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Snapshot.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + listSnapshotsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/ListSnapshots") + .setRequestMarshaller( + ProtoUtils.marshaller(ListSnapshotsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(ListSnapshotsResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + createSnapshotMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/CreateSnapshot") + .setRequestMarshaller( + ProtoUtils.marshaller(CreateSnapshotRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Snapshot.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + updateSnapshotMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/UpdateSnapshot") + .setRequestMarshaller( + ProtoUtils.marshaller(UpdateSnapshotRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Snapshot.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + deleteSnapshotMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/DeleteSnapshot") + .setRequestMarshaller( + ProtoUtils.marshaller(DeleteSnapshotRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + + private static final MethodDescriptor seekMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.pubsub.v1.Subscriber/Seek") + .setRequestMarshaller(ProtoUtils.marshaller(SeekRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(SeekResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor setIamPolicyMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/SetIamPolicy") + .setRequestMarshaller(ProtoUtils.marshaller(SetIamPolicyRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) + .build(); + + private static final MethodDescriptor getIamPolicyMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/GetIamPolicy") + .setRequestMarshaller(ProtoUtils.marshaller(GetIamPolicyRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + testIamPermissionsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/TestIamPermissions") + .setRequestMarshaller( + ProtoUtils.marshaller(TestIamPermissionsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(TestIamPermissionsResponse.getDefaultInstance())) + .build(); + + private final UnaryCallable createSubscriptionCallable; + private final UnaryCallable getSubscriptionCallable; + private final UnaryCallable updateSubscriptionCallable; + private final UnaryCallable + listSubscriptionsCallable; + private final UnaryCallable + listSubscriptionsPagedCallable; + private final UnaryCallable deleteSubscriptionCallable; + private final UnaryCallable modifyAckDeadlineCallable; + private final UnaryCallable acknowledgeCallable; + private final UnaryCallable pullCallable; + private final BidiStreamingCallable + streamingPullCallable; + private final UnaryCallable modifyPushConfigCallable; + private final UnaryCallable getSnapshotCallable; + private final UnaryCallable listSnapshotsCallable; + private final UnaryCallable + listSnapshotsPagedCallable; + private final UnaryCallable createSnapshotCallable; + private final UnaryCallable updateSnapshotCallable; + private final UnaryCallable deleteSnapshotCallable; + private final UnaryCallable seekCallable; + private final UnaryCallable setIamPolicyCallable; + private final UnaryCallable getIamPolicyCallable; + private final UnaryCallable + testIamPermissionsCallable; + + private final BackgroundResource backgroundResources; + private final GrpcOperationsStub operationsStub; + private final GrpcStubCallableFactory callableFactory; + + public static final GrpcSubscriberStub create(SubscriberStubSettings settings) + throws IOException { + return new GrpcSubscriberStub(settings, ClientContext.create(settings)); + } + + public static final GrpcSubscriberStub create(ClientContext clientContext) throws IOException { + return new GrpcSubscriberStub(SubscriberStubSettings.newBuilder().build(), clientContext); + } + + public static final GrpcSubscriberStub create( + ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { + return new GrpcSubscriberStub( + SubscriberStubSettings.newBuilder().build(), clientContext, callableFactory); + } + + /** + * Constructs an instance of GrpcSubscriberStub, 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 GrpcSubscriberStub(SubscriberStubSettings settings, ClientContext clientContext) + throws IOException { + this(settings, clientContext, new GrpcSubscriberCallableFactory()); + } + + /** + * Constructs an instance of GrpcSubscriberStub, 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 GrpcSubscriberStub( + SubscriberStubSettings settings, + ClientContext clientContext, + GrpcStubCallableFactory callableFactory) + throws IOException { + this.callableFactory = callableFactory; + this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); + + GrpcCallSettings createSubscriptionTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(createSubscriptionMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(Subscription request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getSubscriptionTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getSubscriptionMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetSubscriptionRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("subscription", String.valueOf(request.getSubscription())); + return params.build(); + } + }) + .build(); + GrpcCallSettings updateSubscriptionTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(updateSubscriptionMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(UpdateSubscriptionRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put( + "subscription.name", String.valueOf(request.getSubscription().getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + listSubscriptionsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listSubscriptionsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListSubscriptionsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("project", String.valueOf(request.getProject())); + return params.build(); + } + }) + .build(); + GrpcCallSettings deleteSubscriptionTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(deleteSubscriptionMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(DeleteSubscriptionRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("subscription", String.valueOf(request.getSubscription())); + return params.build(); + } + }) + .build(); + GrpcCallSettings modifyAckDeadlineTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(modifyAckDeadlineMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ModifyAckDeadlineRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("subscription", String.valueOf(request.getSubscription())); + return params.build(); + } + }) + .build(); + GrpcCallSettings acknowledgeTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(acknowledgeMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(AcknowledgeRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("subscription", String.valueOf(request.getSubscription())); + return params.build(); + } + }) + .build(); + GrpcCallSettings pullTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(pullMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(PullRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("subscription", String.valueOf(request.getSubscription())); + return params.build(); + } + }) + .build(); + GrpcCallSettings streamingPullTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(streamingPullMethodDescriptor) + .build(); + GrpcCallSettings modifyPushConfigTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(modifyPushConfigMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ModifyPushConfigRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("subscription", String.valueOf(request.getSubscription())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getSnapshotTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getSnapshotMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetSnapshotRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("snapshot", String.valueOf(request.getSnapshot())); + return params.build(); + } + }) + .build(); + GrpcCallSettings listSnapshotsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(listSnapshotsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(ListSnapshotsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("project", String.valueOf(request.getProject())); + return params.build(); + } + }) + .build(); + GrpcCallSettings createSnapshotTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(createSnapshotMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(CreateSnapshotRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings updateSnapshotTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(updateSnapshotMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(UpdateSnapshotRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("snapshot.name", String.valueOf(request.getSnapshot().getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings deleteSnapshotTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(deleteSnapshotMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(DeleteSnapshotRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("snapshot", String.valueOf(request.getSnapshot())); + return params.build(); + } + }) + .build(); + GrpcCallSettings seekTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(seekMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(SeekRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("subscription", String.valueOf(request.getSubscription())); + return params.build(); + } + }) + .build(); + GrpcCallSettings setIamPolicyTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(setIamPolicyMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(SetIamPolicyRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getIamPolicyTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getIamPolicyMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetIamPolicyRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + testIamPermissionsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(testIamPermissionsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(TestIamPermissionsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + + this.createSubscriptionCallable = + callableFactory.createUnaryCallable( + createSubscriptionTransportSettings, + settings.createSubscriptionSettings(), + clientContext); + this.getSubscriptionCallable = + callableFactory.createUnaryCallable( + getSubscriptionTransportSettings, settings.getSubscriptionSettings(), clientContext); + this.updateSubscriptionCallable = + callableFactory.createUnaryCallable( + updateSubscriptionTransportSettings, + settings.updateSubscriptionSettings(), + clientContext); + this.listSubscriptionsCallable = + callableFactory.createUnaryCallable( + listSubscriptionsTransportSettings, + settings.listSubscriptionsSettings(), + clientContext); + this.listSubscriptionsPagedCallable = + callableFactory.createPagedCallable( + listSubscriptionsTransportSettings, + settings.listSubscriptionsSettings(), + clientContext); + this.deleteSubscriptionCallable = + callableFactory.createUnaryCallable( + deleteSubscriptionTransportSettings, + settings.deleteSubscriptionSettings(), + clientContext); + this.modifyAckDeadlineCallable = + callableFactory.createUnaryCallable( + modifyAckDeadlineTransportSettings, + settings.modifyAckDeadlineSettings(), + clientContext); + this.acknowledgeCallable = + callableFactory.createUnaryCallable( + acknowledgeTransportSettings, settings.acknowledgeSettings(), clientContext); + this.pullCallable = + callableFactory.createUnaryCallable( + pullTransportSettings, settings.pullSettings(), clientContext); + this.streamingPullCallable = + callableFactory.createBidiStreamingCallable( + streamingPullTransportSettings, settings.streamingPullSettings(), clientContext); + this.modifyPushConfigCallable = + callableFactory.createUnaryCallable( + modifyPushConfigTransportSettings, settings.modifyPushConfigSettings(), clientContext); + this.getSnapshotCallable = + callableFactory.createUnaryCallable( + getSnapshotTransportSettings, settings.getSnapshotSettings(), clientContext); + this.listSnapshotsCallable = + callableFactory.createUnaryCallable( + listSnapshotsTransportSettings, settings.listSnapshotsSettings(), clientContext); + this.listSnapshotsPagedCallable = + callableFactory.createPagedCallable( + listSnapshotsTransportSettings, settings.listSnapshotsSettings(), clientContext); + this.createSnapshotCallable = + callableFactory.createUnaryCallable( + createSnapshotTransportSettings, settings.createSnapshotSettings(), clientContext); + this.updateSnapshotCallable = + callableFactory.createUnaryCallable( + updateSnapshotTransportSettings, settings.updateSnapshotSettings(), clientContext); + this.deleteSnapshotCallable = + callableFactory.createUnaryCallable( + deleteSnapshotTransportSettings, settings.deleteSnapshotSettings(), clientContext); + this.seekCallable = + callableFactory.createUnaryCallable( + seekTransportSettings, settings.seekSettings(), clientContext); + this.setIamPolicyCallable = + callableFactory.createUnaryCallable( + setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext); + this.getIamPolicyCallable = + callableFactory.createUnaryCallable( + getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext); + this.testIamPermissionsCallable = + callableFactory.createUnaryCallable( + testIamPermissionsTransportSettings, + settings.testIamPermissionsSettings(), + clientContext); + + this.backgroundResources = + new BackgroundResourceAggregation(clientContext.getBackgroundResources()); + } + + public GrpcOperationsStub getOperationsStub() { + return operationsStub; + } + + @Override + public UnaryCallable createSubscriptionCallable() { + return createSubscriptionCallable; + } + + @Override + public UnaryCallable getSubscriptionCallable() { + return getSubscriptionCallable; + } + + @Override + public UnaryCallable updateSubscriptionCallable() { + return updateSubscriptionCallable; + } + + @Override + public UnaryCallable + listSubscriptionsCallable() { + return listSubscriptionsCallable; + } + + @Override + public UnaryCallable + listSubscriptionsPagedCallable() { + return listSubscriptionsPagedCallable; + } + + @Override + public UnaryCallable deleteSubscriptionCallable() { + return deleteSubscriptionCallable; + } + + @Override + public UnaryCallable modifyAckDeadlineCallable() { + return modifyAckDeadlineCallable; + } + + @Override + public UnaryCallable acknowledgeCallable() { + return acknowledgeCallable; + } + + @Override + public UnaryCallable pullCallable() { + return pullCallable; + } + + @Override + public BidiStreamingCallable + streamingPullCallable() { + return streamingPullCallable; + } + + @Override + public UnaryCallable modifyPushConfigCallable() { + return modifyPushConfigCallable; + } + + @Override + public UnaryCallable getSnapshotCallable() { + return getSnapshotCallable; + } + + @Override + public UnaryCallable listSnapshotsCallable() { + return listSnapshotsCallable; + } + + @Override + public UnaryCallable + listSnapshotsPagedCallable() { + return listSnapshotsPagedCallable; + } + + @Override + public UnaryCallable createSnapshotCallable() { + return createSnapshotCallable; + } + + @Override + public UnaryCallable updateSnapshotCallable() { + return updateSnapshotCallable; + } + + @Override + public UnaryCallable deleteSnapshotCallable() { + return deleteSnapshotCallable; + } + + @Override + public UnaryCallable seekCallable() { + return seekCallable; + } + + @Override + public UnaryCallable setIamPolicyCallable() { + return setIamPolicyCallable; + } + + @Override + public UnaryCallable getIamPolicyCallable() { + return getIamPolicyCallable; + } + + @Override + public UnaryCallable + testIamPermissionsCallable() { + return testIamPermissionsCallable; + } + + @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/pubsub/com/google/cloud/pubsub/v1/stub/PublisherStub.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/PublisherStub.java new file mode 100644 index 0000000000..9b90ca986f --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/PublisherStub.java @@ -0,0 +1,125 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.stub; + +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSnapshotsPagedResponse; +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSubscriptionsPagedResponse; +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicsPagedResponse; + +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.DeleteTopicRequest; +import com.google.pubsub.v1.DetachSubscriptionRequest; +import com.google.pubsub.v1.DetachSubscriptionResponse; +import com.google.pubsub.v1.GetTopicRequest; +import com.google.pubsub.v1.ListTopicSnapshotsRequest; +import com.google.pubsub.v1.ListTopicSnapshotsResponse; +import com.google.pubsub.v1.ListTopicSubscriptionsRequest; +import com.google.pubsub.v1.ListTopicSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ListTopicsResponse; +import com.google.pubsub.v1.PublishRequest; +import com.google.pubsub.v1.PublishResponse; +import com.google.pubsub.v1.Topic; +import com.google.pubsub.v1.UpdateTopicRequest; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Base stub class for the Publisher service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public abstract class PublisherStub implements BackgroundResource { + + public UnaryCallable createTopicCallable() { + throw new UnsupportedOperationException("Not implemented: createTopicCallable()"); + } + + public UnaryCallable updateTopicCallable() { + throw new UnsupportedOperationException("Not implemented: updateTopicCallable()"); + } + + public UnaryCallable publishCallable() { + throw new UnsupportedOperationException("Not implemented: publishCallable()"); + } + + public UnaryCallable getTopicCallable() { + throw new UnsupportedOperationException("Not implemented: getTopicCallable()"); + } + + public UnaryCallable listTopicsPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listTopicsPagedCallable()"); + } + + public UnaryCallable listTopicsCallable() { + throw new UnsupportedOperationException("Not implemented: listTopicsCallable()"); + } + + public UnaryCallable + listTopicSubscriptionsPagedCallable() { + throw new UnsupportedOperationException( + "Not implemented: listTopicSubscriptionsPagedCallable()"); + } + + public UnaryCallable + listTopicSubscriptionsCallable() { + throw new UnsupportedOperationException("Not implemented: listTopicSubscriptionsCallable()"); + } + + public UnaryCallable + listTopicSnapshotsPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listTopicSnapshotsPagedCallable()"); + } + + public UnaryCallable + listTopicSnapshotsCallable() { + throw new UnsupportedOperationException("Not implemented: listTopicSnapshotsCallable()"); + } + + public UnaryCallable deleteTopicCallable() { + throw new UnsupportedOperationException("Not implemented: deleteTopicCallable()"); + } + + public UnaryCallable + detachSubscriptionCallable() { + throw new UnsupportedOperationException("Not implemented: detachSubscriptionCallable()"); + } + + public UnaryCallable setIamPolicyCallable() { + throw new UnsupportedOperationException("Not implemented: setIamPolicyCallable()"); + } + + public UnaryCallable getIamPolicyCallable() { + throw new UnsupportedOperationException("Not implemented: getIamPolicyCallable()"); + } + + public UnaryCallable + testIamPermissionsCallable() { + throw new UnsupportedOperationException("Not implemented: testIamPermissionsCallable()"); + } + + @Override + public abstract void close(); +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/PublisherStubSettings.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/PublisherStubSettings.java new file mode 100644 index 0000000000..5909b0850c --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/PublisherStubSettings.java @@ -0,0 +1,885 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.stub; + +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSnapshotsPagedResponse; +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSubscriptionsPagedResponse; +import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicsPagedResponse; + +import com.google.api.core.ApiFunction; +import com.google.api.core.ApiFuture; +import com.google.api.core.BetaApi; +import com.google.api.gax.batching.BatchingSettings; +import com.google.api.gax.batching.FlowControlSettings; +import com.google.api.gax.batching.FlowController; +import com.google.api.gax.batching.PartitionKey; +import com.google.api.gax.batching.RequestBuilder; +import com.google.api.gax.core.GaxProperties; +import com.google.api.gax.core.GoogleCredentialsProvider; +import com.google.api.gax.core.InstantiatingExecutorProvider; +import com.google.api.gax.grpc.GaxGrpcProperties; +import com.google.api.gax.grpc.GrpcTransportChannel; +import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiCallContext; +import com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.BatchedRequestIssuer; +import com.google.api.gax.rpc.BatchingCallSettings; +import com.google.api.gax.rpc.BatchingDescriptor; +import com.google.api.gax.rpc.ClientContext; +import com.google.api.gax.rpc.PageContext; +import com.google.api.gax.rpc.PagedCallSettings; +import com.google.api.gax.rpc.PagedListDescriptor; +import com.google.api.gax.rpc.PagedListResponseFactory; +import com.google.api.gax.rpc.StatusCode; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.DeleteTopicRequest; +import com.google.pubsub.v1.DetachSubscriptionRequest; +import com.google.pubsub.v1.DetachSubscriptionResponse; +import com.google.pubsub.v1.GetTopicRequest; +import com.google.pubsub.v1.ListTopicSnapshotsRequest; +import com.google.pubsub.v1.ListTopicSnapshotsResponse; +import com.google.pubsub.v1.ListTopicSubscriptionsRequest; +import com.google.pubsub.v1.ListTopicSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ListTopicsResponse; +import com.google.pubsub.v1.PublishRequest; +import com.google.pubsub.v1.PublishResponse; +import com.google.pubsub.v1.Topic; +import com.google.pubsub.v1.UpdateTopicRequest; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import javax.annotation.Generated; +import org.threeten.bp.Duration; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link PublisherStub}. + * + *

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

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

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

For example, to set the total timeout of createTopic to 30 seconds: + * + *

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

Note: This method does not support applying settings to streaming methods. + */ + public Builder applyToAllUnaryMethods( + ApiFunction, Void> settingsUpdater) throws Exception { + super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); + return this; + } + + public ImmutableList> unaryMethodSettingsBuilders() { + return unaryMethodSettingsBuilders; + } + + /** Returns the builder for the settings used for calls to createTopic. */ + public UnaryCallSettings.Builder createTopicSettings() { + return createTopicSettings; + } + + /** Returns the builder for the settings used for calls to updateTopic. */ + public UnaryCallSettings.Builder updateTopicSettings() { + return updateTopicSettings; + } + + /** Returns the builder for the settings used for calls to publish. */ + public BatchingCallSettings.Builder publishSettings() { + return publishSettings; + } + + /** Returns the builder for the settings used for calls to getTopic. */ + public UnaryCallSettings.Builder getTopicSettings() { + return getTopicSettings; + } + + /** Returns the builder for the settings used for calls to listTopics. */ + public PagedCallSettings.Builder + listTopicsSettings() { + return listTopicsSettings; + } + + /** Returns the builder for the settings used for calls to listTopicSubscriptions. */ + public PagedCallSettings.Builder< + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> + listTopicSubscriptionsSettings() { + return listTopicSubscriptionsSettings; + } + + /** Returns the builder for the settings used for calls to listTopicSnapshots. */ + public PagedCallSettings.Builder< + ListTopicSnapshotsRequest, ListTopicSnapshotsResponse, ListTopicSnapshotsPagedResponse> + listTopicSnapshotsSettings() { + return listTopicSnapshotsSettings; + } + + /** Returns the builder for the settings used for calls to deleteTopic. */ + public UnaryCallSettings.Builder deleteTopicSettings() { + return deleteTopicSettings; + } + + /** Returns the builder for the settings used for calls to detachSubscription. */ + public UnaryCallSettings.Builder + detachSubscriptionSettings() { + return detachSubscriptionSettings; + } + + /** Returns the builder for the settings used for calls to setIamPolicy. */ + public UnaryCallSettings.Builder setIamPolicySettings() { + return setIamPolicySettings; + } + + /** Returns the builder for the settings used for calls to getIamPolicy. */ + public UnaryCallSettings.Builder getIamPolicySettings() { + return getIamPolicySettings; + } + + /** Returns the builder for the settings used for calls to testIamPermissions. */ + public UnaryCallSettings.Builder + testIamPermissionsSettings() { + return testIamPermissionsSettings; + } + + @Override + public PublisherStubSettings build() throws IOException { + return new PublisherStubSettings(this); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SchemaServiceStub.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SchemaServiceStub.java new file mode 100644 index 0000000000..b194653b3c --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SchemaServiceStub.java @@ -0,0 +1,93 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.stub; + +import static com.google.cloud.pubsub.v1.SchemaServiceClient.ListSchemasPagedResponse; + +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.CreateSchemaRequest; +import com.google.pubsub.v1.DeleteSchemaRequest; +import com.google.pubsub.v1.GetSchemaRequest; +import com.google.pubsub.v1.ListSchemasRequest; +import com.google.pubsub.v1.ListSchemasResponse; +import com.google.pubsub.v1.Schema; +import com.google.pubsub.v1.ValidateMessageRequest; +import com.google.pubsub.v1.ValidateMessageResponse; +import com.google.pubsub.v1.ValidateSchemaRequest; +import com.google.pubsub.v1.ValidateSchemaResponse; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Base stub class for the SchemaService service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public abstract class SchemaServiceStub implements BackgroundResource { + + public UnaryCallable createSchemaCallable() { + throw new UnsupportedOperationException("Not implemented: createSchemaCallable()"); + } + + public UnaryCallable getSchemaCallable() { + throw new UnsupportedOperationException("Not implemented: getSchemaCallable()"); + } + + public UnaryCallable listSchemasPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listSchemasPagedCallable()"); + } + + public UnaryCallable listSchemasCallable() { + throw new UnsupportedOperationException("Not implemented: listSchemasCallable()"); + } + + public UnaryCallable deleteSchemaCallable() { + throw new UnsupportedOperationException("Not implemented: deleteSchemaCallable()"); + } + + public UnaryCallable validateSchemaCallable() { + throw new UnsupportedOperationException("Not implemented: validateSchemaCallable()"); + } + + public UnaryCallable validateMessageCallable() { + throw new UnsupportedOperationException("Not implemented: validateMessageCallable()"); + } + + public UnaryCallable setIamPolicyCallable() { + throw new UnsupportedOperationException("Not implemented: setIamPolicyCallable()"); + } + + public UnaryCallable getIamPolicyCallable() { + throw new UnsupportedOperationException("Not implemented: getIamPolicyCallable()"); + } + + public UnaryCallable + testIamPermissionsCallable() { + throw new UnsupportedOperationException("Not implemented: testIamPermissionsCallable()"); + } + + @Override + public abstract void close(); +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SchemaServiceStubSettings.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SchemaServiceStubSettings.java new file mode 100644 index 0000000000..6f8f9b182e --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SchemaServiceStubSettings.java @@ -0,0 +1,528 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.stub; + +import static com.google.cloud.pubsub.v1.SchemaServiceClient.ListSchemasPagedResponse; + +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.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.CreateSchemaRequest; +import com.google.pubsub.v1.DeleteSchemaRequest; +import com.google.pubsub.v1.GetSchemaRequest; +import com.google.pubsub.v1.ListSchemasRequest; +import com.google.pubsub.v1.ListSchemasResponse; +import com.google.pubsub.v1.Schema; +import com.google.pubsub.v1.ValidateMessageRequest; +import com.google.pubsub.v1.ValidateMessageResponse; +import com.google.pubsub.v1.ValidateSchemaRequest; +import com.google.pubsub.v1.ValidateSchemaResponse; +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 SchemaServiceStub}. + * + *

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

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

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

For example, to set the total timeout of createSchema to 30 seconds: + * + *

{@code
+ * SchemaServiceStubSettings.Builder schemaServiceSettingsBuilder =
+ *     SchemaServiceStubSettings.newBuilder();
+ * schemaServiceSettingsBuilder
+ *     .createSchemaSettings()
+ *     .setRetrySettings(
+ *         schemaServiceSettingsBuilder
+ *             .createSchemaSettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * SchemaServiceStubSettings schemaServiceSettings = schemaServiceSettingsBuilder.build();
+ * }
+ */ +@Generated("by gapic-generator-java") +public class SchemaServiceStubSettings extends StubSettings { + /** The default scopes of the service. */ + private static final ImmutableList DEFAULT_SERVICE_SCOPES = + ImmutableList.builder() + .add("https://www.googleapis.com/auth/cloud-platform") + .add("https://www.googleapis.com/auth/pubsub") + .build(); + + private final UnaryCallSettings createSchemaSettings; + private final UnaryCallSettings getSchemaSettings; + private final PagedCallSettings + listSchemasSettings; + private final UnaryCallSettings deleteSchemaSettings; + private final UnaryCallSettings + validateSchemaSettings; + private final UnaryCallSettings + validateMessageSettings; + private final UnaryCallSettings setIamPolicySettings; + private final UnaryCallSettings getIamPolicySettings; + private final UnaryCallSettings + testIamPermissionsSettings; + + private static final PagedListDescriptor + LIST_SCHEMAS_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListSchemasRequest injectToken(ListSchemasRequest payload, String token) { + return ListSchemasRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListSchemasRequest injectPageSize(ListSchemasRequest payload, int pageSize) { + return ListSchemasRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListSchemasRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListSchemasResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListSchemasResponse payload) { + return payload.getSchemasList() == null + ? ImmutableList.of() + : payload.getSchemasList(); + } + }; + + private static final PagedListResponseFactory< + ListSchemasRequest, ListSchemasResponse, ListSchemasPagedResponse> + LIST_SCHEMAS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListSchemasRequest, ListSchemasResponse, ListSchemasPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListSchemasRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, LIST_SCHEMAS_PAGE_STR_DESC, request, context); + return ListSchemasPagedResponse.createAsync(pageContext, futureResponse); + } + }; + + /** Returns the object with the settings used for calls to createSchema. */ + public UnaryCallSettings createSchemaSettings() { + return createSchemaSettings; + } + + /** Returns the object with the settings used for calls to getSchema. */ + public UnaryCallSettings getSchemaSettings() { + return getSchemaSettings; + } + + /** Returns the object with the settings used for calls to listSchemas. */ + public PagedCallSettings + listSchemasSettings() { + return listSchemasSettings; + } + + /** Returns the object with the settings used for calls to deleteSchema. */ + public UnaryCallSettings deleteSchemaSettings() { + return deleteSchemaSettings; + } + + /** Returns the object with the settings used for calls to validateSchema. */ + public UnaryCallSettings validateSchemaSettings() { + return validateSchemaSettings; + } + + /** Returns the object with the settings used for calls to validateMessage. */ + public UnaryCallSettings + validateMessageSettings() { + return validateMessageSettings; + } + + /** Returns the object with the settings used for calls to setIamPolicy. */ + public UnaryCallSettings setIamPolicySettings() { + return setIamPolicySettings; + } + + /** Returns the object with the settings used for calls to getIamPolicy. */ + public UnaryCallSettings getIamPolicySettings() { + return getIamPolicySettings; + } + + /** Returns the object with the settings used for calls to testIamPermissions. */ + public UnaryCallSettings + testIamPermissionsSettings() { + return testIamPermissionsSettings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public SchemaServiceStub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(GrpcTransportChannel.getGrpcTransportName())) { + return GrpcSchemaServiceStub.create(this); + } + throw new UnsupportedOperationException( + String.format( + "Transport not supported: %s", getTransportChannelProvider().getTransportName())); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return InstantiatingExecutorProvider.newBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return "pubsub.googleapis.com:443"; + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return DEFAULT_SERVICE_SCOPES; + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return InstantiatingGrpcChannelProvider.newBuilder() + .setMaxInboundMessageSize(Integer.MAX_VALUE); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return defaultGrpcTransportProviderBuilder().build(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return ApiClientHeaderProvider.newBuilder() + .setGeneratedLibToken( + "gapic", GaxProperties.getLibraryVersion(SchemaServiceStubSettings.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 SchemaServiceStubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + + createSchemaSettings = settingsBuilder.createSchemaSettings().build(); + getSchemaSettings = settingsBuilder.getSchemaSettings().build(); + listSchemasSettings = settingsBuilder.listSchemasSettings().build(); + deleteSchemaSettings = settingsBuilder.deleteSchemaSettings().build(); + validateSchemaSettings = settingsBuilder.validateSchemaSettings().build(); + validateMessageSettings = settingsBuilder.validateMessageSettings().build(); + setIamPolicySettings = settingsBuilder.setIamPolicySettings().build(); + getIamPolicySettings = settingsBuilder.getIamPolicySettings().build(); + testIamPermissionsSettings = settingsBuilder.testIamPermissionsSettings().build(); + } + + /** Builder for SchemaServiceStubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final UnaryCallSettings.Builder createSchemaSettings; + private final UnaryCallSettings.Builder getSchemaSettings; + private final PagedCallSettings.Builder< + ListSchemasRequest, ListSchemasResponse, ListSchemasPagedResponse> + listSchemasSettings; + private final UnaryCallSettings.Builder deleteSchemaSettings; + private final UnaryCallSettings.Builder + validateSchemaSettings; + private final UnaryCallSettings.Builder + validateMessageSettings; + private final UnaryCallSettings.Builder setIamPolicySettings; + private final UnaryCallSettings.Builder getIamPolicySettings; + private final UnaryCallSettings.Builder + testIamPermissionsSettings; + private static final ImmutableMap> + RETRYABLE_CODE_DEFINITIONS; + + static { + ImmutableMap.Builder> definitions = + ImmutableMap.builder(); + definitions.put("no_retry_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); + RETRY_PARAM_DEFINITIONS = definitions.build(); + } + + protected Builder() { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(clientContext); + + createSchemaSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + getSchemaSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + listSchemasSettings = PagedCallSettings.newBuilder(LIST_SCHEMAS_PAGE_STR_FACT); + deleteSchemaSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + validateSchemaSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + validateMessageSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + setIamPolicySettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + getIamPolicySettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + testIamPermissionsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + createSchemaSettings, + getSchemaSettings, + listSchemasSettings, + deleteSchemaSettings, + validateSchemaSettings, + validateMessageSettings, + setIamPolicySettings, + getIamPolicySettings, + testIamPermissionsSettings); + initDefaults(this); + } + + protected Builder(SchemaServiceStubSettings settings) { + super(settings); + + createSchemaSettings = settings.createSchemaSettings.toBuilder(); + getSchemaSettings = settings.getSchemaSettings.toBuilder(); + listSchemasSettings = settings.listSchemasSettings.toBuilder(); + deleteSchemaSettings = settings.deleteSchemaSettings.toBuilder(); + validateSchemaSettings = settings.validateSchemaSettings.toBuilder(); + validateMessageSettings = settings.validateMessageSettings.toBuilder(); + setIamPolicySettings = settings.setIamPolicySettings.toBuilder(); + getIamPolicySettings = settings.getIamPolicySettings.toBuilder(); + testIamPermissionsSettings = settings.testIamPermissionsSettings.toBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + createSchemaSettings, + getSchemaSettings, + listSchemasSettings, + deleteSchemaSettings, + validateSchemaSettings, + validateMessageSettings, + setIamPolicySettings, + getIamPolicySettings, + testIamPermissionsSettings); + } + + 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 + .createSchemaSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .getSchemaSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .listSchemasSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .deleteSchemaSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .validateSchemaSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .validateMessageSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .setIamPolicySettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .getIamPolicySettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + builder + .testIamPermissionsSettings() + .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 createSchema. */ + public UnaryCallSettings.Builder createSchemaSettings() { + return createSchemaSettings; + } + + /** Returns the builder for the settings used for calls to getSchema. */ + public UnaryCallSettings.Builder getSchemaSettings() { + return getSchemaSettings; + } + + /** Returns the builder for the settings used for calls to listSchemas. */ + public PagedCallSettings.Builder< + ListSchemasRequest, ListSchemasResponse, ListSchemasPagedResponse> + listSchemasSettings() { + return listSchemasSettings; + } + + /** Returns the builder for the settings used for calls to deleteSchema. */ + public UnaryCallSettings.Builder deleteSchemaSettings() { + return deleteSchemaSettings; + } + + /** Returns the builder for the settings used for calls to validateSchema. */ + public UnaryCallSettings.Builder + validateSchemaSettings() { + return validateSchemaSettings; + } + + /** Returns the builder for the settings used for calls to validateMessage. */ + public UnaryCallSettings.Builder + validateMessageSettings() { + return validateMessageSettings; + } + + /** Returns the builder for the settings used for calls to setIamPolicy. */ + public UnaryCallSettings.Builder setIamPolicySettings() { + return setIamPolicySettings; + } + + /** Returns the builder for the settings used for calls to getIamPolicy. */ + public UnaryCallSettings.Builder getIamPolicySettings() { + return getIamPolicySettings; + } + + /** Returns the builder for the settings used for calls to testIamPermissions. */ + public UnaryCallSettings.Builder + testIamPermissionsSettings() { + return testIamPermissionsSettings; + } + + @Override + public SchemaServiceStubSettings build() throws IOException { + return new SchemaServiceStubSettings(this); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SubscriberStub.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SubscriberStub.java new file mode 100644 index 0000000000..7233e20081 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SubscriberStub.java @@ -0,0 +1,155 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.stub; + +import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSnapshotsPagedResponse; +import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSubscriptionsPagedResponse; + +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.rpc.BidiStreamingCallable; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.AcknowledgeRequest; +import com.google.pubsub.v1.CreateSnapshotRequest; +import com.google.pubsub.v1.DeleteSnapshotRequest; +import com.google.pubsub.v1.DeleteSubscriptionRequest; +import com.google.pubsub.v1.GetSnapshotRequest; +import com.google.pubsub.v1.GetSubscriptionRequest; +import com.google.pubsub.v1.ListSnapshotsRequest; +import com.google.pubsub.v1.ListSnapshotsResponse; +import com.google.pubsub.v1.ListSubscriptionsRequest; +import com.google.pubsub.v1.ListSubscriptionsResponse; +import com.google.pubsub.v1.ModifyAckDeadlineRequest; +import com.google.pubsub.v1.ModifyPushConfigRequest; +import com.google.pubsub.v1.PullRequest; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.SeekRequest; +import com.google.pubsub.v1.SeekResponse; +import com.google.pubsub.v1.Snapshot; +import com.google.pubsub.v1.StreamingPullRequest; +import com.google.pubsub.v1.StreamingPullResponse; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.UpdateSnapshotRequest; +import com.google.pubsub.v1.UpdateSubscriptionRequest; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Base stub class for the Subscriber service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public abstract class SubscriberStub implements BackgroundResource { + + public UnaryCallable createSubscriptionCallable() { + throw new UnsupportedOperationException("Not implemented: createSubscriptionCallable()"); + } + + public UnaryCallable getSubscriptionCallable() { + throw new UnsupportedOperationException("Not implemented: getSubscriptionCallable()"); + } + + public UnaryCallable updateSubscriptionCallable() { + throw new UnsupportedOperationException("Not implemented: updateSubscriptionCallable()"); + } + + public UnaryCallable + listSubscriptionsPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listSubscriptionsPagedCallable()"); + } + + public UnaryCallable + listSubscriptionsCallable() { + throw new UnsupportedOperationException("Not implemented: listSubscriptionsCallable()"); + } + + public UnaryCallable deleteSubscriptionCallable() { + throw new UnsupportedOperationException("Not implemented: deleteSubscriptionCallable()"); + } + + public UnaryCallable modifyAckDeadlineCallable() { + throw new UnsupportedOperationException("Not implemented: modifyAckDeadlineCallable()"); + } + + public UnaryCallable acknowledgeCallable() { + throw new UnsupportedOperationException("Not implemented: acknowledgeCallable()"); + } + + public UnaryCallable pullCallable() { + throw new UnsupportedOperationException("Not implemented: pullCallable()"); + } + + public BidiStreamingCallable + streamingPullCallable() { + throw new UnsupportedOperationException("Not implemented: streamingPullCallable()"); + } + + public UnaryCallable modifyPushConfigCallable() { + throw new UnsupportedOperationException("Not implemented: modifyPushConfigCallable()"); + } + + public UnaryCallable getSnapshotCallable() { + throw new UnsupportedOperationException("Not implemented: getSnapshotCallable()"); + } + + public UnaryCallable + listSnapshotsPagedCallable() { + throw new UnsupportedOperationException("Not implemented: listSnapshotsPagedCallable()"); + } + + public UnaryCallable listSnapshotsCallable() { + throw new UnsupportedOperationException("Not implemented: listSnapshotsCallable()"); + } + + public UnaryCallable createSnapshotCallable() { + throw new UnsupportedOperationException("Not implemented: createSnapshotCallable()"); + } + + public UnaryCallable updateSnapshotCallable() { + throw new UnsupportedOperationException("Not implemented: updateSnapshotCallable()"); + } + + public UnaryCallable deleteSnapshotCallable() { + throw new UnsupportedOperationException("Not implemented: deleteSnapshotCallable()"); + } + + public UnaryCallable seekCallable() { + throw new UnsupportedOperationException("Not implemented: seekCallable()"); + } + + public UnaryCallable setIamPolicyCallable() { + throw new UnsupportedOperationException("Not implemented: setIamPolicyCallable()"); + } + + public UnaryCallable getIamPolicyCallable() { + throw new UnsupportedOperationException("Not implemented: getIamPolicyCallable()"); + } + + public UnaryCallable + testIamPermissionsCallable() { + throw new UnsupportedOperationException("Not implemented: testIamPermissionsCallable()"); + } + + @Override + public abstract void close(); +} diff --git a/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SubscriberStubSettings.java b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SubscriberStubSettings.java new file mode 100644 index 0000000000..55101f5595 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/cloud/pubsub/v1/stub/SubscriberStubSettings.java @@ -0,0 +1,879 @@ +/* + * Copyright 2021 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.cloud.pubsub.v1.stub; + +import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSnapshotsPagedResponse; +import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSubscriptionsPagedResponse; + +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.StreamingCallSettings; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.Empty; +import com.google.pubsub.v1.AcknowledgeRequest; +import com.google.pubsub.v1.CreateSnapshotRequest; +import com.google.pubsub.v1.DeleteSnapshotRequest; +import com.google.pubsub.v1.DeleteSubscriptionRequest; +import com.google.pubsub.v1.GetSnapshotRequest; +import com.google.pubsub.v1.GetSubscriptionRequest; +import com.google.pubsub.v1.ListSnapshotsRequest; +import com.google.pubsub.v1.ListSnapshotsResponse; +import com.google.pubsub.v1.ListSubscriptionsRequest; +import com.google.pubsub.v1.ListSubscriptionsResponse; +import com.google.pubsub.v1.ModifyAckDeadlineRequest; +import com.google.pubsub.v1.ModifyPushConfigRequest; +import com.google.pubsub.v1.PullRequest; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.SeekRequest; +import com.google.pubsub.v1.SeekResponse; +import com.google.pubsub.v1.Snapshot; +import com.google.pubsub.v1.StreamingPullRequest; +import com.google.pubsub.v1.StreamingPullResponse; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.UpdateSnapshotRequest; +import com.google.pubsub.v1.UpdateSubscriptionRequest; +import java.io.IOException; +import java.util.List; +import javax.annotation.Generated; +import org.threeten.bp.Duration; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link SubscriberStub}. + * + *

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

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

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

For example, to set the total timeout of createSubscription to 30 seconds: + * + *

{@code
+ * SubscriberStubSettings.Builder subscriptionAdminSettingsBuilder =
+ *     SubscriberStubSettings.newBuilder();
+ * subscriptionAdminSettingsBuilder
+ *     .createSubscriptionSettings()
+ *     .setRetrySettings(
+ *         subscriptionAdminSettingsBuilder
+ *             .createSubscriptionSettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * SubscriberStubSettings subscriptionAdminSettings = subscriptionAdminSettingsBuilder.build();
+ * }
+ */ +@Generated("by gapic-generator-java") +public class SubscriberStubSettings extends StubSettings { + /** The default scopes of the service. */ + private static final ImmutableList DEFAULT_SERVICE_SCOPES = + ImmutableList.builder() + .add("https://www.googleapis.com/auth/cloud-platform") + .add("https://www.googleapis.com/auth/pubsub") + .build(); + + private final UnaryCallSettings createSubscriptionSettings; + private final UnaryCallSettings getSubscriptionSettings; + private final UnaryCallSettings + updateSubscriptionSettings; + private final PagedCallSettings< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> + listSubscriptionsSettings; + private final UnaryCallSettings deleteSubscriptionSettings; + private final UnaryCallSettings modifyAckDeadlineSettings; + private final UnaryCallSettings acknowledgeSettings; + private final UnaryCallSettings pullSettings; + private final StreamingCallSettings + streamingPullSettings; + private final UnaryCallSettings modifyPushConfigSettings; + private final UnaryCallSettings getSnapshotSettings; + private final PagedCallSettings< + ListSnapshotsRequest, ListSnapshotsResponse, ListSnapshotsPagedResponse> + listSnapshotsSettings; + private final UnaryCallSettings createSnapshotSettings; + private final UnaryCallSettings updateSnapshotSettings; + private final UnaryCallSettings deleteSnapshotSettings; + private final UnaryCallSettings seekSettings; + private final UnaryCallSettings setIamPolicySettings; + private final UnaryCallSettings getIamPolicySettings; + private final UnaryCallSettings + testIamPermissionsSettings; + + private static final PagedListDescriptor< + ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription> + LIST_SUBSCRIPTIONS_PAGE_STR_DESC = + new PagedListDescriptor< + ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription>() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListSubscriptionsRequest injectToken( + ListSubscriptionsRequest payload, String token) { + return ListSubscriptionsRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListSubscriptionsRequest injectPageSize( + ListSubscriptionsRequest payload, int pageSize) { + return ListSubscriptionsRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListSubscriptionsRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListSubscriptionsResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListSubscriptionsResponse payload) { + return payload.getSubscriptionsList() == null + ? ImmutableList.of() + : payload.getSubscriptionsList(); + } + }; + + private static final PagedListDescriptor + LIST_SNAPSHOTS_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public ListSnapshotsRequest injectToken(ListSnapshotsRequest payload, String token) { + return ListSnapshotsRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public ListSnapshotsRequest injectPageSize(ListSnapshotsRequest payload, int pageSize) { + return ListSnapshotsRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(ListSnapshotsRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(ListSnapshotsResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(ListSnapshotsResponse payload) { + return payload.getSnapshotsList() == null + ? ImmutableList.of() + : payload.getSnapshotsList(); + } + }; + + private static final PagedListResponseFactory< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> + LIST_SUBSCRIPTIONS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListSubscriptionsRequest, + ListSubscriptionsResponse, + ListSubscriptionsPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListSubscriptionsRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext + pageContext = + PageContext.create( + callable, LIST_SUBSCRIPTIONS_PAGE_STR_DESC, request, context); + return ListSubscriptionsPagedResponse.createAsync(pageContext, futureResponse); + } + }; + + private static final PagedListResponseFactory< + ListSnapshotsRequest, ListSnapshotsResponse, ListSnapshotsPagedResponse> + LIST_SNAPSHOTS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListSnapshotsRequest, ListSnapshotsResponse, ListSnapshotsPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + ListSnapshotsRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, LIST_SNAPSHOTS_PAGE_STR_DESC, request, context); + return ListSnapshotsPagedResponse.createAsync(pageContext, futureResponse); + } + }; + + /** Returns the object with the settings used for calls to createSubscription. */ + public UnaryCallSettings createSubscriptionSettings() { + return createSubscriptionSettings; + } + + /** Returns the object with the settings used for calls to getSubscription. */ + public UnaryCallSettings getSubscriptionSettings() { + return getSubscriptionSettings; + } + + /** Returns the object with the settings used for calls to updateSubscription. */ + public UnaryCallSettings updateSubscriptionSettings() { + return updateSubscriptionSettings; + } + + /** Returns the object with the settings used for calls to listSubscriptions. */ + public PagedCallSettings< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> + listSubscriptionsSettings() { + return listSubscriptionsSettings; + } + + /** Returns the object with the settings used for calls to deleteSubscription. */ + public UnaryCallSettings deleteSubscriptionSettings() { + return deleteSubscriptionSettings; + } + + /** Returns the object with the settings used for calls to modifyAckDeadline. */ + public UnaryCallSettings modifyAckDeadlineSettings() { + return modifyAckDeadlineSettings; + } + + /** Returns the object with the settings used for calls to acknowledge. */ + public UnaryCallSettings acknowledgeSettings() { + return acknowledgeSettings; + } + + /** Returns the object with the settings used for calls to pull. */ + public UnaryCallSettings pullSettings() { + return pullSettings; + } + + /** Returns the object with the settings used for calls to streamingPull. */ + public StreamingCallSettings + streamingPullSettings() { + return streamingPullSettings; + } + + /** Returns the object with the settings used for calls to modifyPushConfig. */ + public UnaryCallSettings modifyPushConfigSettings() { + return modifyPushConfigSettings; + } + + /** Returns the object with the settings used for calls to getSnapshot. */ + public UnaryCallSettings getSnapshotSettings() { + return getSnapshotSettings; + } + + /** Returns the object with the settings used for calls to listSnapshots. */ + public PagedCallSettings + listSnapshotsSettings() { + return listSnapshotsSettings; + } + + /** Returns the object with the settings used for calls to createSnapshot. */ + public UnaryCallSettings createSnapshotSettings() { + return createSnapshotSettings; + } + + /** Returns the object with the settings used for calls to updateSnapshot. */ + public UnaryCallSettings updateSnapshotSettings() { + return updateSnapshotSettings; + } + + /** Returns the object with the settings used for calls to deleteSnapshot. */ + public UnaryCallSettings deleteSnapshotSettings() { + return deleteSnapshotSettings; + } + + /** Returns the object with the settings used for calls to seek. */ + public UnaryCallSettings seekSettings() { + return seekSettings; + } + + /** Returns the object with the settings used for calls to setIamPolicy. */ + public UnaryCallSettings setIamPolicySettings() { + return setIamPolicySettings; + } + + /** Returns the object with the settings used for calls to getIamPolicy. */ + public UnaryCallSettings getIamPolicySettings() { + return getIamPolicySettings; + } + + /** Returns the object with the settings used for calls to testIamPermissions. */ + public UnaryCallSettings + testIamPermissionsSettings() { + return testIamPermissionsSettings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public SubscriberStub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(GrpcTransportChannel.getGrpcTransportName())) { + return GrpcSubscriberStub.create(this); + } + throw new UnsupportedOperationException( + String.format( + "Transport not supported: %s", getTransportChannelProvider().getTransportName())); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return InstantiatingExecutorProvider.newBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return "pubsub.googleapis.com:443"; + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return DEFAULT_SERVICE_SCOPES; + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return InstantiatingGrpcChannelProvider.newBuilder() + .setMaxInboundMessageSize(Integer.MAX_VALUE); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return defaultGrpcTransportProviderBuilder().build(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return ApiClientHeaderProvider.newBuilder() + .setGeneratedLibToken( + "gapic", GaxProperties.getLibraryVersion(SubscriberStubSettings.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 SubscriberStubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + + createSubscriptionSettings = settingsBuilder.createSubscriptionSettings().build(); + getSubscriptionSettings = settingsBuilder.getSubscriptionSettings().build(); + updateSubscriptionSettings = settingsBuilder.updateSubscriptionSettings().build(); + listSubscriptionsSettings = settingsBuilder.listSubscriptionsSettings().build(); + deleteSubscriptionSettings = settingsBuilder.deleteSubscriptionSettings().build(); + modifyAckDeadlineSettings = settingsBuilder.modifyAckDeadlineSettings().build(); + acknowledgeSettings = settingsBuilder.acknowledgeSettings().build(); + pullSettings = settingsBuilder.pullSettings().build(); + streamingPullSettings = settingsBuilder.streamingPullSettings().build(); + modifyPushConfigSettings = settingsBuilder.modifyPushConfigSettings().build(); + getSnapshotSettings = settingsBuilder.getSnapshotSettings().build(); + listSnapshotsSettings = settingsBuilder.listSnapshotsSettings().build(); + createSnapshotSettings = settingsBuilder.createSnapshotSettings().build(); + updateSnapshotSettings = settingsBuilder.updateSnapshotSettings().build(); + deleteSnapshotSettings = settingsBuilder.deleteSnapshotSettings().build(); + seekSettings = settingsBuilder.seekSettings().build(); + setIamPolicySettings = settingsBuilder.setIamPolicySettings().build(); + getIamPolicySettings = settingsBuilder.getIamPolicySettings().build(); + testIamPermissionsSettings = settingsBuilder.testIamPermissionsSettings().build(); + } + + /** Builder for SubscriberStubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final UnaryCallSettings.Builder createSubscriptionSettings; + private final UnaryCallSettings.Builder + getSubscriptionSettings; + private final UnaryCallSettings.Builder + updateSubscriptionSettings; + private final PagedCallSettings.Builder< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> + listSubscriptionsSettings; + private final UnaryCallSettings.Builder + deleteSubscriptionSettings; + private final UnaryCallSettings.Builder + modifyAckDeadlineSettings; + private final UnaryCallSettings.Builder acknowledgeSettings; + private final UnaryCallSettings.Builder pullSettings; + private final StreamingCallSettings.Builder + streamingPullSettings; + private final UnaryCallSettings.Builder + modifyPushConfigSettings; + private final UnaryCallSettings.Builder getSnapshotSettings; + private final PagedCallSettings.Builder< + ListSnapshotsRequest, ListSnapshotsResponse, ListSnapshotsPagedResponse> + listSnapshotsSettings; + private final UnaryCallSettings.Builder createSnapshotSettings; + private final UnaryCallSettings.Builder updateSnapshotSettings; + private final UnaryCallSettings.Builder deleteSnapshotSettings; + private final UnaryCallSettings.Builder seekSettings; + private final UnaryCallSettings.Builder setIamPolicySettings; + private final UnaryCallSettings.Builder getIamPolicySettings; + private final UnaryCallSettings.Builder + testIamPermissionsSettings; + private static final ImmutableMap> + RETRYABLE_CODE_DEFINITIONS; + + static { + ImmutableMap.Builder> definitions = + ImmutableMap.builder(); + definitions.put( + "retry_policy_4_codes", + ImmutableSet.copyOf( + Lists.newArrayList( + StatusCode.Code.UNKNOWN, StatusCode.Code.ABORTED, StatusCode.Code.UNAVAILABLE))); + definitions.put( + "retry_policy_5_codes", + ImmutableSet.copyOf(Lists.newArrayList(StatusCode.Code.UNAVAILABLE))); + definitions.put( + "retry_policy_3_codes", + ImmutableSet.copyOf( + Lists.newArrayList( + StatusCode.Code.DEADLINE_EXCEEDED, + StatusCode.Code.RESOURCE_EXHAUSTED, + StatusCode.Code.ABORTED, + 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_4_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_5_params", settings); + settings = + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(100L)) + .setRetryDelayMultiplier(1.3) + .setMaxRetryDelay(Duration.ofMillis(60000L)) + .setInitialRpcTimeout(Duration.ofMillis(900000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(900000L)) + .setTotalTimeout(Duration.ofMillis(900000L)) + .build(); + definitions.put("retry_policy_3_params", settings); + RETRY_PARAM_DEFINITIONS = definitions.build(); + } + + protected Builder() { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(clientContext); + + createSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + getSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + updateSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + listSubscriptionsSettings = PagedCallSettings.newBuilder(LIST_SUBSCRIPTIONS_PAGE_STR_FACT); + deleteSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + modifyAckDeadlineSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + acknowledgeSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + pullSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + streamingPullSettings = StreamingCallSettings.newBuilder(); + modifyPushConfigSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + getSnapshotSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + listSnapshotsSettings = PagedCallSettings.newBuilder(LIST_SNAPSHOTS_PAGE_STR_FACT); + createSnapshotSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + updateSnapshotSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + deleteSnapshotSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + seekSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + setIamPolicySettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + getIamPolicySettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + testIamPermissionsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + createSubscriptionSettings, + getSubscriptionSettings, + updateSubscriptionSettings, + listSubscriptionsSettings, + deleteSubscriptionSettings, + modifyAckDeadlineSettings, + acknowledgeSettings, + pullSettings, + modifyPushConfigSettings, + getSnapshotSettings, + listSnapshotsSettings, + createSnapshotSettings, + updateSnapshotSettings, + deleteSnapshotSettings, + seekSettings, + setIamPolicySettings, + getIamPolicySettings, + testIamPermissionsSettings); + initDefaults(this); + } + + protected Builder(SubscriberStubSettings settings) { + super(settings); + + createSubscriptionSettings = settings.createSubscriptionSettings.toBuilder(); + getSubscriptionSettings = settings.getSubscriptionSettings.toBuilder(); + updateSubscriptionSettings = settings.updateSubscriptionSettings.toBuilder(); + listSubscriptionsSettings = settings.listSubscriptionsSettings.toBuilder(); + deleteSubscriptionSettings = settings.deleteSubscriptionSettings.toBuilder(); + modifyAckDeadlineSettings = settings.modifyAckDeadlineSettings.toBuilder(); + acknowledgeSettings = settings.acknowledgeSettings.toBuilder(); + pullSettings = settings.pullSettings.toBuilder(); + streamingPullSettings = settings.streamingPullSettings.toBuilder(); + modifyPushConfigSettings = settings.modifyPushConfigSettings.toBuilder(); + getSnapshotSettings = settings.getSnapshotSettings.toBuilder(); + listSnapshotsSettings = settings.listSnapshotsSettings.toBuilder(); + createSnapshotSettings = settings.createSnapshotSettings.toBuilder(); + updateSnapshotSettings = settings.updateSnapshotSettings.toBuilder(); + deleteSnapshotSettings = settings.deleteSnapshotSettings.toBuilder(); + seekSettings = settings.seekSettings.toBuilder(); + setIamPolicySettings = settings.setIamPolicySettings.toBuilder(); + getIamPolicySettings = settings.getIamPolicySettings.toBuilder(); + testIamPermissionsSettings = settings.testIamPermissionsSettings.toBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + createSubscriptionSettings, + getSubscriptionSettings, + updateSubscriptionSettings, + listSubscriptionsSettings, + deleteSubscriptionSettings, + modifyAckDeadlineSettings, + acknowledgeSettings, + pullSettings, + modifyPushConfigSettings, + getSnapshotSettings, + listSnapshotsSettings, + createSnapshotSettings, + updateSnapshotSettings, + deleteSnapshotSettings, + seekSettings, + setIamPolicySettings, + getIamPolicySettings, + testIamPermissionsSettings); + } + + 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 + .createSubscriptionSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_4_params")); + + builder + .getSubscriptionSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_4_params")); + + builder + .updateSubscriptionSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .listSubscriptionsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_4_params")); + + builder + .deleteSubscriptionSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .modifyAckDeadlineSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .acknowledgeSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .pullSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_4_params")); + + builder + .modifyPushConfigSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .getSnapshotSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_4_params")); + + builder + .listSnapshotsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_4_params")); + + builder + .createSnapshotSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .updateSnapshotSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .deleteSnapshotSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .seekSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_4_params")); + + builder + .setIamPolicySettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_5_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_5_params")); + + builder + .getIamPolicySettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_4_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_4_params")); + + builder + .testIamPermissionsSettings() + .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 createSubscription. */ + public UnaryCallSettings.Builder createSubscriptionSettings() { + return createSubscriptionSettings; + } + + /** Returns the builder for the settings used for calls to getSubscription. */ + public UnaryCallSettings.Builder + getSubscriptionSettings() { + return getSubscriptionSettings; + } + + /** Returns the builder for the settings used for calls to updateSubscription. */ + public UnaryCallSettings.Builder + updateSubscriptionSettings() { + return updateSubscriptionSettings; + } + + /** Returns the builder for the settings used for calls to listSubscriptions. */ + public PagedCallSettings.Builder< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> + listSubscriptionsSettings() { + return listSubscriptionsSettings; + } + + /** Returns the builder for the settings used for calls to deleteSubscription. */ + public UnaryCallSettings.Builder + deleteSubscriptionSettings() { + return deleteSubscriptionSettings; + } + + /** Returns the builder for the settings used for calls to modifyAckDeadline. */ + public UnaryCallSettings.Builder modifyAckDeadlineSettings() { + return modifyAckDeadlineSettings; + } + + /** Returns the builder for the settings used for calls to acknowledge. */ + public UnaryCallSettings.Builder acknowledgeSettings() { + return acknowledgeSettings; + } + + /** Returns the builder for the settings used for calls to pull. */ + public UnaryCallSettings.Builder pullSettings() { + return pullSettings; + } + + /** Returns the builder for the settings used for calls to streamingPull. */ + public StreamingCallSettings.Builder + streamingPullSettings() { + return streamingPullSettings; + } + + /** Returns the builder for the settings used for calls to modifyPushConfig. */ + public UnaryCallSettings.Builder modifyPushConfigSettings() { + return modifyPushConfigSettings; + } + + /** Returns the builder for the settings used for calls to getSnapshot. */ + public UnaryCallSettings.Builder getSnapshotSettings() { + return getSnapshotSettings; + } + + /** Returns the builder for the settings used for calls to listSnapshots. */ + public PagedCallSettings.Builder< + ListSnapshotsRequest, ListSnapshotsResponse, ListSnapshotsPagedResponse> + listSnapshotsSettings() { + return listSnapshotsSettings; + } + + /** Returns the builder for the settings used for calls to createSnapshot. */ + public UnaryCallSettings.Builder createSnapshotSettings() { + return createSnapshotSettings; + } + + /** Returns the builder for the settings used for calls to updateSnapshot. */ + public UnaryCallSettings.Builder updateSnapshotSettings() { + return updateSnapshotSettings; + } + + /** Returns the builder for the settings used for calls to deleteSnapshot. */ + public UnaryCallSettings.Builder deleteSnapshotSettings() { + return deleteSnapshotSettings; + } + + /** Returns the builder for the settings used for calls to seek. */ + public UnaryCallSettings.Builder seekSettings() { + return seekSettings; + } + + /** Returns the builder for the settings used for calls to setIamPolicy. */ + public UnaryCallSettings.Builder setIamPolicySettings() { + return setIamPolicySettings; + } + + /** Returns the builder for the settings used for calls to getIamPolicy. */ + public UnaryCallSettings.Builder getIamPolicySettings() { + return getIamPolicySettings; + } + + /** Returns the builder for the settings used for calls to testIamPermissions. */ + public UnaryCallSettings.Builder + testIamPermissionsSettings() { + return testIamPermissionsSettings; + } + + @Override + public SubscriberStubSettings build() throws IOException { + return new SubscriberStubSettings(this); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/iam/v1/ProjectName.java b/test/integration/goldens/pubsub/com/google/iam/v1/ProjectName.java new file mode 100644 index 0000000000..21108a2658 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/iam/v1/ProjectName.java @@ -0,0 +1,168 @@ +/* + * Copyright 2021 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.iam.v1; + +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; + + @Deprecated + protected ProjectName() { + project = null; + } + + 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 (value == null) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (fieldValuesMap == null) { + synchronized (this) { + if (fieldValuesMap == null) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (project != null) { + 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; + + protected 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/pubsub/com/google/pubsub/v1/SchemaName.java b/test/integration/goldens/pubsub/com/google/pubsub/v1/SchemaName.java new file mode 100644 index 0000000000..275fce55e7 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/pubsub/v1/SchemaName.java @@ -0,0 +1,191 @@ +/* + * Copyright 2021 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.pubsub.v1; + +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 SchemaName implements ResourceName { + private static final PathTemplate PROJECT_SCHEMA = + PathTemplate.createWithoutUrlEncoding("projects/{project}/schemas/{schema}"); + private volatile Map fieldValuesMap; + private final String project; + private final String schema; + + @Deprecated + protected SchemaName() { + project = null; + schema = null; + } + + private SchemaName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + schema = Preconditions.checkNotNull(builder.getSchema()); + } + + public String getProject() { + return project; + } + + public String getSchema() { + return schema; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static SchemaName of(String project, String schema) { + return newBuilder().setProject(project).setSchema(schema).build(); + } + + public static String format(String project, String schema) { + return newBuilder().setProject(project).setSchema(schema).build().toString(); + } + + public static SchemaName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + PROJECT_SCHEMA.validatedMatch( + formattedString, "SchemaName.parse: formattedString not in valid format"); + return of(matchMap.get("project"), matchMap.get("schema")); + } + + 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 (SchemaName value : values) { + if (value == null) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_SCHEMA.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (fieldValuesMap == null) { + synchronized (this) { + if (fieldValuesMap == null) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (project != null) { + fieldMapBuilder.put("project", project); + } + if (schema != null) { + fieldMapBuilder.put("schema", schema); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return PROJECT_SCHEMA.instantiate("project", project, "schema", schema); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + SchemaName that = ((SchemaName) o); + return Objects.equals(this.project, that.project) && Objects.equals(this.schema, that.schema); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(schema); + return h; + } + + /** Builder for projects/{project}/schemas/{schema}. */ + public static class Builder { + private String project; + private String schema; + + protected Builder() {} + + public String getProject() { + return project; + } + + public String getSchema() { + return schema; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setSchema(String schema) { + this.schema = schema; + return this; + } + + private Builder(SchemaName schemaName) { + project = schemaName.project; + schema = schemaName.schema; + } + + public SchemaName build() { + return new SchemaName(this); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/pubsub/v1/SnapshotName.java b/test/integration/goldens/pubsub/com/google/pubsub/v1/SnapshotName.java new file mode 100644 index 0000000000..67cb2458e2 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/pubsub/v1/SnapshotName.java @@ -0,0 +1,192 @@ +/* + * Copyright 2021 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.pubsub.v1; + +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 SnapshotName implements ResourceName { + private static final PathTemplate PROJECT_SNAPSHOT = + PathTemplate.createWithoutUrlEncoding("projects/{project}/snapshots/{snapshot}"); + private volatile Map fieldValuesMap; + private final String project; + private final String snapshot; + + @Deprecated + protected SnapshotName() { + project = null; + snapshot = null; + } + + private SnapshotName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + snapshot = Preconditions.checkNotNull(builder.getSnapshot()); + } + + public String getProject() { + return project; + } + + public String getSnapshot() { + return snapshot; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static SnapshotName of(String project, String snapshot) { + return newBuilder().setProject(project).setSnapshot(snapshot).build(); + } + + public static String format(String project, String snapshot) { + return newBuilder().setProject(project).setSnapshot(snapshot).build().toString(); + } + + public static SnapshotName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + PROJECT_SNAPSHOT.validatedMatch( + formattedString, "SnapshotName.parse: formattedString not in valid format"); + return of(matchMap.get("project"), matchMap.get("snapshot")); + } + + 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 (SnapshotName value : values) { + if (value == null) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_SNAPSHOT.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (fieldValuesMap == null) { + synchronized (this) { + if (fieldValuesMap == null) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (project != null) { + fieldMapBuilder.put("project", project); + } + if (snapshot != null) { + fieldMapBuilder.put("snapshot", snapshot); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return PROJECT_SNAPSHOT.instantiate("project", project, "snapshot", snapshot); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + SnapshotName that = ((SnapshotName) o); + return Objects.equals(this.project, that.project) + && Objects.equals(this.snapshot, that.snapshot); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(snapshot); + return h; + } + + /** Builder for projects/{project}/snapshots/{snapshot}. */ + public static class Builder { + private String project; + private String snapshot; + + protected Builder() {} + + public String getProject() { + return project; + } + + public String getSnapshot() { + return snapshot; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setSnapshot(String snapshot) { + this.snapshot = snapshot; + return this; + } + + private Builder(SnapshotName snapshotName) { + project = snapshotName.project; + snapshot = snapshotName.snapshot; + } + + public SnapshotName build() { + return new SnapshotName(this); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/pubsub/v1/SubscriptionName.java b/test/integration/goldens/pubsub/com/google/pubsub/v1/SubscriptionName.java new file mode 100644 index 0000000000..50131e8b35 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/pubsub/v1/SubscriptionName.java @@ -0,0 +1,192 @@ +/* + * Copyright 2021 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.pubsub.v1; + +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 SubscriptionName implements ResourceName { + private static final PathTemplate PROJECT_SUBSCRIPTION = + PathTemplate.createWithoutUrlEncoding("projects/{project}/subscriptions/{subscription}"); + private volatile Map fieldValuesMap; + private final String project; + private final String subscription; + + @Deprecated + protected SubscriptionName() { + project = null; + subscription = null; + } + + private SubscriptionName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + subscription = Preconditions.checkNotNull(builder.getSubscription()); + } + + public String getProject() { + return project; + } + + public String getSubscription() { + return subscription; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static SubscriptionName of(String project, String subscription) { + return newBuilder().setProject(project).setSubscription(subscription).build(); + } + + public static String format(String project, String subscription) { + return newBuilder().setProject(project).setSubscription(subscription).build().toString(); + } + + public static SubscriptionName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + PROJECT_SUBSCRIPTION.validatedMatch( + formattedString, "SubscriptionName.parse: formattedString not in valid format"); + return of(matchMap.get("project"), matchMap.get("subscription")); + } + + 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 (SubscriptionName value : values) { + if (value == null) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_SUBSCRIPTION.matches(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (fieldValuesMap == null) { + synchronized (this) { + if (fieldValuesMap == null) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (project != null) { + fieldMapBuilder.put("project", project); + } + if (subscription != null) { + fieldMapBuilder.put("subscription", subscription); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return PROJECT_SUBSCRIPTION.instantiate("project", project, "subscription", subscription); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + SubscriptionName that = ((SubscriptionName) o); + return Objects.equals(this.project, that.project) + && Objects.equals(this.subscription, that.subscription); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(subscription); + return h; + } + + /** Builder for projects/{project}/subscriptions/{subscription}. */ + public static class Builder { + private String project; + private String subscription; + + protected Builder() {} + + public String getProject() { + return project; + } + + public String getSubscription() { + return subscription; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setSubscription(String subscription) { + this.subscription = subscription; + return this; + } + + private Builder(SubscriptionName subscriptionName) { + project = subscriptionName.project; + subscription = subscriptionName.subscription; + } + + public SubscriptionName build() { + return new SubscriptionName(this); + } + } +} diff --git a/test/integration/goldens/pubsub/com/google/pubsub/v1/TopicName.java b/test/integration/goldens/pubsub/com/google/pubsub/v1/TopicName.java new file mode 100644 index 0000000000..36d4289b67 --- /dev/null +++ b/test/integration/goldens/pubsub/com/google/pubsub/v1/TopicName.java @@ -0,0 +1,235 @@ +/* + * Copyright 2021 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.pubsub.v1; + +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 TopicName implements ResourceName { + private static final PathTemplate PROJECT_TOPIC = + PathTemplate.createWithoutUrlEncoding("projects/{project}/topics/{topic}"); + private static final String DELETED_TOPIC = "_deleted-topic_"; + private volatile Map fieldValuesMap; + private PathTemplate pathTemplate; + private String fixedValue; + private final String project; + private final String topic; + + @Deprecated + protected TopicName() { + project = null; + topic = null; + } + + private TopicName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + topic = Preconditions.checkNotNull(builder.getTopic()); + pathTemplate = PROJECT_TOPIC; + } + + private TopicName(String fixedValue) { + this.fixedValue = fixedValue; + fieldValuesMap = ImmutableMap.of("", fixedValue); + project = null; + topic = null; + } + + public String getProject() { + return project; + } + + public String getTopic() { + return topic; + } + + 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 newProjectTopicBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static TopicName of(String project, String topic) { + return newBuilder().setProject(project).setTopic(topic).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static TopicName ofProjectTopicName(String project, String topic) { + return newBuilder().setProject(project).setTopic(topic).build(); + } + + @BetaApi("The static create methods are not stable yet and may be changed in the future.") + public static TopicName ofDeletedTopicName() { + return new TopicName("_deleted-topic_"); + } + + public static String format(String project, String topic) { + return newBuilder().setProject(project).setTopic(topic).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatProjectTopicName(String project, String topic) { + return newBuilder().setProject(project).setTopic(topic).build().toString(); + } + + @BetaApi("The static format methods are not stable yet and may be changed in the future.") + public static String formatDeletedTopicName() { + return "_deleted-topic_"; + } + + public static TopicName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + if (PROJECT_TOPIC.matches(formattedString)) { + Map matchMap = PROJECT_TOPIC.match(formattedString); + return ofProjectTopicName(matchMap.get("project"), matchMap.get("topic")); + } else if (DELETED_TOPIC.equals(formattedString)) { + return new TopicName("_deleted-topic_"); + } + throw new ValidationException("TopicName.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 (TopicName value : values) { + if (value == null) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_TOPIC.matches(formattedString) || DELETED_TOPIC.equals(formattedString); + } + + @Override + public Map getFieldValuesMap() { + if (fieldValuesMap == null) { + synchronized (this) { + if (fieldValuesMap == null) { + ImmutableMap.Builder fieldMapBuilder = ImmutableMap.builder(); + if (project != null) { + fieldMapBuilder.put("project", project); + } + if (topic != null) { + fieldMapBuilder.put("topic", topic); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return fixedValue != null ? fixedValue : pathTemplate.instantiate(getFieldValuesMap()); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + TopicName that = ((TopicName) o); + return Objects.equals(this.project, that.project) && Objects.equals(this.topic, that.topic); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(topic); + return h; + } + + /** Builder for projects/{project}/topics/{topic}. */ + public static class Builder { + private String project; + private String topic; + + protected Builder() {} + + public String getProject() { + return project; + } + + public String getTopic() { + return topic; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setTopic(String topic) { + this.topic = topic; + return this; + } + + private Builder(TopicName topicName) { + Preconditions.checkArgument( + Objects.equals(topicName.pathTemplate, PROJECT_TOPIC), + "toBuilder is only supported when TopicName has the pattern of projects/{project}/topics/{topic}"); + project = topicName.project; + topic = topicName.topic; + } + + public TopicName build() { + return new TopicName(this); + } + } +} diff --git a/test/integration/pubsub_v1.yaml b/test/integration/pubsub_v1.yaml new file mode 100644 index 0000000000..d32afa39c6 --- /dev/null +++ b/test/integration/pubsub_v1.yaml @@ -0,0 +1,94 @@ +type: google.api.Service +config_version: 3 +name: pubsub.googleapis.com +title: Cloud Pub/Sub API + +apis: +- name: google.pubsub.v1.Publisher +- name: google.pubsub.v1.SchemaService +- name: google.pubsub.v1.Subscriber +- name: google.iam.v1.IAMPolicy + +documentation: + summary: |- + Provides reliable, many-to-many, asynchronous messaging between + applications. + rules: + - selector: google.iam.v1.IAMPolicy.GetIamPolicy + description: |- + Gets the access control policy for a resource. Returns an empty policy + if the resource exists and does not have a policy set. + + - selector: google.iam.v1.IAMPolicy.SetIamPolicy + description: |- + Sets the access control policy on the specified resource. Replaces + any existing policy. + + Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` + errors. + + - selector: google.iam.v1.IAMPolicy.TestIamPermissions + description: |- + Returns permissions that a caller has on the specified resource. If the + resource does not exist, this will return an empty set of + permissions, not a `NOT_FOUND` error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for authorization + checking. This operation may "fail open" without warning. + +backend: + rules: + - selector: 'google.pubsub.v1.Publisher.*' + deadline: 120.0 + - selector: google.pubsub.v1.Publisher.Publish + deadline: 20.0 + - selector: 'google.pubsub.v1.Subscriber.*' + deadline: 120.0 + +http: + rules: + - selector: google.iam.v1.IAMPolicy.GetIamPolicy + get: '/v1/{resource=projects/*/topics/*}:getIamPolicy' + additional_bindings: + - get: '/v1/{resource=projects/*/subscriptions/*}:getIamPolicy' + - get: '/v1/{resource=projects/*/snapshots/*}:getIamPolicy' + - selector: google.iam.v1.IAMPolicy.SetIamPolicy + post: '/v1/{resource=projects/*/topics/*}:setIamPolicy' + body: '*' + additional_bindings: + - post: '/v1/{resource=projects/*/subscriptions/*}:setIamPolicy' + body: '*' + - post: '/v1/{resource=projects/*/snapshots/*}:setIamPolicy' + body: '*' + - selector: google.iam.v1.IAMPolicy.TestIamPermissions + post: '/v1/{resource=projects/*/subscriptions/*}:testIamPermissions' + body: '*' + additional_bindings: + - post: '/v1/{resource=projects/*/topics/*}:testIamPermissions' + body: '*' + - post: '/v1/{resource=projects/*/snapshots/*}:testIamPermissions' + body: '*' + +authentication: + rules: + - selector: 'google.iam.v1.IAMPolicy.*' + oauth: + canonical_scopes: |- + https://www.googleapis.com/auth/cloud-platform, + https://www.googleapis.com/auth/pubsub + - selector: 'google.pubsub.v1.Publisher.*' + oauth: + canonical_scopes: |- + https://www.googleapis.com/auth/cloud-platform, + https://www.googleapis.com/auth/pubsub + - selector: 'google.pubsub.v1.SchemaService.*' + oauth: + canonical_scopes: |- + https://www.googleapis.com/auth/cloud-platform, + https://www.googleapis.com/auth/pubsub + - selector: 'google.pubsub.v1.Subscriber.*' + oauth: + canonical_scopes: |- + https://www.googleapis.com/auth/cloud-platform, + https://www.googleapis.com/auth/pubsub