diff --git a/gapic-generator-java/src/main/java/com/google/api/generator/gapic/composer/common/AbstractServiceStubSettingsClassComposer.java b/gapic-generator-java/src/main/java/com/google/api/generator/gapic/composer/common/AbstractServiceStubSettingsClassComposer.java index 88a3cc6ecd..c13bc5f3f1 100644 --- a/gapic-generator-java/src/main/java/com/google/api/generator/gapic/composer/common/AbstractServiceStubSettingsClassComposer.java +++ b/gapic-generator-java/src/main/java/com/google/api/generator/gapic/composer/common/AbstractServiceStubSettingsClassComposer.java @@ -370,6 +370,16 @@ protected MethodDefinition createApiClientHeaderProviderBuilderMethod( .setReturnType(returnType) .build(); + if (service.hasApiVersion()) { + + returnExpr = + MethodInvocationExpr.builder() + .setExprReferenceExpr(returnExpr) + .setMethodName("setApiVersionToken") + .setArguments(ValueExpr.withValue(StringObjectValue.withValue(service.apiVersion()))) + .setReturnType(returnType) + .build(); + } return MethodDefinition.builder() .setScope(ScopeNode.PUBLIC) .setIsStatic(true) diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpc/ServiceStubSettingsClassComposerTest.java b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpc/ServiceStubSettingsClassComposerTest.java index ff4f35bff7..bfce68a45a 100644 --- a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpc/ServiceStubSettingsClassComposerTest.java +++ b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpc/ServiceStubSettingsClassComposerTest.java @@ -54,6 +54,12 @@ public static Collection data() { GrpcTestProtoLoader.instance().parseDeprecatedService(), "localhost:7469", "v1" + }, + { + "ApiVersionTestingStubSettings", + GrpcTestProtoLoader.instance().parseApiVersionTesting(), + "localhost:7469", + "v1" } }); } diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpc/goldens/ApiVersionTestingStubSettings.golden b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpc/goldens/ApiVersionTestingStubSettings.golden new file mode 100644 index 0000000000..c67187cf5e --- /dev/null +++ b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpc/goldens/ApiVersionTestingStubSettings.golden @@ -0,0 +1,248 @@ +package com.google.api.version.test.stub; + +import com.google.api.core.ApiFunction; +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.ApiClientHeaderProvider; +import com.google.api.gax.rpc.ClientContext; +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.version.test.EchoRequest; +import com.google.api.version.test.EchoResponse; +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 java.io.IOException; +import java.util.List; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link EchoWithVersionStub}. + * + *

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

+ * + *

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 echoWithVersionMethod to 30 seconds: + * + *

{@code
+ * // This snippet has been automatically generated and should be regarded as a code template only.
+ * // It will require modifications to work:
+ * // - It may require correct/in-range values for request initialization.
+ * // - It may require specifying regional endpoints when creating the service client as shown in
+ * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
+ * EchoWithVersionStubSettings.Builder echoWithVersionSettingsBuilder =
+ *     EchoWithVersionStubSettings.newBuilder();
+ * echoWithVersionSettingsBuilder
+ *     .echoWithVersionMethodSettings()
+ *     .setRetrySettings(
+ *         echoWithVersionSettingsBuilder
+ *             .echoWithVersionMethodSettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * EchoWithVersionStubSettings echoWithVersionSettings = echoWithVersionSettingsBuilder.build();
+ * }
+ */ +@Generated("by gapic-generator-java") +public class EchoWithVersionStubSettings extends StubSettings { + /** The default scopes of the service. */ + private static final ImmutableList DEFAULT_SERVICE_SCOPES = + ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build(); + + private final UnaryCallSettings echoWithVersionMethodSettings; + + /** Returns the object with the settings used for calls to echoWithVersionMethod. */ + public UnaryCallSettings echoWithVersionMethodSettings() { + return echoWithVersionMethodSettings; + } + + public EchoWithVersionStub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(GrpcTransportChannel.getGrpcTransportName())) { + return GrpcEchoWithVersionStub.create(this); + } + throw new UnsupportedOperationException( + String.format( + "Transport not supported: %s", getTransportChannelProvider().getTransportName())); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return InstantiatingExecutorProvider.newBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return "localhost:7469"; + } + + /** Returns the default mTLS service endpoint. */ + public static String getDefaultMtlsEndpoint() { + return "localhost:7469"; + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return DEFAULT_SERVICE_SCOPES; + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return GoogleCredentialsProvider.newBuilder() + .setScopesToApply(DEFAULT_SERVICE_SCOPES) + .setUseJwtAccessWithScope(true); + } + + /** 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(); + } + + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return ApiClientHeaderProvider.newBuilder() + .setGeneratedLibToken( + "gapic", GaxProperties.getLibraryVersion(EchoWithVersionStubSettings.class)) + .setTransportToken(GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()) + .setApiVersionToken("fake_version"); + } + + /** 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 EchoWithVersionStubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + + echoWithVersionMethodSettings = settingsBuilder.echoWithVersionMethodSettings().build(); + } + + /** Builder for EchoWithVersionStubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final UnaryCallSettings.Builder + echoWithVersionMethodSettings; + 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); + + echoWithVersionMethodSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of(echoWithVersionMethodSettings); + initDefaults(this); + } + + protected Builder(EchoWithVersionStubSettings settings) { + super(settings); + + echoWithVersionMethodSettings = settings.echoWithVersionMethodSettings.toBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of(echoWithVersionMethodSettings); + } + + private static Builder createDefault() { + Builder builder = new Builder(((ClientContext) null)); + + builder.setTransportChannelProvider(defaultTransportChannelProvider()); + builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); + builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); + builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); + builder.setSwitchToMtlsEndpointAllowed(true); + + return initDefaults(builder); + } + + private static Builder initDefaults(Builder builder) { + builder + .echoWithVersionMethodSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + return builder; + } + + /** + * 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) { + super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); + return this; + } + + public ImmutableList> unaryMethodSettingsBuilders() { + return unaryMethodSettingsBuilders; + } + + /** Returns the builder for the settings used for calls to echoWithVersionMethod. */ + public UnaryCallSettings.Builder echoWithVersionMethodSettings() { + return echoWithVersionMethodSettings; + } + + @Override + public EchoWithVersionStubSettings build() throws IOException { + return new EchoWithVersionStubSettings(this); + } + } +} diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpc/goldens/samples/servicesettings/stub/SyncEchoWithVersionMethod.golden b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpc/goldens/samples/servicesettings/stub/SyncEchoWithVersionMethod.golden new file mode 100644 index 0000000000..fc298b28dc --- /dev/null +++ b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpc/goldens/samples/servicesettings/stub/SyncEchoWithVersionMethod.golden @@ -0,0 +1,49 @@ +/* + * Copyright 2024 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.api.version.test.stub.samples; + +// [START goldensample_generated_EchoWithVersionStubSettings_EchoWithVersionMethod_sync] +import com.google.api.version.test.stub.EchoWithVersionStubSettings; +import java.time.Duration; + +public class SyncEchoWithVersionMethod { + + public static void main(String[] args) throws Exception { + syncEchoWithVersionMethod(); + } + + public static void syncEchoWithVersionMethod() throws Exception { + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in + // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library + EchoWithVersionStubSettings.Builder echoWithVersionSettingsBuilder = + EchoWithVersionStubSettings.newBuilder(); + echoWithVersionSettingsBuilder + .echoWithVersionMethodSettings() + .setRetrySettings( + echoWithVersionSettingsBuilder + .echoWithVersionMethodSettings() + .getRetrySettings() + .toBuilder() + .setTotalTimeout(Duration.ofSeconds(30)) + .build()); + EchoWithVersionStubSettings echoWithVersionSettings = echoWithVersionSettingsBuilder.build(); + } +} +// [END goldensample_generated_EchoWithVersionStubSettings_EchoWithVersionMethod_sync] diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpcrest/ServiceStubSettingsClassComposerTest.java b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpcrest/ServiceStubSettingsClassComposerTest.java index 388fa54648..c9439d525f 100644 --- a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpcrest/ServiceStubSettingsClassComposerTest.java +++ b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpcrest/ServiceStubSettingsClassComposerTest.java @@ -23,37 +23,38 @@ import com.google.api.generator.test.protoloader.GrpcRestTestProtoLoader; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Collection; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +@RunWith(Parameterized.class) public class ServiceStubSettingsClassComposerTest { + @Parameterized.Parameters + public static Collection data() { + return Arrays.asList( + new Object[][] { + {"EchoStubSettings.golden", GrpcRestTestProtoLoader.instance().parseShowcaseEcho()}, + {"WickedStubSettings.golden", GrpcRestTestProtoLoader.instance().parseShowcaseWicked()} + }); + } + + @Parameterized.Parameter public String goldenFileName; + + @Parameterized.Parameter(1) + public GapicContext context; + @Test public void generateServiceClasses() { - GapicContext context = GrpcRestTestProtoLoader.instance().parseShowcaseEcho(); Service echoProtoService = context.services().get(0); GapicClass clazz = ServiceStubSettingsClassComposer.instance().generate(context, echoProtoService); JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - GoldenFileWriter.saveCodegenToFile(this.getClass(), "EchoStubSettings.golden", visitor.write()); - Path goldenFilePath = - Paths.get(GoldenFileWriter.getGoldenDir(this.getClass()), "EchoStubSettings.golden"); - Assert.assertCodeEquals(goldenFilePath, visitor.write()); - } - - @Test - public void generateServiceClassesWicked() { - GapicContext context = GrpcRestTestProtoLoader.instance().parseShowcaseWicked(); - Service wickedProtoService = context.services().get(0); - GapicClass clazz = - ServiceStubSettingsClassComposer.instance().generate(context, wickedProtoService); - - JavaWriterVisitor visitor = new JavaWriterVisitor(); - clazz.classDefinition().accept(visitor); - GoldenFileWriter.saveCodegenToFile( - this.getClass(), "WickedStubSettings.golden", visitor.write()); - Path goldenFilePath = - Paths.get(GoldenFileWriter.getGoldenDir(this.getClass()), "WickedStubSettings.golden"); + GoldenFileWriter.saveCodegenToFile(this.getClass(), goldenFileName, visitor.write()); + Path goldenFilePath = Paths.get(GoldenFileWriter.getGoldenDir(this.getClass()), goldenFileName); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpcrest/goldens/EchoStubSettings.golden b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpcrest/goldens/EchoStubSettings.golden index fefa7643ba..565f38a483 100644 --- a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpcrest/goldens/EchoStubSettings.golden +++ b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/grpcrest/goldens/EchoStubSettings.golden @@ -348,8 +348,8 @@ public class EchoStubSettings extends StubSettings { public static ApiClientHeaderProvider.Builder defaultGrpcApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(EchoStubSettings.class)) - .setTransportToken( - GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); + .setTransportToken(GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()) + .setApiVersionToken("foo_version_for_tests"); } public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() { @@ -357,7 +357,8 @@ public class EchoStubSettings extends StubSettings { .setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(EchoStubSettings.class)) .setTransportToken( GaxHttpJsonProperties.getHttpJsonTokenName(), - GaxHttpJsonProperties.getHttpJsonVersion()); + GaxHttpJsonProperties.getHttpJsonVersion()) + .setApiVersionToken("foo_version_for_tests"); } public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/rest/ServiceStubSettingsClassComposerTest.java b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/rest/ServiceStubSettingsClassComposerTest.java index 1869a893fe..d2ac3b813a 100644 --- a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/rest/ServiceStubSettingsClassComposerTest.java +++ b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/rest/ServiceStubSettingsClassComposerTest.java @@ -23,22 +23,41 @@ import com.google.api.generator.test.protoloader.RestTestProtoLoader; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Collection; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +@RunWith(Parameterized.class) public class ServiceStubSettingsClassComposerTest { + + @Parameterized.Parameters + public static Collection data() { + return Arrays.asList( + new Object[][] { + {"ComplianceStubSettings.golden", RestTestProtoLoader.instance().parseCompliance()}, + { + "HttpJsonApiVersionTestingStubSettings.golden", + RestTestProtoLoader.instance().parseApiVersionTesting() + } + }); + } + + @Parameterized.Parameter public String goldenFileName; + + @Parameterized.Parameter(1) + public GapicContext context; + @Test public void generateServiceClasses() { - GapicContext context = RestTestProtoLoader.instance().parseCompliance(); - Service echoProtoService = context.services().get(0); - GapicClass clazz = - ServiceStubSettingsClassComposer.instance().generate(context, echoProtoService); + Service protoService = context.services().get(0); + GapicClass clazz = ServiceStubSettingsClassComposer.instance().generate(context, protoService); JavaWriterVisitor visitor = new JavaWriterVisitor(); clazz.classDefinition().accept(visitor); - GoldenFileWriter.saveCodegenToFile( - this.getClass(), "ComplianceStubSettings.golden", visitor.write()); - Path goldenFilePath = - Paths.get(GoldenFileWriter.getGoldenDir(this.getClass()), "ComplianceStubSettings.golden"); + GoldenFileWriter.saveCodegenToFile(this.getClass(), goldenFileName, visitor.write()); + Path goldenFilePath = Paths.get(GoldenFileWriter.getGoldenDir(this.getClass()), goldenFileName); Assert.assertCodeEquals(goldenFilePath, visitor.write()); } } diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/rest/goldens/HttpJsonApiVersionTestingStubSettings.golden b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/rest/goldens/HttpJsonApiVersionTestingStubSettings.golden new file mode 100644 index 0000000000..219800efd4 --- /dev/null +++ b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/rest/goldens/HttpJsonApiVersionTestingStubSettings.golden @@ -0,0 +1,250 @@ +package com.google.api.version.test.stub; + +import com.google.api.core.ApiFunction; +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.httpjson.GaxHttpJsonProperties; +import com.google.api.gax.httpjson.HttpJsonTransportChannel; +import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.ClientContext; +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.version.test.EchoRequest; +import com.google.api.version.test.EchoResponse; +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 java.io.IOException; +import java.util.List; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link EchoWithVersionStub}. + * + *

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

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

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

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

{@code
+ * // This snippet has been automatically generated and should be regarded as a code template only.
+ * // It will require modifications to work:
+ * // - It may require correct/in-range values for request initialization.
+ * // - It may require specifying regional endpoints when creating the service client as shown in
+ * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
+ * EchoWithVersionStubSettings.Builder echoWithVersionSettingsBuilder =
+ *     EchoWithVersionStubSettings.newBuilder();
+ * echoWithVersionSettingsBuilder
+ *     .echoWithVersionMethodSettings()
+ *     .setRetrySettings(
+ *         echoWithVersionSettingsBuilder
+ *             .echoWithVersionMethodSettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * EchoWithVersionStubSettings echoWithVersionSettings = echoWithVersionSettingsBuilder.build();
+ * }
+ */ +@Generated("by gapic-generator-java") +public class EchoWithVersionStubSettings extends StubSettings { + /** The default scopes of the service. */ + private static final ImmutableList DEFAULT_SERVICE_SCOPES = + ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build(); + + private final UnaryCallSettings echoWithVersionMethodSettings; + + /** Returns the object with the settings used for calls to echoWithVersionMethod. */ + public UnaryCallSettings echoWithVersionMethodSettings() { + return echoWithVersionMethodSettings; + } + + public EchoWithVersionStub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(HttpJsonTransportChannel.getHttpJsonTransportName())) { + return HttpJsonEchoWithVersionStub.create(this); + } + throw new UnsupportedOperationException( + String.format( + "Transport not supported: %s", getTransportChannelProvider().getTransportName())); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return InstantiatingExecutorProvider.newBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return "localhost:7469"; + } + + /** Returns the default mTLS service endpoint. */ + public static String getDefaultMtlsEndpoint() { + return "localhost:7469"; + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return DEFAULT_SERVICE_SCOPES; + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return GoogleCredentialsProvider.newBuilder() + .setScopesToApply(DEFAULT_SERVICE_SCOPES) + .setUseJwtAccessWithScope(true); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingHttpJsonChannelProvider.Builder + defaultHttpJsonTransportProviderBuilder() { + return InstantiatingHttpJsonChannelProvider.newBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return defaultHttpJsonTransportProviderBuilder().build(); + } + + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return ApiClientHeaderProvider.newBuilder() + .setGeneratedLibToken( + "gapic", GaxProperties.getLibraryVersion(EchoWithVersionStubSettings.class)) + .setTransportToken( + GaxHttpJsonProperties.getHttpJsonTokenName(), + GaxHttpJsonProperties.getHttpJsonVersion()) + .setApiVersionToken("fake_version"); + } + + /** 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 EchoWithVersionStubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + + echoWithVersionMethodSettings = settingsBuilder.echoWithVersionMethodSettings().build(); + } + + /** Builder for EchoWithVersionStubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final UnaryCallSettings.Builder + echoWithVersionMethodSettings; + 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); + + echoWithVersionMethodSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of(echoWithVersionMethodSettings); + initDefaults(this); + } + + protected Builder(EchoWithVersionStubSettings settings) { + super(settings); + + echoWithVersionMethodSettings = settings.echoWithVersionMethodSettings.toBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of(echoWithVersionMethodSettings); + } + + private static Builder createDefault() { + Builder builder = new Builder(((ClientContext) null)); + + builder.setTransportChannelProvider(defaultTransportChannelProvider()); + builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); + builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); + builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); + builder.setSwitchToMtlsEndpointAllowed(true); + + return initDefaults(builder); + } + + private static Builder initDefaults(Builder builder) { + builder + .echoWithVersionMethodSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); + + return builder; + } + + /** + * 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) { + super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); + return this; + } + + public ImmutableList> unaryMethodSettingsBuilders() { + return unaryMethodSettingsBuilders; + } + + /** Returns the builder for the settings used for calls to echoWithVersionMethod. */ + public UnaryCallSettings.Builder echoWithVersionMethodSettings() { + return echoWithVersionMethodSettings; + } + + @Override + public EchoWithVersionStubSettings build() throws IOException { + return new EchoWithVersionStubSettings(this); + } + } +} diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/rest/goldens/HttpJsonEchoStubSettings.golden b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/rest/goldens/HttpJsonEchoStubSettings.golden new file mode 100644 index 0000000000..0c788d7ebd --- /dev/null +++ b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/composer/rest/goldens/HttpJsonEchoStubSettings.golden @@ -0,0 +1,635 @@ +package com.google.showcase.v1beta1.stub; + +import static com.google.showcase.v1beta1.EchoClient.PagedExpandPagedResponse; +import static com.google.showcase.v1beta1.EchoClient.SimplePagedExpandPagedResponse; + +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.httpjson.GaxHttpJsonProperties; +import com.google.api.gax.httpjson.HttpJsonTransportChannel; +import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider; +import com.google.api.gax.httpjson.ProtoOperationTransformers; +import com.google.api.gax.longrunning.OperationSnapshot; +import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiCallContext; +import com.google.api.gax.rpc.ApiClientHeaderProvider; +import com.google.api.gax.rpc.ClientContext; +import com.google.api.gax.rpc.OperationCallSettings; +import com.google.api.gax.rpc.PageContext; +import com.google.api.gax.rpc.PagedCallSettings; +import com.google.api.gax.rpc.PagedListDescriptor; +import com.google.api.gax.rpc.PagedListResponseFactory; +import com.google.api.gax.rpc.ServerStreamingCallSettings; +import com.google.api.gax.rpc.StatusCode; +import com.google.api.gax.rpc.StreamingCallSettings; +import com.google.api.gax.rpc.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.longrunning.Operation; +import com.google.showcase.v1beta1.BlockRequest; +import com.google.showcase.v1beta1.BlockResponse; +import com.google.showcase.v1beta1.EchoRequest; +import com.google.showcase.v1beta1.EchoResponse; +import com.google.showcase.v1beta1.ExpandRequest; +import com.google.showcase.v1beta1.Object; +import com.google.showcase.v1beta1.PagedExpandRequest; +import com.google.showcase.v1beta1.PagedExpandResponse; +import com.google.showcase.v1beta1.WaitMetadata; +import com.google.showcase.v1beta1.WaitRequest; +import com.google.showcase.v1beta1.WaitResponse; +import java.io.IOException; +import java.util.List; +import javax.annotation.Generated; +import org.threeten.bp.Duration; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link EchoStub}. + * + *

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

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

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

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

{@code
+ * // This snippet has been automatically generated and should be regarded as a code template only.
+ * // It will require modifications to work:
+ * // - It may require correct/in-range values for request initialization.
+ * // - It may require specifying regional endpoints when creating the service client as shown in
+ * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
+ * EchoStubSettings.Builder echoSettingsBuilder = EchoStubSettings.newBuilder();
+ * echoSettingsBuilder
+ *     .echoSettings()
+ *     .setRetrySettings(
+ *         echoSettingsBuilder
+ *             .echoSettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * EchoStubSettings echoSettings = echoSettingsBuilder.build();
+ * }
+ */ +@BetaApi +@Generated("by gapic-generator-java") +public class EchoStubSettings extends StubSettings { + /** The default scopes of the service. */ + private static final ImmutableList DEFAULT_SERVICE_SCOPES = + ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build(); + + private final UnaryCallSettings echoSettings; + private final ServerStreamingCallSettings expandSettings; + private final StreamingCallSettings collectSettings; + private final StreamingCallSettings chatSettings; + private final StreamingCallSettings chatAgainSettings; + private final PagedCallSettings + pagedExpandSettings; + private final PagedCallSettings< + PagedExpandRequest, PagedExpandResponse, SimplePagedExpandPagedResponse> + simplePagedExpandSettings; + private final UnaryCallSettings waitSettings; + private final OperationCallSettings + waitOperationSettings; + private final UnaryCallSettings blockSettings; + private final UnaryCallSettings collideNameSettings; + + private static final PagedListDescriptor + PAGED_EXPAND_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public PagedExpandRequest injectToken(PagedExpandRequest payload, String token) { + return PagedExpandRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public PagedExpandRequest injectPageSize(PagedExpandRequest payload, int pageSize) { + return PagedExpandRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(PagedExpandRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(PagedExpandResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(PagedExpandResponse payload) { + return payload.getResponsesList() == null + ? ImmutableList.of() + : payload.getResponsesList(); + } + }; + + private static final PagedListDescriptor + SIMPLE_PAGED_EXPAND_PAGE_STR_DESC = + new PagedListDescriptor() { + @Override + public String emptyToken() { + return ""; + } + + @Override + public PagedExpandRequest injectToken(PagedExpandRequest payload, String token) { + return PagedExpandRequest.newBuilder(payload).setPageToken(token).build(); + } + + @Override + public PagedExpandRequest injectPageSize(PagedExpandRequest payload, int pageSize) { + return PagedExpandRequest.newBuilder(payload).setPageSize(pageSize).build(); + } + + @Override + public Integer extractPageSize(PagedExpandRequest payload) { + return payload.getPageSize(); + } + + @Override + public String extractNextToken(PagedExpandResponse payload) { + return payload.getNextPageToken(); + } + + @Override + public Iterable extractResources(PagedExpandResponse payload) { + return payload.getResponsesList() == null + ? ImmutableList.of() + : payload.getResponsesList(); + } + }; + + private static final PagedListResponseFactory< + PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse> + PAGED_EXPAND_PAGE_STR_FACT = + new PagedListResponseFactory< + PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + PagedExpandRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, PAGED_EXPAND_PAGE_STR_DESC, request, context); + return PagedExpandPagedResponse.createAsync(pageContext, futureResponse); + } + }; + + private static final PagedListResponseFactory< + PagedExpandRequest, PagedExpandResponse, SimplePagedExpandPagedResponse> + SIMPLE_PAGED_EXPAND_PAGE_STR_FACT = + new PagedListResponseFactory< + PagedExpandRequest, PagedExpandResponse, SimplePagedExpandPagedResponse>() { + @Override + public ApiFuture getFuturePagedResponse( + UnaryCallable callable, + PagedExpandRequest request, + ApiCallContext context, + ApiFuture futureResponse) { + PageContext pageContext = + PageContext.create(callable, SIMPLE_PAGED_EXPAND_PAGE_STR_DESC, request, context); + return SimplePagedExpandPagedResponse.createAsync(pageContext, futureResponse); + } + }; + + /** Returns the object with the settings used for calls to echo. */ + public UnaryCallSettings echoSettings() { + return echoSettings; + } + + /** Returns the object with the settings used for calls to expand. */ + public ServerStreamingCallSettings expandSettings() { + return expandSettings; + } + + /** Returns the object with the settings used for calls to collect. */ + public StreamingCallSettings collectSettings() { + return collectSettings; + } + + /** Returns the object with the settings used for calls to chat. */ + public StreamingCallSettings chatSettings() { + return chatSettings; + } + + /** Returns the object with the settings used for calls to chatAgain. */ + public StreamingCallSettings chatAgainSettings() { + return chatAgainSettings; + } + + /** Returns the object with the settings used for calls to pagedExpand. */ + public PagedCallSettings + pagedExpandSettings() { + return pagedExpandSettings; + } + + /** Returns the object with the settings used for calls to simplePagedExpand. */ + public PagedCallSettings + simplePagedExpandSettings() { + return simplePagedExpandSettings; + } + + /** Returns the object with the settings used for calls to wait. */ + public UnaryCallSettings waitSettings() { + return waitSettings; + } + + /** Returns the object with the settings used for calls to wait. */ + public OperationCallSettings waitOperationSettings() { + return waitOperationSettings; + } + + /** Returns the object with the settings used for calls to block. */ + public UnaryCallSettings blockSettings() { + return blockSettings; + } + + /** Returns the object with the settings used for calls to collideName. */ + public UnaryCallSettings collideNameSettings() { + return collideNameSettings; + } + + public EchoStub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(HttpJsonTransportChannel.getHttpJsonTransportName())) { + return HttpJsonEchoStub.create(this); + } + throw new UnsupportedOperationException( + String.format( + "Transport not supported: %s", getTransportChannelProvider().getTransportName())); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return InstantiatingExecutorProvider.newBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return "localhost:7469"; + } + + /** Returns the default mTLS service endpoint. */ + public static String getDefaultMtlsEndpoint() { + return "localhost:7469"; + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return DEFAULT_SERVICE_SCOPES; + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return GoogleCredentialsProvider.newBuilder() + .setScopesToApply(DEFAULT_SERVICE_SCOPES) + .setUseJwtAccessWithScope(true); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingHttpJsonChannelProvider.Builder + defaultHttpJsonTransportProviderBuilder() { + return InstantiatingHttpJsonChannelProvider.newBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return defaultHttpJsonTransportProviderBuilder().build(); + } + + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return ApiClientHeaderProvider.newBuilder() + .setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(EchoStubSettings.class)) + .setTransportToken( + GaxHttpJsonProperties.getHttpJsonTokenName(), + GaxHttpJsonProperties.getHttpJsonVersion()); + } + + /** Returns a new builder for this class. */ + public static Builder newBuilder() { + return Builder.createDefault(); + } + + /** Returns a new builder for this class. */ + public static Builder newBuilder(ClientContext clientContext) { + return new Builder(clientContext); + } + + /** Returns a builder containing all the values of this settings class. */ + public Builder toBuilder() { + return new Builder(this); + } + + protected EchoStubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + + echoSettings = settingsBuilder.echoSettings().build(); + expandSettings = settingsBuilder.expandSettings().build(); + collectSettings = settingsBuilder.collectSettings().build(); + chatSettings = settingsBuilder.chatSettings().build(); + chatAgainSettings = settingsBuilder.chatAgainSettings().build(); + pagedExpandSettings = settingsBuilder.pagedExpandSettings().build(); + simplePagedExpandSettings = settingsBuilder.simplePagedExpandSettings().build(); + waitSettings = settingsBuilder.waitSettings().build(); + waitOperationSettings = settingsBuilder.waitOperationSettings().build(); + blockSettings = settingsBuilder.blockSettings().build(); + collideNameSettings = settingsBuilder.collideNameSettings().build(); + } + + /** Builder for EchoStubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final UnaryCallSettings.Builder echoSettings; + private final ServerStreamingCallSettings.Builder expandSettings; + private final StreamingCallSettings.Builder collectSettings; + private final StreamingCallSettings.Builder chatSettings; + private final StreamingCallSettings.Builder chatAgainSettings; + private final PagedCallSettings.Builder< + PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse> + pagedExpandSettings; + private final PagedCallSettings.Builder< + PagedExpandRequest, PagedExpandResponse, SimplePagedExpandPagedResponse> + simplePagedExpandSettings; + private final UnaryCallSettings.Builder waitSettings; + private final OperationCallSettings.Builder + waitOperationSettings; + private final UnaryCallSettings.Builder blockSettings; + private final UnaryCallSettings.Builder collideNameSettings; + private static final ImmutableMap> + RETRYABLE_CODE_DEFINITIONS; + + static { + ImmutableMap.Builder> definitions = + ImmutableMap.builder(); + definitions.put( + "retry_policy_1_codes", + ImmutableSet.copyOf( + Lists.newArrayList( + StatusCode.Code.UNAVAILABLE, StatusCode.Code.UNKNOWN))); + definitions.put( + "no_retry_0_codes", ImmutableSet.copyOf(Lists.newArrayList())); + RETRYABLE_CODE_DEFINITIONS = definitions.build(); + } + + private static final ImmutableMap RETRY_PARAM_DEFINITIONS; + + static { + ImmutableMap.Builder definitions = ImmutableMap.builder(); + RetrySettings settings = null; + settings = + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(100L)) + .setRetryDelayMultiplier(2.0) + .setMaxRetryDelay(Duration.ofMillis(3000L)) + .setInitialRpcTimeout(Duration.ofMillis(10000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(10000L)) + .setTotalTimeout(Duration.ofMillis(10000L)) + .build(); + definitions.put("retry_policy_1_params", settings); + settings = + RetrySettings.newBuilder() + .setInitialRpcTimeout(Duration.ofMillis(5000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(5000L)) + .setTotalTimeout(Duration.ofMillis(5000L)) + .build(); + definitions.put("no_retry_0_params", settings); + RETRY_PARAM_DEFINITIONS = definitions.build(); + } + + protected Builder() { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(clientContext); + + echoSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + expandSettings = ServerStreamingCallSettings.newBuilder(); + collectSettings = StreamingCallSettings.newBuilder(); + chatSettings = StreamingCallSettings.newBuilder(); + chatAgainSettings = StreamingCallSettings.newBuilder(); + pagedExpandSettings = PagedCallSettings.newBuilder(PAGED_EXPAND_PAGE_STR_FACT); + simplePagedExpandSettings = PagedCallSettings.newBuilder(SIMPLE_PAGED_EXPAND_PAGE_STR_FACT); + waitSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + waitOperationSettings = OperationCallSettings.newBuilder(); + blockSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + collideNameSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + echoSettings, + pagedExpandSettings, + simplePagedExpandSettings, + waitSettings, + blockSettings, + collideNameSettings); + initDefaults(this); + } + + protected Builder(EchoStubSettings settings) { + super(settings); + + echoSettings = settings.echoSettings.toBuilder(); + expandSettings = settings.expandSettings.toBuilder(); + collectSettings = settings.collectSettings.toBuilder(); + chatSettings = settings.chatSettings.toBuilder(); + chatAgainSettings = settings.chatAgainSettings.toBuilder(); + pagedExpandSettings = settings.pagedExpandSettings.toBuilder(); + simplePagedExpandSettings = settings.simplePagedExpandSettings.toBuilder(); + waitSettings = settings.waitSettings.toBuilder(); + waitOperationSettings = settings.waitOperationSettings.toBuilder(); + blockSettings = settings.blockSettings.toBuilder(); + collideNameSettings = settings.collideNameSettings.toBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + echoSettings, + pagedExpandSettings, + simplePagedExpandSettings, + waitSettings, + blockSettings, + collideNameSettings); + } + + private static Builder createDefault() { + Builder builder = new Builder(((ClientContext) null)); + + builder.setTransportChannelProvider(defaultTransportChannelProvider()); + builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); + builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); + builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); + builder.setSwitchToMtlsEndpointAllowed(true); + + return initDefaults(builder); + } + + private static Builder initDefaults(Builder builder) { + builder + .echoSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + + builder + .expandSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + + builder + .pagedExpandSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); + + builder + .simplePagedExpandSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); + + builder + .waitSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); + + builder + .blockSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); + + builder + .collideNameSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); + + builder + .waitOperationSettings() + .setInitialCallSettings( + UnaryCallSettings.newUnaryCallSettingsBuilder() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")) + .build()) + .setResponseTransformer( + ProtoOperationTransformers.ResponseTransformer.create(WaitResponse.class)) + .setMetadataTransformer( + ProtoOperationTransformers.MetadataTransformer.create(WaitMetadata.class)) + .setPollingAlgorithm( + OperationTimedPollAlgorithm.create( + RetrySettings.newBuilder() + .setInitialRetryDelay(Duration.ofMillis(5000L)) + .setRetryDelayMultiplier(1.5) + .setMaxRetryDelay(Duration.ofMillis(45000L)) + .setInitialRpcTimeout(Duration.ZERO) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ZERO) + .setTotalTimeout(Duration.ofMillis(300000L)) + .build())); + + return builder; + } + + /** + * 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) { + super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); + return this; + } + + public ImmutableList> unaryMethodSettingsBuilders() { + return unaryMethodSettingsBuilders; + } + + /** Returns the builder for the settings used for calls to echo. */ + public UnaryCallSettings.Builder echoSettings() { + return echoSettings; + } + + /** Returns the builder for the settings used for calls to expand. */ + public ServerStreamingCallSettings.Builder expandSettings() { + return expandSettings; + } + + /** Returns the builder for the settings used for calls to collect. */ + public StreamingCallSettings.Builder collectSettings() { + return collectSettings; + } + + /** Returns the builder for the settings used for calls to chat. */ + public StreamingCallSettings.Builder chatSettings() { + return chatSettings; + } + + /** Returns the builder for the settings used for calls to chatAgain. */ + public StreamingCallSettings.Builder chatAgainSettings() { + return chatAgainSettings; + } + + /** Returns the builder for the settings used for calls to pagedExpand. */ + public PagedCallSettings.Builder< + PagedExpandRequest, PagedExpandResponse, PagedExpandPagedResponse> + pagedExpandSettings() { + return pagedExpandSettings; + } + + /** Returns the builder for the settings used for calls to simplePagedExpand. */ + public PagedCallSettings.Builder< + PagedExpandRequest, PagedExpandResponse, SimplePagedExpandPagedResponse> + simplePagedExpandSettings() { + return simplePagedExpandSettings; + } + + /** Returns the builder for the settings used for calls to wait. */ + public UnaryCallSettings.Builder waitSettings() { + return waitSettings; + } + + /** Returns the builder for the settings used for calls to wait. */ + public OperationCallSettings.Builder + waitOperationSettings() { + return waitOperationSettings; + } + + /** Returns the builder for the settings used for calls to block. */ + public UnaryCallSettings.Builder blockSettings() { + return blockSettings; + } + + /** Returns the builder for the settings used for calls to collideName. */ + public UnaryCallSettings.Builder collideNameSettings() { + return collideNameSettings; + } + + @Override + public EchoStubSettings build() throws IOException { + return new EchoStubSettings(this); + } + } +} diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/protoparser/ParserTest.java b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/protoparser/ParserTest.java index 42462dd1c8..f06c464055 100644 --- a/gapic-generator-java/src/test/java/com/google/api/generator/gapic/protoparser/ParserTest.java +++ b/gapic-generator-java/src/test/java/com/google/api/generator/gapic/protoparser/ParserTest.java @@ -623,7 +623,7 @@ public void parseServiceApiVersionTest() { new HashSet<>()); com.google.api.generator.gapic.model.Service parsedEchoService = services.get(0); - assertEquals("Echo", parsedEchoService.overriddenName()); + assertEquals("EchoWithVersion", parsedEchoService.overriddenName()); assertTrue(parsedEchoService.hasApiVersion()); assertEquals("fake_version", parsedEchoService.apiVersion()); } diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/test/protoloader/RestTestProtoLoader.java b/gapic-generator-java/src/test/java/com/google/api/generator/test/protoloader/RestTestProtoLoader.java index 20d64c7b3a..63938fcaad 100644 --- a/gapic-generator-java/src/test/java/com/google/api/generator/test/protoloader/RestTestProtoLoader.java +++ b/gapic-generator-java/src/test/java/com/google/api/generator/test/protoloader/RestTestProtoLoader.java @@ -15,6 +15,7 @@ package com.google.api.generator.test.protoloader; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertEquals; import com.google.api.generator.gapic.model.GapicContext; import com.google.api.generator.gapic.model.GapicServiceConfig; @@ -25,6 +26,7 @@ import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.gapic.protoparser.ServiceConfigParser; import com.google.api.generator.gapic.protoparser.ServiceYamlParser; +import com.google.api.version.test.ApiVersionTestingOuterClass; import com.google.longrunning.OperationsProto; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; @@ -121,4 +123,37 @@ public GapicContext parseEcho() { .setRestNumericEnumsEnabled(true) .build(); } + + public GapicContext parseApiVersionTesting() { + FileDescriptor testingFileDescriptor = ApiVersionTestingOuterClass.getDescriptor(); + ServiceDescriptor testingService = testingFileDescriptor.getServices().get(0); + assertEquals(testingService.getName(), "EchoWithVersion"); + + Map messageTypes = Parser.parseMessages(testingFileDescriptor); + Map resourceNames = Parser.parseResourceNames(testingFileDescriptor); + Set outputResourceNames = new HashSet<>(); + List services = + Parser.parseService( + testingFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); + + String jsonFilename = "showcase_grpc_service_config.json"; + Path jsonPath = Paths.get(getTestFilesDirectory(), jsonFilename); + Optional configOpt = ServiceConfigParser.parse(jsonPath.toString()); + assertThat(configOpt.isPresent()).isTrue(); + GapicServiceConfig config = configOpt.get(); + + return GapicContext.builder() + .setMessages(messageTypes) + .setResourceNames(resourceNames) + .setServices(services) + .setServiceConfig(config) + .setHelperResourceNames(outputResourceNames) + .setTransport(getTransport()) + .setRestNumericEnumsEnabled(true) + .build(); + } } diff --git a/gapic-generator-java/src/test/java/com/google/api/generator/test/protoloader/TestProtoLoader.java b/gapic-generator-java/src/test/java/com/google/api/generator/test/protoloader/TestProtoLoader.java index d5e62ddf70..db9efd06ca 100644 --- a/gapic-generator-java/src/test/java/com/google/api/generator/test/protoloader/TestProtoLoader.java +++ b/gapic-generator-java/src/test/java/com/google/api/generator/test/protoloader/TestProtoLoader.java @@ -28,6 +28,7 @@ import com.google.api.generator.gapic.protoparser.Parser; import com.google.api.generator.gapic.protoparser.ServiceConfigParser; import com.google.api.generator.gapic.protoparser.ServiceYamlParser; +import com.google.api.version.test.ApiVersionTestingOuterClass; import com.google.auto.populate.field.AutoPopulateFieldTestingOuterClass; import com.google.bookshop.v1beta1.BookshopProto; import com.google.explicit.dynamic.routing.header.ExplicitDynamicRoutingHeaderTestingOuterClass; @@ -293,6 +294,37 @@ public GapicContext parseExplicitDynamicRoutingHeaderTesting() { .build(); } + public GapicContext parseApiVersionTesting() { + FileDescriptor testingFileDescriptor = ApiVersionTestingOuterClass.getDescriptor(); + ServiceDescriptor testingService = testingFileDescriptor.getServices().get(0); + assertEquals(testingService.getName(), "EchoWithVersion"); + + Map messageTypes = Parser.parseMessages(testingFileDescriptor); + Map resourceNames = Parser.parseResourceNames(testingFileDescriptor); + Set outputResourceNames = new HashSet<>(); + List services = + Parser.parseService( + testingFileDescriptor, + messageTypes, + resourceNames, + Optional.empty(), + outputResourceNames); + String jsonFilename = "showcase_grpc_service_config.json"; + Path jsonPath = Paths.get(testFilesDirectory, jsonFilename); + Optional configOpt = ServiceConfigParser.parse(jsonPath.toString()); + assertTrue(configOpt.isPresent()); + GapicServiceConfig config = configOpt.get(); + + return GapicContext.builder() + .setMessages(messageTypes) + .setResourceNames(resourceNames) + .setServices(services) + .setServiceConfig(config) + .setHelperResourceNames(outputResourceNames) + .setTransport(transport) + .build(); + } + public GapicContext parseAutoPopulateFieldTesting() { FileDescriptor autopopulationFileDescriptor = AutoPopulateFieldTestingOuterClass.getDescriptor(); diff --git a/gapic-generator-java/src/test/proto/api_version_testing.proto b/gapic-generator-java/src/test/proto/api_version_testing.proto index 52c7b6bdd9..f815a7633e 100644 --- a/gapic-generator-java/src/test/proto/api_version_testing.proto +++ b/gapic-generator-java/src/test/proto/api_version_testing.proto @@ -24,7 +24,7 @@ import "google/protobuf/duration.proto"; import "google/protobuf/timestamp.proto"; import "google/rpc/status.proto"; -package google.api.version.test; +package google.api.version.test.v1; option java_package = "com.google.api.version.test"; option java_multiple_files = true; @@ -39,7 +39,7 @@ option (google.api.resource_definition) = { // to test different scenarios. // This service is used to test when api_version string is provided. -service Echo { +service EchoWithVersion { // This service is meant to only run locally on the port 7469 (keypad digits // for "show"). option (google.api.default_host) = "localhost:7469"; @@ -48,7 +48,7 @@ service Echo { "https://www.googleapis.com/auth/cloud-platform"; // This method simply echos the request. This method is showcases unary rpcs. - rpc Echo(EchoRequest) returns (EchoResponse) { + rpc EchoWithVersionMethod(EchoRequest) returns (EchoResponse) { option (google.api.http) = { post: "/v1beta1/echo:echo" body: "*" diff --git a/gapic-generator-java/src/test/proto/echo_grpcrest.proto b/gapic-generator-java/src/test/proto/echo_grpcrest.proto index fbab0c2553..ea4a9392f3 100644 --- a/gapic-generator-java/src/test/proto/echo_grpcrest.proto +++ b/gapic-generator-java/src/test/proto/echo_grpcrest.proto @@ -47,6 +47,7 @@ service Echo { option (google.api.default_host) = "localhost:7469"; option (google.api.oauth_scopes) = "https://www.googleapis.com/auth/cloud-platform"; + option (google.api.api_version) = "foo_version_for_tests"; // This method simply echos the request. This method is showcases unary rpcs. rpc Echo(EchoRequest) returns (EchoResponse) { diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiClientHeaderProvider.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiClientHeaderProvider.java index 34d00d0f3a..ae27404335 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiClientHeaderProvider.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiClientHeaderProvider.java @@ -42,6 +42,8 @@ public class ApiClientHeaderProvider implements HeaderProvider, Serializable { private static final long serialVersionUID = -8876627296793342119L; static final String QUOTA_PROJECT_ID_HEADER_KEY = "x-goog-user-project"; + static final String API_VERSION_HEADER_KEY = "x-goog-api-version"; + private final Map headers; protected ApiClientHeaderProvider(Builder builder) { @@ -68,6 +70,9 @@ protected ApiClientHeaderProvider(Builder builder) { headersBuilder.put(QUOTA_PROJECT_ID_HEADER_KEY, builder.getQuotaProjectIdToken()); } + if (builder.getApiVersionToken() != null) { + headersBuilder.put(API_VERSION_HEADER_KEY, builder.getApiVersionToken()); + } this.headers = headersBuilder.build(); } @@ -109,6 +114,8 @@ public static class Builder { private String resourceHeaderKey; private String resourceToken; + private String apiVersionToken; + protected Builder() { // Initialize with default values apiClientHeaderKey = getDefaultApiClientHeaderKey(); @@ -121,6 +128,8 @@ protected Builder() { resourceHeaderKey = getDefaultResourceHeaderKey(); resourceToken = null; + + apiVersionToken = null; } public String getApiClientHeaderKey() { @@ -206,6 +215,15 @@ public Builder setResourceToken(String resourceToken) { return this; } + public String getApiVersionToken() { + return apiVersionToken; + } + + public Builder setApiVersionToken(String apiVersionToken) { + this.apiVersionToken = apiVersionToken; + return this; + } + private String constructToken(String name, String version) { if (version == null) { return null; diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ApiClientHeaderProviderTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ApiClientHeaderProviderTest.java index f60c3c0760..bc524cb35d 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ApiClientHeaderProviderTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ApiClientHeaderProviderTest.java @@ -138,4 +138,18 @@ public void testQuotaProjectHeader() { assertThat(provider.getHeaders().get(ApiClientHeaderProvider.QUOTA_PROJECT_ID_HEADER_KEY)) .matches(quotaProjectHeaderValue); } + + @Test + public void testApiVersionHeader() { + ApiClientHeaderProvider provider = + ApiClientHeaderProvider.newBuilder().setApiVersionToken("fake-version-string").build(); + assertThat(provider.getHeaders().size()).isEqualTo(2); + assertThat(provider.getHeaders().get(ApiClientHeaderProvider.API_VERSION_HEADER_KEY)) + .matches("fake-version-string"); + + ApiClientHeaderProvider emptyProvider = + ApiClientHeaderProvider.newBuilder().setApiVersionToken("").build(); + assertThat( + emptyProvider.getHeaders().get(ApiClientHeaderProvider.API_VERSION_HEADER_KEY).isEmpty()); + } } diff --git a/showcase/gapic-showcase/src/main/java/com/google/showcase/v1beta1/stub/EchoStubSettings.java b/showcase/gapic-showcase/src/main/java/com/google/showcase/v1beta1/stub/EchoStubSettings.java index 1e659ed8d7..a54d329a0e 100644 --- a/showcase/gapic-showcase/src/main/java/com/google/showcase/v1beta1/stub/EchoStubSettings.java +++ b/showcase/gapic-showcase/src/main/java/com/google/showcase/v1beta1/stub/EchoStubSettings.java @@ -479,8 +479,8 @@ public static TransportChannelProvider defaultTransportChannelProvider() { public static ApiClientHeaderProvider.Builder defaultGrpcApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(EchoStubSettings.class)) - .setTransportToken( - GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); + .setTransportToken(GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()) + .setApiVersionToken("v1_20240408"); } public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() { @@ -488,7 +488,8 @@ public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProv .setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(EchoStubSettings.class)) .setTransportToken( GaxHttpJsonProperties.getHttpJsonTokenName(), - GaxHttpJsonProperties.getHttpJsonVersion()); + GaxHttpJsonProperties.getHttpJsonVersion()) + .setApiVersionToken("v1_20240408"); } public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {