diff --git a/src/main/java/com/google/api/generator/gapic/composer/ClassNames.java b/src/main/java/com/google/api/generator/gapic/composer/ClassNames.java index 8952119964..a53ffbb047 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ClassNames.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ClassNames.java @@ -20,44 +20,66 @@ public class ClassNames { // Using constants since many of these class names are used often. private static final String MOCK_SERVICE_CLASS_NAME_PATTERN = "Mock%s"; + private static final String MOCK_SERVICE_IMPL_CLASS_NAME_PATTERN = "Mock%sImpl"; private static final String SERVICE_CLIENT_CLASS_NAME_PATTERN = "%sClient"; + private static final String SERVICE_CLIENT_TEST_CLASS_NAME_PATTERN = "%sClientTest"; private static final String SERVICE_SETTINGS_CLASS_NAME_PATTERN = "%sSettings"; private static final String SERVICE_STUB_SETTINGS_CLASS_NAME_PATTERN = "%sStubSettings"; private static final String SERVICE_STUB_CLASS_NAME_PATTERN = "%sStub"; private static final String GRPC_SERVICE_STUB_CLASS_NAME_PATTERN = "Grpc%sStub"; private static final String GRPC_SERVICE_CALLABLE_FACTORY_CLASS_NAME_PATTERN = "Grpc%sCallableFactory"; - private static final String MOCK_SERVICE_IMPL_CLASS_NAME_PATTERN = "Mock%sImpl"; protected static String getServiceClientClassName(Service service) { - return String.format(SERVICE_CLIENT_CLASS_NAME_PATTERN, service.overriddenName()); + return String.format( + SERVICE_CLIENT_CLASS_NAME_PATTERN, + monolithBackwardsCompatibleName(service.overriddenName())); } protected static String getServiceSettingsClassName(Service service) { - return String.format(SERVICE_SETTINGS_CLASS_NAME_PATTERN, service.overriddenName()); - } - - protected static String getMockServiceClassName(Service service) { - return String.format(MOCK_SERVICE_CLASS_NAME_PATTERN, service.name()); - } - - protected static String getMockServiceImplClassName(Service service) { - return String.format(MOCK_SERVICE_IMPL_CLASS_NAME_PATTERN, service.name()); + return String.format( + SERVICE_SETTINGS_CLASS_NAME_PATTERN, + monolithBackwardsCompatibleName(service.overriddenName())); } protected static String getServiceStubSettingsClassName(Service service) { - return String.format(SERVICE_STUB_SETTINGS_CLASS_NAME_PATTERN, service.name()); + return String.format( + SERVICE_STUB_SETTINGS_CLASS_NAME_PATTERN, monolithBackwardsCompatibleName(service.name())); } protected static String getServiceStubClassName(Service service) { - return String.format(SERVICE_STUB_CLASS_NAME_PATTERN, service.name()); + return String.format( + SERVICE_STUB_CLASS_NAME_PATTERN, monolithBackwardsCompatibleName(service.name())); } protected static String getGrpcServiceCallableFactoryClassName(Service service) { - return String.format(GRPC_SERVICE_CALLABLE_FACTORY_CLASS_NAME_PATTERN, service.name()); + return String.format( + GRPC_SERVICE_CALLABLE_FACTORY_CLASS_NAME_PATTERN, + monolithBackwardsCompatibleName(service.name())); } protected static String getGrpcServiceStubClassName(Service service) { - return String.format(GRPC_SERVICE_STUB_CLASS_NAME_PATTERN, service.name()); + return String.format( + GRPC_SERVICE_STUB_CLASS_NAME_PATTERN, monolithBackwardsCompatibleName(service.name())); + } + + protected static String getServiceClientTestClassName(Service service) { + return String.format( + SERVICE_CLIENT_TEST_CLASS_NAME_PATTERN, + monolithBackwardsCompatibleName(service.overriddenName())); + } + + protected static String getMockServiceClassName(Service service) { + return String.format(MOCK_SERVICE_CLASS_NAME_PATTERN, service.name()); + } + + protected static String getMockServiceImplClassName(Service service) { + return String.format(MOCK_SERVICE_IMPL_CLASS_NAME_PATTERN, service.name()); + } + + private static String monolithBackwardsCompatibleName(String rawServiceName) { + return rawServiceName.startsWith("IAMCredentials") + ? rawServiceName.replace("IAM", "Iam") + : rawServiceName; } } diff --git a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java index 6673e10389..7686f679df 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/GrpcServiceStubClassComposer.java @@ -163,7 +163,7 @@ public GapicClass generate(Service service, Map ignore) { .setAnnotations(createClassAnnotations()) .setScope(ScopeNode.PUBLIC) .setName(className) - .setExtendsType(types.get(String.format(STUB_PATTERN, service.name()))) + .setExtendsType(types.get(ClassNames.getServiceStubClassName(service))) .setStatements(classStatements) .setMethods( createClassMethods( @@ -500,7 +500,7 @@ private static List createConstructorMethods( Map classMemberVarExprs, Map callableClassMemberVarExprs, Map protoMethodNameToDescriptorVarExprs) { - TypeNode stubSettingsType = types.get(String.format(STUB_SETTINGS_PATTERN, service.name())); + TypeNode stubSettingsType = types.get(ClassNames.getServiceStubSettingsClassName(service)); VariableExpr settingsVarExpr = VariableExpr.withVariable( Variable.builder().setName("settings").setType(stubSettingsType).build()); @@ -549,8 +549,7 @@ private static List createConstructorMethods( NewObjectExpr.builder() .setType( types.get( - String.format( - GRPC_SERVICE_CALLABLE_FACTORY_PATTERN, service.name()))) + ClassNames.getGrpcServiceCallableFactoryClassName(service))) .build()) .build()))); diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java index cd9674dcd6..4c72ed80a3 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientClassComposer.java @@ -303,7 +303,7 @@ private static List createConstructorMethods( String thisClientName = ClassNames.getServiceClientClassName(service); String settingsName = ClassNames.getServiceSettingsClassName(service); TypeNode thisClassType = types.get(thisClientName); - TypeNode stubSettingsType = types.get(String.format("%sStubSettings", service.name())); + TypeNode stubSettingsType = types.get(ClassNames.getServiceStubSettingsClassName(service)); TypeNode operationsClientType = types.get("OperationsClient"); TypeNode exceptionType = types.get("IOException"); @@ -1430,26 +1430,32 @@ private static Map createConcreteTypes() { private static Map createVaporTypes(Service service) { // Client stub types. Map types = - Arrays.asList("%sStub", "%sStubSettings").stream() + Arrays.asList( + ClassNames.getServiceStubClassName(service), + ClassNames.getServiceStubSettingsClassName(service)) + .stream() .collect( Collectors.toMap( - t -> String.format(t, service.name()), - t -> + n -> n, + n -> TypeNode.withReference( VaporReference.builder() - .setName(String.format(t, service.name())) + .setName(n) .setPakkage(String.format("%s.stub", service.pakkage())) .build()))); // Client ServiceClient and ServiceSettings types. types.putAll( - Arrays.asList("%sClient", "%sSettings").stream() + Arrays.asList( + ClassNames.getServiceClientClassName(service), + ClassNames.getServiceSettingsClassName(service)) + .stream() .collect( Collectors.toMap( - t -> String.format(t, service.overriddenName()), - t -> + n -> n, + n -> TypeNode.withReference( VaporReference.builder() - .setName(String.format(t, service.overriddenName())) + .setName(n) .setPakkage(service.pakkage()) .build())))); diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java index 1324b950bf..266efa242b 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceClientTestClassComposer.java @@ -135,7 +135,7 @@ public GapicClass generate( Service service, Map resourceNames, Map messageTypes) { String pakkage = service.pakkage(); Map types = createDynamicTypes(service); - String className = String.format("%sClientTest", service.overriddenName()); + String className = ClassNames.getServiceClientTestClassName(service); GapicClass.Kind kind = Kind.MAIN; Map classMemberVarExprs = createClassMemberVarExprs(service, types); diff --git a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java index c55d0fefc9..590c589e23 100644 --- a/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java +++ b/src/main/java/com/google/api/generator/gapic/composer/ServiceStubClassComposer.java @@ -59,7 +59,7 @@ public static ServiceStubClassComposer instance() { @Override public GapicClass generate(Service service, Map messageTypes) { Map types = createTypes(service, messageTypes); - String className = String.format("%sStub", service.name()); + String className = ClassNames.getServiceStubClassName(service); GapicClass.Kind kind = Kind.STUB; String pakkage = String.format("%s.stub", service.pakkage()); 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 35d460cc2b..ba9c38d455 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 @@ -29,6 +29,7 @@ public static String toLowerCamelCase(String s) { if (s.indexOf(UNDERSCORE) >= 0) { s = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, s); } + return capitalizeLettersAfterDigits( String.format("%s%s", s.substring(0, 1).toLowerCase(), s.substring(1))); } @@ -46,7 +47,8 @@ public static String toUpperCamelCase(String s) { } public static String toUpperSnakeCase(String s) { - return CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, toUpperCamelCase(s)); + String result = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, toUpperCamelCase(s)); + return result; } private static String capitalizeLettersAfterDigits(String s) { diff --git a/test/integration/BUILD.bazel b/test/integration/BUILD.bazel index 59b65ac274..7383a5ad11 100644 --- a/test/integration/BUILD.bazel +++ b/test/integration/BUILD.bazel @@ -18,6 +18,7 @@ package(default_visibility = ["//visibility:public"]) INTEGRATION_TEST_LIBRARIES = [ "asset", + "credentials", "logging", "redis", "library", # No gRPC service config. @@ -180,3 +181,37 @@ java_gapic_assembly_gradle_pkg( "@com_google_googleapis//google/example/library/v1:library_proto", ], ) + +# IAMCredentials. +# Check that the capital name edge case is handled. +java_gapic_library( + name = "credentials_java_gapic", + srcs = ["@com_google_googleapis//google/iam/credentials/v1:credentials_proto_with_info"], + grpc_service_config = "@com_google_googleapis//google/iam/credentials/v1:iamcredentials_grpc_service_config.json", + package = "google.iam.credentials.v1", + test_deps = [ + "@com_google_googleapis//google/iam/credentials/v1:credentials_java_grpc", + ], + deps = [ + "@com_google_googleapis//google/iam/credentials/v1:credentials_java_proto", + ], +) + +java_gapic_test( + name = "credentials_java_gapic_test_suite", + test_classes = [ + "com.google.cloud.iam.credentials.v1.IamCredentialsClientTest", + ], + runtime_deps = [":credentials_java_gapic_test"], +) + +# Open Source Packages +java_gapic_assembly_gradle_pkg( + name = "google-cloud-iam-credentials-v1-java", + deps = [ + ":credentials_java_gapic", + "@com_google_googleapis//google/iam/credentials/v1:credentials_java_grpc", + "@com_google_googleapis//google/iam/credentials/v1:credentials_java_proto", + "@com_google_googleapis//google/iam/credentials/v1:credentials_proto", + ], +) diff --git a/test/integration/goldens/credentials/BUILD.bazel b/test/integration/goldens/credentials/BUILD.bazel new file mode 100644 index 0000000000..0b74aed56b --- /dev/null +++ b/test/integration/goldens/credentials/BUILD.bazel @@ -0,0 +1,6 @@ +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "goldens_files", + srcs = glob(["*.java"]), +) diff --git a/test/integration/goldens/credentials/GrpcIamCredentialsCallableFactory.java b/test/integration/goldens/credentials/GrpcIamCredentialsCallableFactory.java new file mode 100644 index 0000000000..6dc31820a3 --- /dev/null +++ b/test/integration/goldens/credentials/GrpcIamCredentialsCallableFactory.java @@ -0,0 +1,113 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.iam.credentials.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 IAMCredentials service API. + * + *

This class is for advanced usage. + */ +@Generated("by gapic-generator") +public class GrpcIamCredentialsCallableFactory 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/credentials/GrpcIamCredentialsStub.java b/test/integration/goldens/credentials/GrpcIamCredentialsStub.java new file mode 100644 index 0000000000..869e84c892 --- /dev/null +++ b/test/integration/goldens/credentials/GrpcIamCredentialsStub.java @@ -0,0 +1,265 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.iam.credentials.v1.stub; + +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.cloud.iam.credentials.v1.GenerateAccessTokenRequest; +import com.google.cloud.iam.credentials.v1.GenerateAccessTokenResponse; +import com.google.cloud.iam.credentials.v1.GenerateIdTokenRequest; +import com.google.cloud.iam.credentials.v1.GenerateIdTokenResponse; +import com.google.cloud.iam.credentials.v1.SignBlobRequest; +import com.google.cloud.iam.credentials.v1.SignBlobResponse; +import com.google.cloud.iam.credentials.v1.SignJwtRequest; +import com.google.cloud.iam.credentials.v1.SignJwtResponse; +import com.google.common.collect.ImmutableMap; +import com.google.longrunning.stub.GrpcOperationsStub; +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 IAMCredentials service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public class GrpcIamCredentialsStub extends IamCredentialsStub { + private static final MethodDescriptor + generateAccessTokenMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.credentials.v1.IAMCredentials/GenerateAccessToken") + .setRequestMarshaller( + ProtoUtils.marshaller(GenerateAccessTokenRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(GenerateAccessTokenResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + generateIdTokenMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.credentials.v1.IAMCredentials/GenerateIdToken") + .setRequestMarshaller( + ProtoUtils.marshaller(GenerateIdTokenRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(GenerateIdTokenResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + signBlobMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.credentials.v1.IAMCredentials/SignBlob") + .setRequestMarshaller(ProtoUtils.marshaller(SignBlobRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(SignBlobResponse.getDefaultInstance())) + .build(); + + private static final MethodDescriptor signJwtMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.credentials.v1.IAMCredentials/SignJwt") + .setRequestMarshaller(ProtoUtils.marshaller(SignJwtRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(SignJwtResponse.getDefaultInstance())) + .build(); + + private final UnaryCallable + generateAccessTokenCallable; + private final UnaryCallable + generateIdTokenCallable; + private final UnaryCallable signBlobCallable; + private final UnaryCallable signJwtCallable; + + private final BackgroundResource backgroundResources; + private final GrpcOperationsStub operationsStub; + private final GrpcStubCallableFactory callableFactory; + + public static final GrpcIamCredentialsStub create(IamCredentialsStubSettings settings) + throws IOException { + return new GrpcIamCredentialsStub(settings, ClientContext.create(settings)); + } + + public static final GrpcIamCredentialsStub create(ClientContext clientContext) + throws IOException { + return new GrpcIamCredentialsStub( + IamCredentialsStubSettings.newBuilder().build(), clientContext); + } + + public static final GrpcIamCredentialsStub create( + ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { + return new GrpcIamCredentialsStub( + IamCredentialsStubSettings.newBuilder().build(), clientContext, callableFactory); + } + + /** + * Constructs an instance of GrpcIamCredentialsStub, 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 GrpcIamCredentialsStub(IamCredentialsStubSettings settings, ClientContext clientContext) + throws IOException { + this(settings, clientContext, new GrpcIamCredentialsCallableFactory()); + } + + /** + * Constructs an instance of GrpcIamCredentialsStub, 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 GrpcIamCredentialsStub( + IamCredentialsStubSettings settings, + ClientContext clientContext, + GrpcStubCallableFactory callableFactory) + throws IOException { + this.callableFactory = callableFactory; + this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); + + GrpcCallSettings + generateAccessTokenTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(generateAccessTokenMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GenerateAccessTokenRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + generateIdTokenTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(generateIdTokenMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GenerateIdTokenRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings signBlobTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(signBlobMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(SignBlobRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + GrpcCallSettings signJwtTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(signJwtMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(SignJwtRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("name", String.valueOf(request.getName())); + return params.build(); + } + }) + .build(); + + this.generateAccessTokenCallable = + callableFactory.createUnaryCallable( + generateAccessTokenTransportSettings, + settings.generateAccessTokenSettings(), + clientContext); + this.generateIdTokenCallable = + callableFactory.createUnaryCallable( + generateIdTokenTransportSettings, settings.generateIdTokenSettings(), clientContext); + this.signBlobCallable = + callableFactory.createUnaryCallable( + signBlobTransportSettings, settings.signBlobSettings(), clientContext); + this.signJwtCallable = + callableFactory.createUnaryCallable( + signJwtTransportSettings, settings.signJwtSettings(), clientContext); + + this.backgroundResources = + new BackgroundResourceAggregation(clientContext.getBackgroundResources()); + } + + public GrpcOperationsStub getOperationsStub() { + return operationsStub; + } + + public UnaryCallable + generateAccessTokenCallable() { + return generateAccessTokenCallable; + } + + public UnaryCallable generateIdTokenCallable() { + return generateIdTokenCallable; + } + + public UnaryCallable signBlobCallable() { + return signBlobCallable; + } + + public UnaryCallable signJwtCallable() { + return signJwtCallable; + } + + @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/credentials/IamCredentialsClient.java b/test/integration/goldens/credentials/IamCredentialsClient.java new file mode 100644 index 0000000000..e3699cdcc0 --- /dev/null +++ b/test/integration/goldens/credentials/IamCredentialsClient.java @@ -0,0 +1,518 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.iam.credentials.v1; + +import com.google.api.core.BetaApi; +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.cloud.iam.credentials.v1.stub.IamCredentialsStub; +import com.google.cloud.iam.credentials.v1.stub.IamCredentialsStubSettings; +import com.google.protobuf.ByteString; +import com.google.protobuf.Duration; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Service Description: A service account is a special type of Google account that belongs to your + * application or a virtual machine (VM), instead of to an individual end user. Your application + * assumes the identity of the service account to call Google APIs, so that the users aren't + * directly involved. + * + *

Service account credentials are used to temporarily assume the identity of the service + * account. Supported credential types include OAuth 2.0 access tokens, OpenID Connect ID tokens, + * self-signed JSON Web Tokens (JWTs), and more. + * + *

This class provides the ability to make remote calls to the backing service through method + * calls that map to API methods. Sample code to get started: + * + *

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

To customize credentials: + * + *

{@code
+ * IamCredentialsSettings iamCredentialsSettings =
+ *     IamCredentialsSettings.newBuilder()
+ *         .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
+ *         .build();
+ * IamCredentialsClient iamCredentialsClient = IamCredentialsClient.create(iamCredentialsSettings);
+ * }
+ * + *

To customize the endpoint: + * + *

{@code
+ * IamCredentialsSettings iamCredentialsSettings =
+ *     IamCredentialsSettings.newBuilder().setEndpoint(myEndpoint).build();
+ * IamCredentialsClient iamCredentialsClient = IamCredentialsClient.create(iamCredentialsSettings);
+ * }
+ * + *

Please refer to the GitHub repository's samples for more quickstart code snippets. + */ +@BetaApi +@Generated("by gapic-generator") +public class IamCredentialsClient implements BackgroundResource { + private final IamCredentialsSettings settings; + private final IamCredentialsStub stub; + + /** Constructs an instance of IamCredentialsClient with default settings. */ + public static final IamCredentialsClient create() throws IOException { + return create(IamCredentialsSettings.newBuilder().build()); + } + + /** + * Constructs an instance of IamCredentialsClient, 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 IamCredentialsClient create(IamCredentialsSettings settings) + throws IOException { + return new IamCredentialsClient(settings); + } + + /** + * Constructs an instance of IamCredentialsClient, using the given stub for making calls. This is + * for advanced usage - prefer using create(IamCredentialsSettings). + */ + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public static final IamCredentialsClient create(IamCredentialsStub stub) { + return new IamCredentialsClient(stub); + } + + /** + * Constructs an instance of IamCredentialsClient, 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 IamCredentialsClient(IamCredentialsSettings settings) throws IOException { + this.settings = settings; + this.stub = ((IamCredentialsStubSettings) settings.getStubSettings()).createStub(); + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + protected IamCredentialsClient(IamCredentialsStub stub) { + this.settings = null; + this.stub = stub; + } + + public final IamCredentialsSettings getSettings() { + return settings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public IamCredentialsStub getStub() { + return stub; + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Generates an OAuth 2.0 access token for a service account. + * + * @param name Required. The resource name of the service account for which the credentials are + * requested, in the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param delegates The sequence of service accounts in a delegation chain. Each service account + * must be granted the `roles/iam.serviceAccountTokenCreator` role on its next service account + * in the chain. The last service account in the chain must be granted the + * `roles/iam.serviceAccountTokenCreator` role on the service account that is specified in the + * `name` field of the request. + *

The delegates must have the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param scope Required. Code to identify the scopes to be included in the OAuth 2.0 access + * token. See https://developers.google.com/identity/protocols/googlescopes for more + * information. At least one value required. + * @param lifetime The desired lifetime duration of the access token in seconds. Must be set to a + * value less than or equal to 3600 (1 hour). If a value is not specified, the token's + * lifetime will be set to a default value of one hour. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final GenerateAccessTokenResponse generateAccessToken( + ServiceAccountName name, List delegates, List scope, Duration lifetime) { + GenerateAccessTokenRequest request = + GenerateAccessTokenRequest.newBuilder() + .setName(name == null ? null : name.toString()) + .addAllDelegates(delegates) + .addAllScope(scope) + .setLifetime(lifetime) + .build(); + return generateAccessToken(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Generates an OAuth 2.0 access token for a service account. + * + * @param name Required. The resource name of the service account for which the credentials are + * requested, in the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param delegates The sequence of service accounts in a delegation chain. Each service account + * must be granted the `roles/iam.serviceAccountTokenCreator` role on its next service account + * in the chain. The last service account in the chain must be granted the + * `roles/iam.serviceAccountTokenCreator` role on the service account that is specified in the + * `name` field of the request. + *

The delegates must have the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param scope Required. Code to identify the scopes to be included in the OAuth 2.0 access + * token. See https://developers.google.com/identity/protocols/googlescopes for more + * information. At least one value required. + * @param lifetime The desired lifetime duration of the access token in seconds. Must be set to a + * value less than or equal to 3600 (1 hour). If a value is not specified, the token's + * lifetime will be set to a default value of one hour. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final GenerateAccessTokenResponse generateAccessToken( + String name, List delegates, List scope, Duration lifetime) { + GenerateAccessTokenRequest request = + GenerateAccessTokenRequest.newBuilder() + .setName(name) + .addAllDelegates(delegates) + .addAllScope(scope) + .setLifetime(lifetime) + .build(); + return generateAccessToken(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Generates an OAuth 2.0 access token for a service account. + * + * @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 GenerateAccessTokenResponse generateAccessToken(GenerateAccessTokenRequest request) { + return generateAccessTokenCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Generates an OAuth 2.0 access token for a service account. + * + *

Sample code: + */ + public final UnaryCallable + generateAccessTokenCallable() { + return stub.generateAccessTokenCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Generates an OpenID Connect ID token for a service account. + * + * @param name Required. The resource name of the service account for which the credentials are + * requested, in the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param delegates The sequence of service accounts in a delegation chain. Each service account + * must be granted the `roles/iam.serviceAccountTokenCreator` role on its next service account + * in the chain. The last service account in the chain must be granted the + * `roles/iam.serviceAccountTokenCreator` role on the service account that is specified in the + * `name` field of the request. + *

The delegates must have the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param audience Required. The audience for the token, such as the API or account that this + * token grants access to. + * @param includeEmail Include the service account email in the token. If set to `true`, the token + * will contain `email` and `email_verified` claims. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final GenerateIdTokenResponse generateIdToken( + ServiceAccountName name, List delegates, String audience, boolean includeEmail) { + GenerateIdTokenRequest request = + GenerateIdTokenRequest.newBuilder() + .setName(name == null ? null : name.toString()) + .addAllDelegates(delegates) + .setAudience(audience) + .setIncludeEmail(includeEmail) + .build(); + return generateIdToken(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Generates an OpenID Connect ID token for a service account. + * + * @param name Required. The resource name of the service account for which the credentials are + * requested, in the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param delegates The sequence of service accounts in a delegation chain. Each service account + * must be granted the `roles/iam.serviceAccountTokenCreator` role on its next service account + * in the chain. The last service account in the chain must be granted the + * `roles/iam.serviceAccountTokenCreator` role on the service account that is specified in the + * `name` field of the request. + *

The delegates must have the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param audience Required. The audience for the token, such as the API or account that this + * token grants access to. + * @param includeEmail Include the service account email in the token. If set to `true`, the token + * will contain `email` and `email_verified` claims. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final GenerateIdTokenResponse generateIdToken( + String name, List delegates, String audience, boolean includeEmail) { + GenerateIdTokenRequest request = + GenerateIdTokenRequest.newBuilder() + .setName(name) + .addAllDelegates(delegates) + .setAudience(audience) + .setIncludeEmail(includeEmail) + .build(); + return generateIdToken(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Generates an OpenID Connect ID token for a service account. + * + * @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 GenerateIdTokenResponse generateIdToken(GenerateIdTokenRequest request) { + return generateIdTokenCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Generates an OpenID Connect ID token for a service account. + * + *

Sample code: + */ + public final UnaryCallable + generateIdTokenCallable() { + return stub.generateIdTokenCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Signs a blob using a service account's system-managed private key. + * + * @param name Required. The resource name of the service account for which the credentials are + * requested, in the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param delegates The sequence of service accounts in a delegation chain. Each service account + * must be granted the `roles/iam.serviceAccountTokenCreator` role on its next service account + * in the chain. The last service account in the chain must be granted the + * `roles/iam.serviceAccountTokenCreator` role on the service account that is specified in the + * `name` field of the request. + *

The delegates must have the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param payload Required. The bytes to sign. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final SignBlobResponse signBlob( + ServiceAccountName name, List delegates, ByteString payload) { + SignBlobRequest request = + SignBlobRequest.newBuilder() + .setName(name == null ? null : name.toString()) + .addAllDelegates(delegates) + .setPayload(payload) + .build(); + return signBlob(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Signs a blob using a service account's system-managed private key. + * + * @param name Required. The resource name of the service account for which the credentials are + * requested, in the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param delegates The sequence of service accounts in a delegation chain. Each service account + * must be granted the `roles/iam.serviceAccountTokenCreator` role on its next service account + * in the chain. The last service account in the chain must be granted the + * `roles/iam.serviceAccountTokenCreator` role on the service account that is specified in the + * `name` field of the request. + *

The delegates must have the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param payload Required. The bytes to sign. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final SignBlobResponse signBlob(String name, List delegates, ByteString payload) { + SignBlobRequest request = + SignBlobRequest.newBuilder() + .setName(name) + .addAllDelegates(delegates) + .setPayload(payload) + .build(); + return signBlob(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Signs a blob using a service account's system-managed private key. + * + * @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 SignBlobResponse signBlob(SignBlobRequest request) { + return signBlobCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Signs a blob using a service account's system-managed private key. + * + *

Sample code: + */ + public final UnaryCallable signBlobCallable() { + return stub.signBlobCallable(); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Signs a JWT using a service account's system-managed private key. + * + * @param name Required. The resource name of the service account for which the credentials are + * requested, in the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param delegates The sequence of service accounts in a delegation chain. Each service account + * must be granted the `roles/iam.serviceAccountTokenCreator` role on its next service account + * in the chain. The last service account in the chain must be granted the + * `roles/iam.serviceAccountTokenCreator` role on the service account that is specified in the + * `name` field of the request. + *

The delegates must have the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param payload Required. The JWT payload to sign: a JSON object that contains a JWT Claims Set. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final SignJwtResponse signJwt( + ServiceAccountName name, List delegates, String payload) { + SignJwtRequest request = + SignJwtRequest.newBuilder() + .setName(name == null ? null : name.toString()) + .addAllDelegates(delegates) + .setPayload(payload) + .build(); + return signJwt(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Signs a JWT using a service account's system-managed private key. + * + * @param name Required. The resource name of the service account for which the credentials are + * requested, in the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param delegates The sequence of service accounts in a delegation chain. Each service account + * must be granted the `roles/iam.serviceAccountTokenCreator` role on its next service account + * in the chain. The last service account in the chain must be granted the + * `roles/iam.serviceAccountTokenCreator` role on the service account that is specified in the + * `name` field of the request. + *

The delegates must have the following format: + * `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is + * required; replacing it with a project ID is invalid. + * @param payload Required. The JWT payload to sign: a JSON object that contains a JWT Claims Set. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final SignJwtResponse signJwt(String name, List delegates, String payload) { + SignJwtRequest request = + SignJwtRequest.newBuilder() + .setName(name) + .addAllDelegates(delegates) + .setPayload(payload) + .build(); + return signJwt(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Signs a JWT using a service account's system-managed private key. + * + * @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 SignJwtResponse signJwt(SignJwtRequest request) { + return signJwtCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Signs a JWT using a service account's system-managed private key. + * + *

Sample code: + */ + public final UnaryCallable signJwtCallable() { + return stub.signJwtCallable(); + } + + @Override + public final void close() { + stub.close(); + } + + @Override + public void shutdown() { + stub.shutdown(); + } + + @Override + public boolean isShutdown() { + return stub.isShutdown(); + } + + @Override + public boolean isTerminated() { + return stub.isTerminated(); + } + + @Override + public void shutdownNow() { + stub.shutdownNow(); + } + + @Override + public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { + return stub.awaitTermination(duration, unit); + } +} diff --git a/test/integration/goldens/credentials/IamCredentialsClientTest.java b/test/integration/goldens/credentials/IamCredentialsClientTest.java new file mode 100644 index 0000000000..e34da02196 --- /dev/null +++ b/test/integration/goldens/credentials/IamCredentialsClientTest.java @@ -0,0 +1,451 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.iam.credentials.v1; + +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.protobuf.AbstractMessage; +import com.google.protobuf.ByteString; +import com.google.protobuf.Duration; +import com.google.protobuf.Timestamp; +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 IamCredentialsClientTest { + private static MockServiceHelper mockServiceHelper; + private static MockIAMCredentials mockIAMCredentials; + private IamCredentialsClient client; + private LocalChannelProvider channelProvider; + + @BeforeClass + public static void startStaticServer() { + mockIAMCredentials = new MockIAMCredentials(); + mockServiceHelper = + new MockServiceHelper( + UUID.randomUUID().toString(), Arrays.asList(mockIAMCredentials)); + mockServiceHelper.start(); + } + + @AfterClass + public static void stopServer() { + mockServiceHelper.stop(); + } + + @Before + public void setUp() throws IOException { + mockServiceHelper.reset(); + channelProvider = mockServiceHelper.createChannelProvider(); + IamCredentialsSettings settings = + IamCredentialsSettings.newBuilder() + .setTransportChannelProvider(channelProvider) + .setCredentialsProvider(NoCredentialsProvider.create()) + .build(); + client = IamCredentialsClient.create(settings); + } + + @After + public void tearDown() throws Exception { + client.close(); + } + + @Test + public void generateAccessTokenTest() throws Exception { + GenerateAccessTokenResponse expectedResponse = + GenerateAccessTokenResponse.newBuilder() + .setAccessToken("accessToken-1042689291") + .setExpireTime(Timestamp.newBuilder().build()) + .build(); + mockIAMCredentials.addResponse(expectedResponse); + + ServiceAccountName name = ServiceAccountName.of("[PROJECT]", "[SERVICE_ACCOUNT]"); + List delegates = new ArrayList<>(); + List scope = new ArrayList<>(); + Duration lifetime = Duration.newBuilder().build(); + + GenerateAccessTokenResponse actualResponse = + client.generateAccessToken(name, delegates, scope, lifetime); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMCredentials.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GenerateAccessTokenRequest actualRequest = ((GenerateAccessTokenRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertEquals(delegates, actualRequest.getDelegatesList()); + Assert.assertEquals(scope, actualRequest.getScopeList()); + Assert.assertEquals(lifetime, actualRequest.getLifetime()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void generateAccessTokenExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMCredentials.addException(exception); + + try { + ServiceAccountName name = ServiceAccountName.of("[PROJECT]", "[SERVICE_ACCOUNT]"); + List delegates = new ArrayList<>(); + List scope = new ArrayList<>(); + Duration lifetime = Duration.newBuilder().build(); + client.generateAccessToken(name, delegates, scope, lifetime); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void generateAccessTokenTest2() throws Exception { + GenerateAccessTokenResponse expectedResponse = + GenerateAccessTokenResponse.newBuilder() + .setAccessToken("accessToken-1042689291") + .setExpireTime(Timestamp.newBuilder().build()) + .build(); + mockIAMCredentials.addResponse(expectedResponse); + + String name = "name3373707"; + List delegates = new ArrayList<>(); + List scope = new ArrayList<>(); + Duration lifetime = Duration.newBuilder().build(); + + GenerateAccessTokenResponse actualResponse = + client.generateAccessToken(name, delegates, scope, lifetime); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMCredentials.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GenerateAccessTokenRequest actualRequest = ((GenerateAccessTokenRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertEquals(delegates, actualRequest.getDelegatesList()); + Assert.assertEquals(scope, actualRequest.getScopeList()); + Assert.assertEquals(lifetime, actualRequest.getLifetime()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void generateAccessTokenExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMCredentials.addException(exception); + + try { + String name = "name3373707"; + List delegates = new ArrayList<>(); + List scope = new ArrayList<>(); + Duration lifetime = Duration.newBuilder().build(); + client.generateAccessToken(name, delegates, scope, lifetime); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void generateIdTokenTest() throws Exception { + GenerateIdTokenResponse expectedResponse = + GenerateIdTokenResponse.newBuilder().setToken("token110541305").build(); + mockIAMCredentials.addResponse(expectedResponse); + + ServiceAccountName name = ServiceAccountName.of("[PROJECT]", "[SERVICE_ACCOUNT]"); + List delegates = new ArrayList<>(); + String audience = "audience975628804"; + boolean includeEmail = true; + + GenerateIdTokenResponse actualResponse = + client.generateIdToken(name, delegates, audience, includeEmail); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMCredentials.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GenerateIdTokenRequest actualRequest = ((GenerateIdTokenRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertEquals(delegates, actualRequest.getDelegatesList()); + Assert.assertEquals(audience, actualRequest.getAudience()); + Assert.assertEquals(includeEmail, actualRequest.getIncludeEmail()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void generateIdTokenExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMCredentials.addException(exception); + + try { + ServiceAccountName name = ServiceAccountName.of("[PROJECT]", "[SERVICE_ACCOUNT]"); + List delegates = new ArrayList<>(); + String audience = "audience975628804"; + boolean includeEmail = true; + client.generateIdToken(name, delegates, audience, includeEmail); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void generateIdTokenTest2() throws Exception { + GenerateIdTokenResponse expectedResponse = + GenerateIdTokenResponse.newBuilder().setToken("token110541305").build(); + mockIAMCredentials.addResponse(expectedResponse); + + String name = "name3373707"; + List delegates = new ArrayList<>(); + String audience = "audience975628804"; + boolean includeEmail = true; + + GenerateIdTokenResponse actualResponse = + client.generateIdToken(name, delegates, audience, includeEmail); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMCredentials.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GenerateIdTokenRequest actualRequest = ((GenerateIdTokenRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertEquals(delegates, actualRequest.getDelegatesList()); + Assert.assertEquals(audience, actualRequest.getAudience()); + Assert.assertEquals(includeEmail, actualRequest.getIncludeEmail()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void generateIdTokenExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMCredentials.addException(exception); + + try { + String name = "name3373707"; + List delegates = new ArrayList<>(); + String audience = "audience975628804"; + boolean includeEmail = true; + client.generateIdToken(name, delegates, audience, includeEmail); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void signBlobTest() throws Exception { + SignBlobResponse expectedResponse = + SignBlobResponse.newBuilder() + .setKeyId("keyId101944282") + .setSignedBlob(ByteString.EMPTY) + .build(); + mockIAMCredentials.addResponse(expectedResponse); + + ServiceAccountName name = ServiceAccountName.of("[PROJECT]", "[SERVICE_ACCOUNT]"); + List delegates = new ArrayList<>(); + ByteString payload = ByteString.EMPTY; + + SignBlobResponse actualResponse = client.signBlob(name, delegates, payload); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMCredentials.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + SignBlobRequest actualRequest = ((SignBlobRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertEquals(delegates, actualRequest.getDelegatesList()); + Assert.assertEquals(payload, actualRequest.getPayload()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void signBlobExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMCredentials.addException(exception); + + try { + ServiceAccountName name = ServiceAccountName.of("[PROJECT]", "[SERVICE_ACCOUNT]"); + List delegates = new ArrayList<>(); + ByteString payload = ByteString.EMPTY; + client.signBlob(name, delegates, payload); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void signBlobTest2() throws Exception { + SignBlobResponse expectedResponse = + SignBlobResponse.newBuilder() + .setKeyId("keyId101944282") + .setSignedBlob(ByteString.EMPTY) + .build(); + mockIAMCredentials.addResponse(expectedResponse); + + String name = "name3373707"; + List delegates = new ArrayList<>(); + ByteString payload = ByteString.EMPTY; + + SignBlobResponse actualResponse = client.signBlob(name, delegates, payload); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMCredentials.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + SignBlobRequest actualRequest = ((SignBlobRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertEquals(delegates, actualRequest.getDelegatesList()); + Assert.assertEquals(payload, actualRequest.getPayload()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void signBlobExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMCredentials.addException(exception); + + try { + String name = "name3373707"; + List delegates = new ArrayList<>(); + ByteString payload = ByteString.EMPTY; + client.signBlob(name, delegates, payload); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void signJwtTest() throws Exception { + SignJwtResponse expectedResponse = + SignJwtResponse.newBuilder() + .setKeyId("keyId101944282") + .setSignedJwt("signedJwt1076760587") + .build(); + mockIAMCredentials.addResponse(expectedResponse); + + ServiceAccountName name = ServiceAccountName.of("[PROJECT]", "[SERVICE_ACCOUNT]"); + List delegates = new ArrayList<>(); + String payload = "payload-786701938"; + + SignJwtResponse actualResponse = client.signJwt(name, delegates, payload); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMCredentials.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + SignJwtRequest actualRequest = ((SignJwtRequest) actualRequests.get(0)); + + Assert.assertEquals(name.toString(), actualRequest.getName()); + Assert.assertEquals(delegates, actualRequest.getDelegatesList()); + Assert.assertEquals(payload, actualRequest.getPayload()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void signJwtExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMCredentials.addException(exception); + + try { + ServiceAccountName name = ServiceAccountName.of("[PROJECT]", "[SERVICE_ACCOUNT]"); + List delegates = new ArrayList<>(); + String payload = "payload-786701938"; + client.signJwt(name, delegates, payload); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void signJwtTest2() throws Exception { + SignJwtResponse expectedResponse = + SignJwtResponse.newBuilder() + .setKeyId("keyId101944282") + .setSignedJwt("signedJwt1076760587") + .build(); + mockIAMCredentials.addResponse(expectedResponse); + + String name = "name3373707"; + List delegates = new ArrayList<>(); + String payload = "payload-786701938"; + + SignJwtResponse actualResponse = client.signJwt(name, delegates, payload); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMCredentials.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + SignJwtRequest actualRequest = ((SignJwtRequest) actualRequests.get(0)); + + Assert.assertEquals(name, actualRequest.getName()); + Assert.assertEquals(delegates, actualRequest.getDelegatesList()); + Assert.assertEquals(payload, actualRequest.getPayload()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void signJwtExceptionTest2() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMCredentials.addException(exception); + + try { + String name = "name3373707"; + List delegates = new ArrayList<>(); + String payload = "payload-786701938"; + client.signJwt(name, delegates, payload); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } +} diff --git a/test/integration/goldens/credentials/IamCredentialsSettings.java b/test/integration/goldens/credentials/IamCredentialsSettings.java new file mode 100644 index 0000000000..0f932e8fe4 --- /dev/null +++ b/test/integration/goldens/credentials/IamCredentialsSettings.java @@ -0,0 +1,218 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.iam.credentials.v1; + +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.StubSettings; +import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.cloud.iam.credentials.v1.stub.IamCredentialsStubSettings; +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 IamCredentialsClient}. + * + *

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

    + *
  • The default service address (iamcredentials.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 generateAccessToken to 30 seconds: + * + *

{@code
+ * IamCredentialsSettings.Builder iamCredentialsSettingsBuilder =
+ *     IamCredentialsSettings.newBuilder();
+ * iamCredentialsSettingsBuilder
+ *     .generateAccessTokenSettings()
+ *     .setRetrySettings(
+ *         iamCredentialsSettingsBuilder
+ *             .generateAccessTokenSettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * IamCredentialsSettings iamCredentialsSettings = iamCredentialsSettingsBuilder.build();
+ * }
+ */ +@Generated("by gapic-generator-java") +public class IamCredentialsSettings extends ClientSettings { + + /** Returns the object with the settings used for calls to generateAccessToken. */ + public UnaryCallSettings + generateAccessTokenSettings() { + return ((IamCredentialsStubSettings) getStubSettings()).generateAccessTokenSettings(); + } + + /** Returns the object with the settings used for calls to generateIdToken. */ + public UnaryCallSettings + generateIdTokenSettings() { + return ((IamCredentialsStubSettings) getStubSettings()).generateIdTokenSettings(); + } + + /** Returns the object with the settings used for calls to signBlob. */ + public UnaryCallSettings signBlobSettings() { + return ((IamCredentialsStubSettings) getStubSettings()).signBlobSettings(); + } + + /** Returns the object with the settings used for calls to signJwt. */ + public UnaryCallSettings signJwtSettings() { + return ((IamCredentialsStubSettings) getStubSettings()).signJwtSettings(); + } + + public static final IamCredentialsSettings create(IamCredentialsStubSettings stub) + throws IOException { + return new IamCredentialsSettings.Builder(stub.toBuilder()).build(); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return IamCredentialsStubSettings.defaultExecutorProviderBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return IamCredentialsStubSettings.getDefaultEndpoint(); + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return IamCredentialsStubSettings.getDefaultServiceScopes(); + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return IamCredentialsStubSettings.defaultCredentialsProviderBuilder(); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return IamCredentialsStubSettings.defaultGrpcTransportProviderBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return IamCredentialsStubSettings.defaultTransportChannelProvider(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return IamCredentialsStubSettings.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 IamCredentialsSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + } + + /** Builder for IamCredentialsSettings. */ + public static class Builder extends ClientSettings.Builder { + + protected Builder() throws IOException { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(IamCredentialsStubSettings.newBuilder(clientContext)); + } + + protected Builder(IamCredentialsSettings settings) { + super(settings.getStubSettings().toBuilder()); + } + + protected Builder(IamCredentialsStubSettings.Builder stubSettings) { + super(stubSettings); + } + + private static Builder createDefault() { + return new Builder(IamCredentialsStubSettings.newBuilder()); + } + + public IamCredentialsStubSettings.Builder getStubSettingsBuilder() { + return ((IamCredentialsStubSettings.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 generateAccessToken. */ + public UnaryCallSettings.Builder + generateAccessTokenSettings() { + return getStubSettingsBuilder().generateAccessTokenSettings(); + } + + /** Returns the builder for the settings used for calls to generateIdToken. */ + public UnaryCallSettings.Builder + generateIdTokenSettings() { + return getStubSettingsBuilder().generateIdTokenSettings(); + } + + /** Returns the builder for the settings used for calls to signBlob. */ + public UnaryCallSettings.Builder signBlobSettings() { + return getStubSettingsBuilder().signBlobSettings(); + } + + /** Returns the builder for the settings used for calls to signJwt. */ + public UnaryCallSettings.Builder signJwtSettings() { + return getStubSettingsBuilder().signJwtSettings(); + } + + @Override + public IamCredentialsSettings build() throws IOException { + return new IamCredentialsSettings(this); + } + } +} diff --git a/test/integration/goldens/credentials/IamCredentialsStub.java b/test/integration/goldens/credentials/IamCredentialsStub.java new file mode 100644 index 0000000000..8b195e93b0 --- /dev/null +++ b/test/integration/goldens/credentials/IamCredentialsStub.java @@ -0,0 +1,59 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.iam.credentials.v1.stub; + +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.cloud.iam.credentials.v1.GenerateAccessTokenRequest; +import com.google.cloud.iam.credentials.v1.GenerateAccessTokenResponse; +import com.google.cloud.iam.credentials.v1.GenerateIdTokenRequest; +import com.google.cloud.iam.credentials.v1.GenerateIdTokenResponse; +import com.google.cloud.iam.credentials.v1.SignBlobRequest; +import com.google.cloud.iam.credentials.v1.SignBlobResponse; +import com.google.cloud.iam.credentials.v1.SignJwtRequest; +import com.google.cloud.iam.credentials.v1.SignJwtResponse; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Base stub class for the IAMCredentials service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator") +public abstract class IamCredentialsStub implements BackgroundResource { + + public UnaryCallable + generateAccessTokenCallable() { + throw new UnsupportedOperationException("Not implemented: generateAccessTokenCallable()"); + } + + public UnaryCallable generateIdTokenCallable() { + throw new UnsupportedOperationException("Not implemented: generateIdTokenCallable()"); + } + + public UnaryCallable signBlobCallable() { + throw new UnsupportedOperationException("Not implemented: signBlobCallable()"); + } + + public UnaryCallable signJwtCallable() { + throw new UnsupportedOperationException("Not implemented: signJwtCallable()"); + } + + @Override + public abstract void close(); +} diff --git a/test/integration/goldens/credentials/IamCredentialsStubSettings.java b/test/integration/goldens/credentials/IamCredentialsStubSettings.java new file mode 100644 index 0000000000..d86322d07b --- /dev/null +++ b/test/integration/goldens/credentials/IamCredentialsStubSettings.java @@ -0,0 +1,352 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.iam.credentials.v1.stub; + +import com.google.api.core.ApiFunction; +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.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.cloud.iam.credentials.v1.GenerateAccessTokenRequest; +import com.google.cloud.iam.credentials.v1.GenerateAccessTokenResponse; +import com.google.cloud.iam.credentials.v1.GenerateIdTokenRequest; +import com.google.cloud.iam.credentials.v1.GenerateIdTokenResponse; +import com.google.cloud.iam.credentials.v1.SignBlobRequest; +import com.google.cloud.iam.credentials.v1.SignBlobResponse; +import com.google.cloud.iam.credentials.v1.SignJwtRequest; +import com.google.cloud.iam.credentials.v1.SignJwtResponse; +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; +import org.threeten.bp.Duration; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Settings class to configure an instance of {@link IamCredentialsStub}. + * + *

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

    + *
  • The default service address (iamcredentials.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 generateAccessToken to 30 seconds: + * + *

{@code
+ * IamCredentialsStubSettings.Builder iamCredentialsSettingsBuilder =
+ *     IamCredentialsStubSettings.newBuilder();
+ * iamCredentialsSettingsBuilder
+ *     .generateAccessTokenSettings()
+ *     .setRetrySettings(
+ *         iamCredentialsSettingsBuilder
+ *             .generateAccessTokenSettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * IamCredentialsStubSettings iamCredentialsSettings = iamCredentialsSettingsBuilder.build();
+ * }
+ */ +@BetaApi +@Generated("by gapic-generator-java") +public class IamCredentialsStubSettings 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 + generateAccessTokenSettings; + private final UnaryCallSettings + generateIdTokenSettings; + private final UnaryCallSettings signBlobSettings; + private final UnaryCallSettings signJwtSettings; + + /** Returns the object with the settings used for calls to generateAccessToken. */ + public UnaryCallSettings + generateAccessTokenSettings() { + return generateAccessTokenSettings; + } + + /** Returns the object with the settings used for calls to generateIdToken. */ + public UnaryCallSettings + generateIdTokenSettings() { + return generateIdTokenSettings; + } + + /** Returns the object with the settings used for calls to signBlob. */ + public UnaryCallSettings signBlobSettings() { + return signBlobSettings; + } + + /** Returns the object with the settings used for calls to signJwt. */ + public UnaryCallSettings signJwtSettings() { + return signJwtSettings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public IamCredentialsStub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(GrpcTransportChannel.getGrpcTransportName())) { + return GrpcIamCredentialsStub.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 "iamcredentials.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(IamCredentialsStubSettings.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 IamCredentialsStubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + + generateAccessTokenSettings = settingsBuilder.generateAccessTokenSettings().build(); + generateIdTokenSettings = settingsBuilder.generateIdTokenSettings().build(); + signBlobSettings = settingsBuilder.signBlobSettings().build(); + signJwtSettings = settingsBuilder.signJwtSettings().build(); + } + + /** Builder for IamCredentialsStubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final UnaryCallSettings.Builder + generateAccessTokenSettings; + private final UnaryCallSettings.Builder + generateIdTokenSettings; + private final UnaryCallSettings.Builder signBlobSettings; + private final UnaryCallSettings.Builder signJwtSettings; + 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, StatusCode.Code.DEADLINE_EXCEEDED))); + 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); + RETRY_PARAM_DEFINITIONS = definitions.build(); + } + + protected Builder() { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(clientContext); + + generateAccessTokenSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + generateIdTokenSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + signBlobSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + signJwtSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + generateAccessTokenSettings, + generateIdTokenSettings, + signBlobSettings, + signJwtSettings); + initDefaults(this); + } + + protected Builder(IamCredentialsStubSettings settings) { + super(settings); + + generateAccessTokenSettings = settings.generateAccessTokenSettings.toBuilder(); + generateIdTokenSettings = settings.generateIdTokenSettings.toBuilder(); + signBlobSettings = settings.signBlobSettings.toBuilder(); + signJwtSettings = settings.signJwtSettings.toBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + generateAccessTokenSettings, + generateIdTokenSettings, + signBlobSettings, + signJwtSettings); + } + + 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 + .generateAccessTokenSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); + + builder + .generateIdTokenSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); + + builder + .signBlobSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); + + builder + .signJwtSettings() + .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 generateAccessToken. */ + public UnaryCallSettings.Builder + generateAccessTokenSettings() { + return generateAccessTokenSettings; + } + + /** Returns the builder for the settings used for calls to generateIdToken. */ + public UnaryCallSettings.Builder + generateIdTokenSettings() { + return generateIdTokenSettings; + } + + /** Returns the builder for the settings used for calls to signBlob. */ + public UnaryCallSettings.Builder signBlobSettings() { + return signBlobSettings; + } + + /** Returns the builder for the settings used for calls to signJwt. */ + public UnaryCallSettings.Builder signJwtSettings() { + return signJwtSettings; + } + + @Override + public IamCredentialsStubSettings build() throws IOException { + return new IamCredentialsStubSettings(this); + } + } +} diff --git a/test/integration/goldens/credentials/MockIAMCredentials.java b/test/integration/goldens/credentials/MockIAMCredentials.java new file mode 100644 index 0000000000..4aefde532c --- /dev/null +++ b/test/integration/goldens/credentials/MockIAMCredentials.java @@ -0,0 +1,59 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.iam.credentials.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 MockIAMCredentials implements MockGrpcService { + private final MockIAMCredentialsImpl serviceImpl; + + public MockIAMCredentials() { + serviceImpl = new MockIAMCredentialsImpl(); + } + + @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/credentials/MockIAMCredentialsImpl.java b/test/integration/goldens/credentials/MockIAMCredentialsImpl.java new file mode 100644 index 0000000000..851402cad9 --- /dev/null +++ b/test/integration/goldens/credentials/MockIAMCredentialsImpl.java @@ -0,0 +1,119 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.iam.credentials.v1; + +import com.google.api.core.BetaApi; +import com.google.cloud.iam.credentials.v1.IAMCredentialsGrpc.IAMCredentialsImplBase; +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 MockIAMCredentialsImpl extends IAMCredentialsImplBase { + private List requests; + private Queue responses; + + public MockIAMCredentialsImpl() { + 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 generateAccessToken( + GenerateAccessTokenRequest request, + StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof GenerateAccessTokenResponse) { + requests.add(request); + responseObserver.onNext(((GenerateAccessTokenResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void generateIdToken( + GenerateIdTokenRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof GenerateIdTokenResponse) { + requests.add(request); + responseObserver.onNext(((GenerateIdTokenResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void signBlob(SignBlobRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof SignBlobResponse) { + requests.add(request); + responseObserver.onNext(((SignBlobResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } + + @Override + public void signJwt(SignJwtRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof SignJwtResponse) { + requests.add(request); + responseObserver.onNext(((SignJwtResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError(new IllegalArgumentException("Unrecognized response type")); + } + } +} diff --git a/test/integration/goldens/credentials/ServiceAccountName.java b/test/integration/goldens/credentials/ServiceAccountName.java new file mode 100644 index 0000000000..677f604c7c --- /dev/null +++ b/test/integration/goldens/credentials/ServiceAccountName.java @@ -0,0 +1,193 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.iam.credentials.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 ServiceAccountName implements ResourceName { + private static final PathTemplate PROJECT_SERVICE_ACCOUNT = + PathTemplate.createWithoutUrlEncoding("projects/{project}/serviceAccounts/{service_account}"); + private volatile Map fieldValuesMap; + private final String project; + private final String serviceAccount; + + @Deprecated + protected ServiceAccountName() { + project = null; + serviceAccount = null; + } + + private ServiceAccountName(Builder builder) { + project = Preconditions.checkNotNull(builder.getProject()); + serviceAccount = Preconditions.checkNotNull(builder.getServiceAccount()); + } + + public String getProject() { + return project; + } + + public String getServiceAccount() { + return serviceAccount; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static ServiceAccountName of(String project, String serviceAccount) { + return newBuilder().setProject(project).setServiceAccount(serviceAccount).build(); + } + + public static String format(String project, String serviceAccount) { + return newBuilder().setProject(project).setServiceAccount(serviceAccount).build().toString(); + } + + public static ServiceAccountName parse(String formattedString) { + if (formattedString.isEmpty()) { + return null; + } + Map matchMap = + PROJECT_SERVICE_ACCOUNT.validatedMatch( + formattedString, "ServiceAccountName.parse: formattedString not in valid format"); + return of(matchMap.get("project"), matchMap.get("service_account")); + } + + public static List parseList(List formattedStrings) { + List list = new ArrayList<>(formattedStrings.size()); + for (String formattedString : formattedStrings) { + list.add(parse(formattedString)); + } + return list; + } + + public static List toStringList(List values) { + List list = new ArrayList<>(values.size()); + for (ServiceAccountName value : values) { + if (value == null) { + list.add(""); + } else { + list.add(value.toString()); + } + } + return list; + } + + public static boolean isParsableFrom(String formattedString) { + return PROJECT_SERVICE_ACCOUNT.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 (serviceAccount != null) { + fieldMapBuilder.put("service_account", serviceAccount); + } + fieldValuesMap = fieldMapBuilder.build(); + } + } + } + return fieldValuesMap; + } + + public String getFieldValue(String fieldName) { + return getFieldValuesMap().get(fieldName); + } + + @Override + public String toString() { + return PROJECT_SERVICE_ACCOUNT.instantiate( + "project", project, "service_account", serviceAccount); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o != null || getClass() == o.getClass()) { + ServiceAccountName that = ((ServiceAccountName) o); + return Objects.equals(this.project, that.project) + && Objects.equals(this.serviceAccount, that.serviceAccount); + } + return false; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= Objects.hashCode(project); + h *= 1000003; + h ^= Objects.hashCode(serviceAccount); + return h; + } + + /** Builder for projects/{project}/serviceAccounts/{service_account}. */ + public static class Builder { + private String project; + private String serviceAccount; + + protected Builder() {} + + public String getProject() { + return project; + } + + public String getServiceAccount() { + return serviceAccount; + } + + public Builder setProject(String project) { + this.project = project; + return this; + } + + public Builder setServiceAccount(String serviceAccount) { + this.serviceAccount = serviceAccount; + return this; + } + + private Builder(ServiceAccountName serviceAccountName) { + project = serviceAccountName.project; + serviceAccount = serviceAccountName.serviceAccount; + } + + public ServiceAccountName build() { + return new ServiceAccountName(this); + } + } +} diff --git a/test/integration/goldens/credentials/package-info.java b/test/integration/goldens/credentials/package-info.java new file mode 100644 index 0000000000..dd29f50059 --- /dev/null +++ b/test/integration/goldens/credentials/package-info.java @@ -0,0 +1,36 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The interfaces provided are listed below, along with usage samples. + * + *

======================= IamCredentialsClient ======================= + * + *

Service Description: A service account is a special type of Google account that belongs to + * your application or a virtual machine (VM), instead of to an individual end user. Your + * application assumes the identity of the service account to call Google APIs, so that the users + * aren't directly involved. + * + *

Service account credentials are used to temporarily assume the identity of the service + * account. Supported credential types include OAuth 2.0 access tokens, OpenID Connect ID tokens, + * self-signed JSON Web Tokens (JWTs), and more. + * + *

Sample for IamCredentialsClient: + */ +@Generated("by gapic-generator-java") +package com.google.cloud.iam.credentials.v1; + +import javax.annotation.Generated;