diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 04b029dee6..b6829aa65c 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -134,7 +134,7 @@ if [ $NUM_JAVA_FILES_CHANGED -gt 0 ] then echo_status "Checking Apache License Header ..." header_check_preparation - addlicense -c "Google LLC" -l apache -check $(find $PWD -type f -name '*.java') + addlicense -c "Google LLC" -l apache -check $(find $PWD -type f -name '*.java' ! -iname '*PlaceholderFile.java') CHECK_STATUS=$? if [ $CHECK_STATUS != 0 ] then diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 9222c3e454..33b7738029 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -49,7 +49,7 @@ jobs: run: bazel --batch test $(bazel query "//src/test/..." | grep "Test$") --noshow_progress - name: Integration Tests - run: bazel --batch test //test/integration:asset //test/integration:credentials //test/integration:kms //test/integration:logging //test/integration:redis //test/integration:library --noshow_progress + run: bazel --batch test //test/integration:asset //test/integration:credentials //test/integration:iam //test/integration:kms //test/integration:logging //test/integration:redis //test/integration:library --noshow_progress - uses: actions/upload-artifact@v2 if: ${{ failure() }} @@ -90,5 +90,5 @@ jobs: - name: License Header Check run: | go get -u github.com/google/addlicense - addlicense -c "Google LLC" -l apache -check $(find $PWD -type f -name '*.java') + addlicense -c "Google LLC" -l apache -check $(find $PWD -type f -name '*.java' ! -iname '*PlaceholderFile.java') diff --git a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java index a14d886f58..13797240ca 100644 --- a/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java +++ b/src/main/java/com/google/api/generator/gapic/protoparser/Parser.java @@ -218,13 +218,20 @@ public static List parseServices( // indicator that we are not generating a GAPIC client for the mixed-in service on its own. Function serviceFullNameFn = s -> String.format("%s.%s", s.protoPakkage(), s.name()); - Set blockedCodegenMixinApis = - services.stream() - .filter(s -> MIXIN_ALLOWLIST.contains(serviceFullNameFn.apply(s))) - .map(s -> s) - .collect(Collectors.toSet()); + Set blockedCodegenMixinApis = new HashSet<>(); + Set definedServices = new HashSet<>(); + for (Service s : services) { + if (MIXIN_ALLOWLIST.contains(serviceFullNameFn.apply(s))) { + blockedCodegenMixinApis.add(s); + } else { + definedServices.add(s); + } + } // It's very unlikely the blocklisted APIs will contain the other, or any other service. - boolean servicesContainBlocklistedApi = !blockedCodegenMixinApis.isEmpty(); + boolean servicesContainBlocklistedApi = + !blockedCodegenMixinApis.isEmpty() && !definedServices.isEmpty(); + // Service names that are stated in the YAML file (as mixins). Used to filter + // blockedCodegenMixinApis. Set mixedInApis = !serviceYamlProtoOpt.isPresent() ? Collections.emptySet() diff --git a/src/test/java/com/google/api/generator/gapic/composer/constants/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/constants/BUILD.bazel index d77098ae19..c83471c30b 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/constants/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/constants/BUILD.bazel @@ -1,3 +1,5 @@ +load("@rules_java//java:defs.bzl", "java_binary") + package(default_visibility = ["//visibility:public"]) filegroup( diff --git a/src/test/java/com/google/api/generator/gapic/composer/defaultvalue/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/defaultvalue/BUILD.bazel index dd73c0bef7..c14999e877 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/defaultvalue/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/defaultvalue/BUILD.bazel @@ -1,4 +1,4 @@ -load("@rules_java//java:defs.bzl", "java_test") +load("@rules_java//java:defs.bzl", "java_proto_library", "java_test") package(default_visibility = ["//visibility:public"]) diff --git a/src/test/java/com/google/api/generator/gapic/composer/resourcename/BUILD.bazel b/src/test/java/com/google/api/generator/gapic/composer/resourcename/BUILD.bazel index 16db1b17b0..17b37c640b 100644 --- a/src/test/java/com/google/api/generator/gapic/composer/resourcename/BUILD.bazel +++ b/src/test/java/com/google/api/generator/gapic/composer/resourcename/BUILD.bazel @@ -1,4 +1,4 @@ -load("@rules_java//java:defs.bzl", "java_test") +load("@rules_java//java:defs.bzl", "java_proto_library", "java_test") package(default_visibility = ["//visibility:public"]) diff --git a/test/integration/BUILD.bazel b/test/integration/BUILD.bazel index 004d8b1f9d..7090825238 100644 --- a/test/integration/BUILD.bazel +++ b/test/integration/BUILD.bazel @@ -5,6 +5,7 @@ load( "java_gapic_test", "java_grpc_library", "java_proto_library", + "proto_library_with_info", ) load( "//:rules_bazel/java/integration_test.bzl", @@ -12,6 +13,9 @@ load( "integration_test", ) +# KMS (for mixins). +load("@rules_proto//proto:defs.bzl", "proto_library") + package(default_visibility = ["//visibility:public"]) #################################################### @@ -21,6 +25,7 @@ package(default_visibility = ["//visibility:public"]) INTEGRATION_TEST_LIBRARIES = [ "asset", # Basic case. "credentials", # Check that the capital name edge case is handled. + "iam", # Mixin-only special-case API can build on its own. "kms", # Mixins, with an override in the proto file. "logging", # Java package remapping in gapic.yaml. "redis", # Has a gapic.yaml. @@ -31,6 +36,7 @@ INTEGRATION_TEST_LIBRARIES = [ API_GAPIC_TARGETS = { "asset": "@com_google_googleapis//google/cloud/asset/v1:asset_java_gapic", "credentials": "@com_google_googleapis//google/iam/credentials/v1:credentials_java_gapic", + "iam": ":iam_java_gapic", # Googleapis' LRO does not have a Java Gapic. "kms": ":kms_java_gapic", # Local target because mixins are not rolled out yet. "logging": "@com_google_googleapis//google/logging/v2:logging_java_gapic", "redis": "@com_google_googleapis//google/cloud/redis/v1beta1:redis_java_gapic", @@ -157,9 +163,35 @@ java_gapic_assembly_gradle_pkg( ], ) -# KMS (for mixins). -load("@rules_proto//proto:defs.bzl", "proto_library") -load("@com_google_googleapis_imports//:imports.bzl", "proto_library_with_info") +# IAM (for a standalone mixed-in API). +java_gapic_library( + name = "iam_java_gapic", + srcs = ["@com_google_googleapis//google/iam/v1:iam_proto_with_info"], + grpc_service_config = "iam_grpc_service_config.json", + test_deps = [ + "@com_google_googleapis//google/iam/v1:iam_java_grpc", + ], + deps = [ + "@com_google_googleapis//google/iam/v1:iam_java_proto", + ], +) + +java_gapic_test( + name = "iam_java_gapic_test_suite", + test_classes = [ + "com.google.iam.v1.IAMPolicyClientTest", + ], + runtime_deps = ["iam_java_gapic_test"], +) + +java_gapic_assembly_gradle_pkg( + name = "google-cloud-iam-java", + deps = [ + ":iam_java_gapic", + "@com_google_googleapis//google/iam/v1:iam_java_grpc", + "@com_google_googleapis//google/iam/v1:iam_java_proto", + ], +) proto_library( name = "kms_proto", diff --git a/test/integration/goldens/iam/BUILD.bazel b/test/integration/goldens/iam/BUILD.bazel new file mode 100644 index 0000000000..667772f01b --- /dev/null +++ b/test/integration/goldens/iam/BUILD.bazel @@ -0,0 +1,9 @@ +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "goldens_files", + srcs = glob([ + "*.java", + "gapic_metadata.json", + ]), +) diff --git a/test/integration/goldens/iam/GrpcIAMPolicyCallableFactory.java b/test/integration/goldens/iam/GrpcIAMPolicyCallableFactory.java new file mode 100644 index 0000000000..5b96cd1ec8 --- /dev/null +++ b/test/integration/goldens/iam/GrpcIAMPolicyCallableFactory.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.iam.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 IAMPolicy service API. + * + *

This class is for advanced usage. + */ +@Generated("by gapic-generator-java") +public class GrpcIAMPolicyCallableFactory 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/iam/GrpcIAMPolicyStub.java b/test/integration/goldens/iam/GrpcIAMPolicyStub.java new file mode 100644 index 0000000000..b12e0f6863 --- /dev/null +++ b/test/integration/goldens/iam/GrpcIAMPolicyStub.java @@ -0,0 +1,227 @@ +/* + * 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.iam.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.common.collect.ImmutableMap; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.longrunning.stub.GrpcOperationsStub; +import 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 IAMPolicy service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public class GrpcIAMPolicyStub extends IAMPolicyStub { + private static final MethodDescriptor setIamPolicyMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/SetIamPolicy") + .setRequestMarshaller(ProtoUtils.marshaller(SetIamPolicyRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) + .build(); + + private static final MethodDescriptor getIamPolicyMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/GetIamPolicy") + .setRequestMarshaller(ProtoUtils.marshaller(GetIamPolicyRequest.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) + .build(); + + private static final MethodDescriptor + testIamPermissionsMethodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName("google.iam.v1.IAMPolicy/TestIamPermissions") + .setRequestMarshaller( + ProtoUtils.marshaller(TestIamPermissionsRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(TestIamPermissionsResponse.getDefaultInstance())) + .build(); + + private final UnaryCallable setIamPolicyCallable; + private final UnaryCallable getIamPolicyCallable; + private final UnaryCallable + testIamPermissionsCallable; + + private final BackgroundResource backgroundResources; + private final GrpcOperationsStub operationsStub; + private final GrpcStubCallableFactory callableFactory; + + public static final GrpcIAMPolicyStub create(IAMPolicyStubSettings settings) throws IOException { + return new GrpcIAMPolicyStub(settings, ClientContext.create(settings)); + } + + public static final GrpcIAMPolicyStub create(ClientContext clientContext) throws IOException { + return new GrpcIAMPolicyStub(IAMPolicyStubSettings.newBuilder().build(), clientContext); + } + + public static final GrpcIAMPolicyStub create( + ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { + return new GrpcIAMPolicyStub( + IAMPolicyStubSettings.newBuilder().build(), clientContext, callableFactory); + } + + /** + * Constructs an instance of GrpcIAMPolicyStub, 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 GrpcIAMPolicyStub(IAMPolicyStubSettings settings, ClientContext clientContext) + throws IOException { + this(settings, clientContext, new GrpcIAMPolicyCallableFactory()); + } + + /** + * Constructs an instance of GrpcIAMPolicyStub, 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 GrpcIAMPolicyStub( + IAMPolicyStubSettings settings, + ClientContext clientContext, + GrpcStubCallableFactory callableFactory) + throws IOException { + this.callableFactory = callableFactory; + this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); + + GrpcCallSettings setIamPolicyTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(setIamPolicyMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(SetIamPolicyRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + GrpcCallSettings getIamPolicyTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(getIamPolicyMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(GetIamPolicyRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + GrpcCallSettings + testIamPermissionsTransportSettings = + GrpcCallSettings.newBuilder() + .setMethodDescriptor(testIamPermissionsMethodDescriptor) + .setParamsExtractor( + new RequestParamsExtractor() { + @Override + public Map extract(TestIamPermissionsRequest request) { + ImmutableMap.Builder params = ImmutableMap.builder(); + params.put("resource", String.valueOf(request.getResource())); + return params.build(); + } + }) + .build(); + + this.setIamPolicyCallable = + callableFactory.createUnaryCallable( + setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext); + this.getIamPolicyCallable = + callableFactory.createUnaryCallable( + getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext); + this.testIamPermissionsCallable = + callableFactory.createUnaryCallable( + testIamPermissionsTransportSettings, + settings.testIamPermissionsSettings(), + clientContext); + + this.backgroundResources = + new BackgroundResourceAggregation(clientContext.getBackgroundResources()); + } + + public GrpcOperationsStub getOperationsStub() { + return operationsStub; + } + + @Override + public UnaryCallable setIamPolicyCallable() { + return setIamPolicyCallable; + } + + @Override + public UnaryCallable getIamPolicyCallable() { + return getIamPolicyCallable; + } + + @Override + public UnaryCallable + testIamPermissionsCallable() { + return testIamPermissionsCallable; + } + + @Override + public final void close() { + shutdown(); + } + + @Override + public void shutdown() { + backgroundResources.shutdown(); + } + + @Override + public boolean isShutdown() { + return backgroundResources.isShutdown(); + } + + @Override + public boolean isTerminated() { + return backgroundResources.isTerminated(); + } + + @Override + public void shutdownNow() { + backgroundResources.shutdownNow(); + } + + @Override + public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { + return backgroundResources.awaitTermination(duration, unit); + } +} diff --git a/test/integration/goldens/iam/IAMPolicyClient.java b/test/integration/goldens/iam/IAMPolicyClient.java new file mode 100644 index 0000000000..d7ec4a68e7 --- /dev/null +++ b/test/integration/goldens/iam/IAMPolicyClient.java @@ -0,0 +1,348 @@ +/* + * 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.iam.v1; + +import com.google.api.core.BetaApi; +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.iam.v1.stub.IAMPolicyStub; +import com.google.iam.v1.stub.IAMPolicyStubSettings; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Service Description: ## API Overview + * + *

Manages Identity and Access Management (IAM) policies. + * + *

Any implementation of an API that offers access control features implements the + * google.iam.v1.IAMPolicy interface. + * + *

## Data model + * + *

Access control is applied when a principal (user or service account), takes some action on a + * resource exposed by a service. Resources, identified by URI-like names, are the unit of access + * control specification. Service implementations can choose the granularity of access control and + * the supported permissions for their resources. For example one database service may allow access + * control to be specified only at the Table level, whereas another might allow access control to + * also be specified at the Column level. + * + *

## Policy Structure + * + *

See google.iam.v1.Policy + * + *

This is intentionally not a CRUD style API because access control policies are created and + * deleted implicitly with the resources to which they are attached. + * + *

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

{@code
+ * try (IAMPolicyClient iAMPolicyClient = IAMPolicyClient.create()) {
+ *   SetIamPolicyRequest request =
+ *       SetIamPolicyRequest.newBuilder()
+ *           .setResource("SetIamPolicyRequest1223629066".toString())
+ *           .setPolicy(Policy.newBuilder().build())
+ *           .build();
+ *   Policy response = iAMPolicyClient.setIamPolicy(request);
+ * }
+ * }
+ * + *

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

To customize credentials: + * + *

{@code
+ * IAMPolicySettings iAMPolicySettings =
+ *     IAMPolicySettings.newBuilder()
+ *         .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
+ *         .build();
+ * IAMPolicyClient iAMPolicyClient = IAMPolicyClient.create(iAMPolicySettings);
+ * }
+ * + *

To customize the endpoint: + * + *

{@code
+ * IAMPolicySettings iAMPolicySettings =
+ *     IAMPolicySettings.newBuilder().setEndpoint(myEndpoint).build();
+ * IAMPolicyClient iAMPolicyClient = IAMPolicyClient.create(iAMPolicySettings);
+ * }
+ * + *

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

Sample code: + * + *

{@code
+   * try (IAMPolicyClient iAMPolicyClient = IAMPolicyClient.create()) {
+   *   SetIamPolicyRequest request =
+   *       SetIamPolicyRequest.newBuilder()
+   *           .setResource("SetIamPolicyRequest1223629066".toString())
+   *           .setPolicy(Policy.newBuilder().build())
+   *           .build();
+   *   Policy response = iAMPolicyClient.setIamPolicy(request);
+   * }
+   * }
+ * + * @param request The request object containing all of the parameters for the API call. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Policy setIamPolicy(SetIamPolicyRequest request) { + return setIamPolicyCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Sets the access control policy on the specified resource. Replaces any existing policy. + * + *

Sample code: + * + *

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

Sample code: + * + *

{@code
+   * try (IAMPolicyClient iAMPolicyClient = IAMPolicyClient.create()) {
+   *   GetIamPolicyRequest request =
+   *       GetIamPolicyRequest.newBuilder()
+   *           .setResource("GetIamPolicyRequest-1527610370".toString())
+   *           .setOptions(GetPolicyOptions.newBuilder().build())
+   *           .build();
+   *   Policy response = iAMPolicyClient.getIamPolicy(request);
+   * }
+   * }
+ * + * @param request The request object containing all of the parameters for the API call. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final Policy getIamPolicy(GetIamPolicyRequest request) { + return getIamPolicyCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Gets the access control policy for a resource. Returns an empty policy if the resource exists + * and does not have a policy set. + * + *

Sample code: + * + *

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

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

Sample code: + * + *

{@code
+   * try (IAMPolicyClient iAMPolicyClient = IAMPolicyClient.create()) {
+   *   TestIamPermissionsRequest request =
+   *       TestIamPermissionsRequest.newBuilder()
+   *           .setResource("TestIamPermissionsRequest942398222".toString())
+   *           .addAllPermissions(new ArrayList())
+   *           .build();
+   *   TestIamPermissionsResponse response = iAMPolicyClient.testIamPermissions(request);
+   * }
+   * }
+ * + * @param request The request object containing all of the parameters for the API call. + * @throws com.google.api.gax.rpc.ApiException if the remote call fails + */ + public final TestIamPermissionsResponse testIamPermissions(TestIamPermissionsRequest request) { + return testIamPermissionsCallable().call(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD. + /** + * Returns permissions that a caller has on the specified resource. If the resource does not + * exist, this will return an empty set of permissions, not a NOT_FOUND error. + * + *

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

Sample code: + * + *

{@code
+   * try (IAMPolicyClient iAMPolicyClient = IAMPolicyClient.create()) {
+   *   TestIamPermissionsRequest request =
+   *       TestIamPermissionsRequest.newBuilder()
+   *           .setResource("TestIamPermissionsRequest942398222".toString())
+   *           .addAllPermissions(new ArrayList())
+   *           .build();
+   *   ApiFuture future =
+   *       iAMPolicyClient.testIamPermissionsCallable().futureCall(request);
+   *   // Do something.
+   *   TestIamPermissionsResponse response = future.get();
+   * }
+   * }
+ */ + public final UnaryCallable + testIamPermissionsCallable() { + return stub.testIamPermissionsCallable(); + } + + @Override + public final void close() { + stub.close(); + } + + @Override + public void shutdown() { + stub.shutdown(); + } + + @Override + public boolean isShutdown() { + return stub.isShutdown(); + } + + @Override + public boolean isTerminated() { + return stub.isTerminated(); + } + + @Override + public void shutdownNow() { + stub.shutdownNow(); + } + + @Override + public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { + return stub.awaitTermination(duration, unit); + } +} diff --git a/test/integration/goldens/iam/IAMPolicyClientTest.java b/test/integration/goldens/iam/IAMPolicyClientTest.java new file mode 100644 index 0000000000..cd911b0459 --- /dev/null +++ b/test/integration/goldens/iam/IAMPolicyClientTest.java @@ -0,0 +1,222 @@ +/* + * 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.iam.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 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 IAMPolicyClientTest { + private static MockServiceHelper mockServiceHelper; + private IAMPolicyClient client; + private static MockIAMPolicy mockIAMPolicy; + private LocalChannelProvider channelProvider; + + @BeforeClass + public static void startStaticServer() { + mockIAMPolicy = new MockIAMPolicy(); + mockServiceHelper = + new MockServiceHelper( + UUID.randomUUID().toString(), Arrays.asList(mockIAMPolicy)); + mockServiceHelper.start(); + } + + @AfterClass + public static void stopServer() { + mockServiceHelper.stop(); + } + + @Before + public void setUp() throws IOException { + mockServiceHelper.reset(); + channelProvider = mockServiceHelper.createChannelProvider(); + IAMPolicySettings settings = + IAMPolicySettings.newBuilder() + .setTransportChannelProvider(channelProvider) + .setCredentialsProvider(NoCredentialsProvider.create()) + .build(); + client = IAMPolicyClient.create(settings); + } + + @After + public void tearDown() throws Exception { + client.close(); + } + + @Test + public void setIamPolicyTest() throws Exception { + Policy expectedResponse = + Policy.newBuilder() + .setVersion(351608024) + .addAllBindings(new ArrayList()) + .setEtag(ByteString.EMPTY) + .build(); + mockIAMPolicy.addResponse(expectedResponse); + + SetIamPolicyRequest request = + SetIamPolicyRequest.newBuilder() + .setResource("SetIamPolicyRequest1223629066".toString()) + .setPolicy(Policy.newBuilder().build()) + .build(); + + Policy actualResponse = client.setIamPolicy(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + SetIamPolicyRequest actualRequest = ((SetIamPolicyRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getPolicy(), actualRequest.getPolicy()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void setIamPolicyExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + SetIamPolicyRequest request = + SetIamPolicyRequest.newBuilder() + .setResource("SetIamPolicyRequest1223629066".toString()) + .setPolicy(Policy.newBuilder().build()) + .build(); + client.setIamPolicy(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void getIamPolicyTest() throws Exception { + Policy expectedResponse = + Policy.newBuilder() + .setVersion(351608024) + .addAllBindings(new ArrayList()) + .setEtag(ByteString.EMPTY) + .build(); + mockIAMPolicy.addResponse(expectedResponse); + + GetIamPolicyRequest request = + GetIamPolicyRequest.newBuilder() + .setResource("GetIamPolicyRequest-1527610370".toString()) + .setOptions(GetPolicyOptions.newBuilder().build()) + .build(); + + Policy actualResponse = client.getIamPolicy(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + GetIamPolicyRequest actualRequest = ((GetIamPolicyRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getOptions(), actualRequest.getOptions()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void getIamPolicyExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + GetIamPolicyRequest request = + GetIamPolicyRequest.newBuilder() + .setResource("GetIamPolicyRequest-1527610370".toString()) + .setOptions(GetPolicyOptions.newBuilder().build()) + .build(); + client.getIamPolicy(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } + + @Test + public void testIamPermissionsTest() throws Exception { + TestIamPermissionsResponse expectedResponse = + TestIamPermissionsResponse.newBuilder().addAllPermissions(new ArrayList()).build(); + mockIAMPolicy.addResponse(expectedResponse); + + TestIamPermissionsRequest request = + TestIamPermissionsRequest.newBuilder() + .setResource("TestIamPermissionsRequest942398222".toString()) + .addAllPermissions(new ArrayList()) + .build(); + + TestIamPermissionsResponse actualResponse = client.testIamPermissions(request); + Assert.assertEquals(expectedResponse, actualResponse); + + List actualRequests = mockIAMPolicy.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + TestIamPermissionsRequest actualRequest = ((TestIamPermissionsRequest) actualRequests.get(0)); + + Assert.assertEquals(request.getResource(), actualRequest.getResource()); + Assert.assertEquals(request.getPermissionsList(), actualRequest.getPermissionsList()); + Assert.assertTrue( + channelProvider.isHeaderSent( + ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), + GaxGrpcProperties.getDefaultApiClientHeaderPattern())); + } + + @Test + public void testIamPermissionsExceptionTest() throws Exception { + StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); + mockIAMPolicy.addException(exception); + + try { + TestIamPermissionsRequest request = + TestIamPermissionsRequest.newBuilder() + .setResource("TestIamPermissionsRequest942398222".toString()) + .addAllPermissions(new ArrayList()) + .build(); + client.testIamPermissions(request); + Assert.fail("No exception raised"); + } catch (InvalidArgumentException e) { + // Expected exception. + } + } +} diff --git a/test/integration/goldens/iam/IAMPolicySettings.java b/test/integration/goldens/iam/IAMPolicySettings.java new file mode 100644 index 0000000000..b190fa6b2f --- /dev/null +++ b/test/integration/goldens/iam/IAMPolicySettings.java @@ -0,0 +1,203 @@ +/* + * 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.iam.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.iam.v1.stub.IAMPolicyStubSettings; +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 IAMPolicyClient}. + * + *

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

    + *
  • The default service address (iam-meta-api.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 setIamPolicy to 30 seconds: + * + *

{@code
+ * IAMPolicySettings.Builder iAMPolicySettingsBuilder = IAMPolicySettings.newBuilder();
+ * iAMPolicySettingsBuilder
+ *     .setIamPolicySettings()
+ *     .setRetrySettings(
+ *         iAMPolicySettingsBuilder
+ *             .setIamPolicySettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * IAMPolicySettings iAMPolicySettings = iAMPolicySettingsBuilder.build();
+ * }
+ */ +@Generated("by gapic-generator-java") +public class IAMPolicySettings extends ClientSettings { + + /** Returns the object with the settings used for calls to setIamPolicy. */ + public UnaryCallSettings setIamPolicySettings() { + return ((IAMPolicyStubSettings) getStubSettings()).setIamPolicySettings(); + } + + /** Returns the object with the settings used for calls to getIamPolicy. */ + public UnaryCallSettings getIamPolicySettings() { + return ((IAMPolicyStubSettings) getStubSettings()).getIamPolicySettings(); + } + + /** Returns the object with the settings used for calls to testIamPermissions. */ + public UnaryCallSettings + testIamPermissionsSettings() { + return ((IAMPolicyStubSettings) getStubSettings()).testIamPermissionsSettings(); + } + + public static final IAMPolicySettings create(IAMPolicyStubSettings stub) throws IOException { + return new IAMPolicySettings.Builder(stub.toBuilder()).build(); + } + + /** Returns a builder for the default ExecutorProvider for this service. */ + public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { + return IAMPolicyStubSettings.defaultExecutorProviderBuilder(); + } + + /** Returns the default service endpoint. */ + public static String getDefaultEndpoint() { + return IAMPolicyStubSettings.getDefaultEndpoint(); + } + + /** Returns the default service scopes. */ + public static List getDefaultServiceScopes() { + return IAMPolicyStubSettings.getDefaultServiceScopes(); + } + + /** Returns a builder for the default credentials for this service. */ + public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { + return IAMPolicyStubSettings.defaultCredentialsProviderBuilder(); + } + + /** Returns a builder for the default ChannelProvider for this service. */ + public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { + return IAMPolicyStubSettings.defaultGrpcTransportProviderBuilder(); + } + + public static TransportChannelProvider defaultTransportChannelProvider() { + return IAMPolicyStubSettings.defaultTransportChannelProvider(); + } + + @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") + public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { + return IAMPolicyStubSettings.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 IAMPolicySettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + } + + /** Builder for IAMPolicySettings. */ + public static class Builder extends ClientSettings.Builder { + + protected Builder() throws IOException { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(IAMPolicyStubSettings.newBuilder(clientContext)); + } + + protected Builder(IAMPolicySettings settings) { + super(settings.getStubSettings().toBuilder()); + } + + protected Builder(IAMPolicyStubSettings.Builder stubSettings) { + super(stubSettings); + } + + private static Builder createDefault() { + return new Builder(IAMPolicyStubSettings.newBuilder()); + } + + public IAMPolicyStubSettings.Builder getStubSettingsBuilder() { + return ((IAMPolicyStubSettings.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 setIamPolicy. */ + public UnaryCallSettings.Builder setIamPolicySettings() { + return getStubSettingsBuilder().setIamPolicySettings(); + } + + /** Returns the builder for the settings used for calls to getIamPolicy. */ + public UnaryCallSettings.Builder getIamPolicySettings() { + return getStubSettingsBuilder().getIamPolicySettings(); + } + + /** Returns the builder for the settings used for calls to testIamPermissions. */ + public UnaryCallSettings.Builder + testIamPermissionsSettings() { + return getStubSettingsBuilder().testIamPermissionsSettings(); + } + + @Override + public IAMPolicySettings build() throws IOException { + return new IAMPolicySettings(this); + } + } +} diff --git a/test/integration/goldens/iam/IAMPolicyStub.java b/test/integration/goldens/iam/IAMPolicyStub.java new file mode 100644 index 0000000000..6cfd45226b --- /dev/null +++ b/test/integration/goldens/iam/IAMPolicyStub.java @@ -0,0 +1,52 @@ +/* + * 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.iam.v1.stub; + +import com.google.api.gax.core.BackgroundResource; +import com.google.api.gax.rpc.UnaryCallable; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import javax.annotation.Generated; + +// AUTO-GENERATED DOCUMENTATION AND CLASS. +/** + * Base stub class for the IAMPolicy service API. + * + *

This class is for advanced usage and reflects the underlying API directly. + */ +@Generated("by gapic-generator-java") +public abstract class IAMPolicyStub implements BackgroundResource { + + public UnaryCallable setIamPolicyCallable() { + throw new UnsupportedOperationException("Not implemented: setIamPolicyCallable()"); + } + + public UnaryCallable getIamPolicyCallable() { + throw new UnsupportedOperationException("Not implemented: getIamPolicyCallable()"); + } + + public UnaryCallable + testIamPermissionsCallable() { + throw new UnsupportedOperationException("Not implemented: testIamPermissionsCallable()"); + } + + @Override + public abstract void close(); +} diff --git a/test/integration/goldens/iam/IAMPolicyStubSettings.java b/test/integration/goldens/iam/IAMPolicyStubSettings.java new file mode 100644 index 0000000000..51fd4491d6 --- /dev/null +++ b/test/integration/goldens/iam/IAMPolicyStubSettings.java @@ -0,0 +1,313 @@ +/* + * 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.iam.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.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.iam.v1.TestIamPermissionsRequest; +import com.google.iam.v1.TestIamPermissionsResponse; +import 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 IAMPolicyStub}. + * + *

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

    + *
  • The default service address (iam-meta-api.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 setIamPolicy to 30 seconds: + * + *

{@code
+ * IAMPolicyStubSettings.Builder iAMPolicySettingsBuilder = IAMPolicyStubSettings.newBuilder();
+ * iAMPolicySettingsBuilder
+ *     .setIamPolicySettings()
+ *     .setRetrySettings(
+ *         iAMPolicySettingsBuilder
+ *             .setIamPolicySettings()
+ *             .getRetrySettings()
+ *             .toBuilder()
+ *             .setTotalTimeout(Duration.ofSeconds(30))
+ *             .build());
+ * IAMPolicyStubSettings iAMPolicySettings = iAMPolicySettingsBuilder.build();
+ * }
+ */ +@Generated("by gapic-generator-java") +public class IAMPolicyStubSettings extends StubSettings { + /** The default scopes of the service. */ + private static final ImmutableList DEFAULT_SERVICE_SCOPES = + ImmutableList.builder().build(); + + private final UnaryCallSettings setIamPolicySettings; + private final UnaryCallSettings getIamPolicySettings; + private final UnaryCallSettings + testIamPermissionsSettings; + + /** Returns the object with the settings used for calls to setIamPolicy. */ + public UnaryCallSettings setIamPolicySettings() { + return setIamPolicySettings; + } + + /** Returns the object with the settings used for calls to getIamPolicy. */ + public UnaryCallSettings getIamPolicySettings() { + return getIamPolicySettings; + } + + /** Returns the object with the settings used for calls to testIamPermissions. */ + public UnaryCallSettings + testIamPermissionsSettings() { + return testIamPermissionsSettings; + } + + @BetaApi("A restructuring of stub classes is planned, so this may break in the future") + public IAMPolicyStub createStub() throws IOException { + if (getTransportChannelProvider() + .getTransportName() + .equals(GrpcTransportChannel.getGrpcTransportName())) { + return GrpcIAMPolicyStub.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 "iam-meta-api.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(IAMPolicyStubSettings.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 IAMPolicyStubSettings(Builder settingsBuilder) throws IOException { + super(settingsBuilder); + + setIamPolicySettings = settingsBuilder.setIamPolicySettings().build(); + getIamPolicySettings = settingsBuilder.getIamPolicySettings().build(); + testIamPermissionsSettings = settingsBuilder.testIamPermissionsSettings().build(); + } + + /** Builder for IAMPolicyStubSettings. */ + public static class Builder extends StubSettings.Builder { + private final ImmutableList> unaryMethodSettingsBuilders; + private final UnaryCallSettings.Builder setIamPolicySettings; + private final UnaryCallSettings.Builder getIamPolicySettings; + private final UnaryCallSettings.Builder + testIamPermissionsSettings; + private static final ImmutableMap> + RETRYABLE_CODE_DEFINITIONS; + + static { + ImmutableMap.Builder> definitions = + ImmutableMap.builder(); + definitions.put( + "retry_policy_0_codes", + ImmutableSet.copyOf(Lists.newArrayList(StatusCode.Code.UNAVAILABLE))); + 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(500L)) + .setRetryDelayMultiplier(2.0) + .setMaxRetryDelay(Duration.ofMillis(10000L)) + .setInitialRpcTimeout(Duration.ofMillis(10000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeout(Duration.ofMillis(10000L)) + .setTotalTimeout(Duration.ofMillis(10000L)) + .build(); + definitions.put("retry_policy_0_params", settings); + RETRY_PARAM_DEFINITIONS = definitions.build(); + } + + protected Builder() { + this(((ClientContext) null)); + } + + protected Builder(ClientContext clientContext) { + super(clientContext); + + setIamPolicySettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + getIamPolicySettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + testIamPermissionsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + setIamPolicySettings, getIamPolicySettings, testIamPermissionsSettings); + initDefaults(this); + } + + protected Builder(IAMPolicyStubSettings settings) { + super(settings); + + setIamPolicySettings = settings.setIamPolicySettings.toBuilder(); + getIamPolicySettings = settings.getIamPolicySettings.toBuilder(); + testIamPermissionsSettings = settings.testIamPermissionsSettings.toBuilder(); + + unaryMethodSettingsBuilders = + ImmutableList.>of( + setIamPolicySettings, getIamPolicySettings, testIamPermissionsSettings); + } + + private static Builder createDefault() { + Builder builder = new Builder(((ClientContext) null)); + + builder.setTransportChannelProvider(defaultTransportChannelProvider()); + builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); + builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); + builder.setEndpoint(getDefaultEndpoint()); + + return initDefaults(builder); + } + + private static Builder initDefaults(Builder builder) { + builder + .setIamPolicySettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); + + builder + .getIamPolicySettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); + + builder + .testIamPermissionsSettings() + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) + .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); + + return builder; + } + + // NEXT_MAJOR_VER: remove 'throws Exception'. + /** + * Applies the given settings updater function to all of the unary API methods in this service. + * + *

Note: This method does not support applying settings to streaming methods. + */ + public Builder applyToAllUnaryMethods( + ApiFunction, Void> settingsUpdater) throws Exception { + super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); + return this; + } + + public ImmutableList> unaryMethodSettingsBuilders() { + return unaryMethodSettingsBuilders; + } + + /** Returns the builder for the settings used for calls to setIamPolicy. */ + public UnaryCallSettings.Builder setIamPolicySettings() { + return setIamPolicySettings; + } + + /** Returns the builder for the settings used for calls to getIamPolicy. */ + public UnaryCallSettings.Builder getIamPolicySettings() { + return getIamPolicySettings; + } + + /** Returns the builder for the settings used for calls to testIamPermissions. */ + public UnaryCallSettings.Builder + testIamPermissionsSettings() { + return testIamPermissionsSettings; + } + + @Override + public IAMPolicyStubSettings build() throws IOException { + return new IAMPolicyStubSettings(this); + } + } +} diff --git a/test/integration/goldens/iam/MockIAMPolicy.java b/test/integration/goldens/iam/MockIAMPolicy.java new file mode 100644 index 0000000000..b7ebc56b18 --- /dev/null +++ b/test/integration/goldens/iam/MockIAMPolicy.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.iam.v1; + +import com.google.api.core.BetaApi; +import com.google.api.gax.grpc.testing.MockGrpcService; +import com.google.protobuf.AbstractMessage; +import io.grpc.ServerServiceDefinition; +import java.util.List; +import javax.annotation.Generated; + +@BetaApi +@Generated("by gapic-generator-java") +public class MockIAMPolicy implements MockGrpcService { + private final MockIAMPolicyImpl serviceImpl; + + public MockIAMPolicy() { + serviceImpl = new MockIAMPolicyImpl(); + } + + @Override + public List getRequests() { + return serviceImpl.getRequests(); + } + + @Override + public void addResponse(AbstractMessage response) { + serviceImpl.addResponse(response); + } + + @Override + public void addException(Exception exception) { + serviceImpl.addException(exception); + } + + @Override + public ServerServiceDefinition getServiceDefinition() { + return serviceImpl.bindService(); + } + + @Override + public void reset() { + serviceImpl.reset(); + } +} diff --git a/test/integration/goldens/iam/MockIAMPolicyImpl.java b/test/integration/goldens/iam/MockIAMPolicyImpl.java new file mode 100644 index 0000000000..920aec564d --- /dev/null +++ b/test/integration/goldens/iam/MockIAMPolicyImpl.java @@ -0,0 +1,122 @@ +/* + * 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.iam.v1; + +import com.google.api.core.BetaApi; +import com.google.iam.v1.IAMPolicyGrpc.IAMPolicyImplBase; +import com.google.protobuf.AbstractMessage; +import io.grpc.stub.StreamObserver; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import javax.annotation.Generated; + +@BetaApi +@Generated("by gapic-generator-java") +public class MockIAMPolicyImpl extends IAMPolicyImplBase { + private List requests; + private Queue responses; + + public MockIAMPolicyImpl() { + requests = new ArrayList<>(); + responses = new LinkedList<>(); + } + + public List getRequests() { + return requests; + } + + public void addResponse(AbstractMessage response) { + responses.add(response); + } + + public void setResponses(List responses) { + this.responses = new LinkedList(responses); + } + + public void addException(Exception exception) { + responses.add(exception); + } + + public void reset() { + requests = new ArrayList<>(); + responses = new LinkedList<>(); + } + + @Override + public void setIamPolicy(SetIamPolicyRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof Policy) { + requests.add(request); + responseObserver.onNext(((Policy) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method SetIamPolicy, expected %s or %s", + response.getClass().getName(), + Policy.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void getIamPolicy(GetIamPolicyRequest request, StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof Policy) { + requests.add(request); + responseObserver.onNext(((Policy) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method GetIamPolicy, expected %s or %s", + response.getClass().getName(), + Policy.class.getName(), + Exception.class.getName()))); + } + } + + @Override + public void testIamPermissions( + TestIamPermissionsRequest request, + StreamObserver responseObserver) { + Object response = responses.remove(); + if (response instanceof TestIamPermissionsResponse) { + requests.add(request); + responseObserver.onNext(((TestIamPermissionsResponse) response)); + responseObserver.onCompleted(); + } else if (response instanceof Exception) { + responseObserver.onError(((Exception) response)); + } else { + responseObserver.onError( + new IllegalArgumentException( + String.format( + "Unrecognized response type %s for method TestIamPermissions, expected %s or %s", + response.getClass().getName(), + TestIamPermissionsResponse.class.getName(), + Exception.class.getName()))); + } + } +} diff --git a/test/integration/goldens/iam/PlaceholderFile.java b/test/integration/goldens/iam/PlaceholderFile.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/integration/goldens/iam/gapic_metadata.json b/test/integration/goldens/iam/gapic_metadata.json new file mode 100644 index 0000000000..7169270d1e --- /dev/null +++ b/test/integration/goldens/iam/gapic_metadata.json @@ -0,0 +1,27 @@ +{ + "schema": "1.0", + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "java", + "protoPackage": "google.iam.v1", + "libraryPackage": "com.google.iam.v1", + "services": { + "IAMPolicy": { + "clients": { + "grpc": { + "libraryClient": "IAMPolicyClient", + "rpcs": { + "GetIamPolicy": { + "methods": ["getIamPolicy", "getIamPolicyCallable"] + }, + "SetIamPolicy": { + "methods": ["setIamPolicy", "setIamPolicyCallable"] + }, + "TestIamPermissions": { + "methods": ["testIamPermissions", "testIamPermissionsCallable"] + } + } + } + } + } + } +} \ No newline at end of file diff --git a/test/integration/goldens/iam/package-info.java b/test/integration/goldens/iam/package-info.java new file mode 100644 index 0000000000..45e257e56c --- /dev/null +++ b/test/integration/goldens/iam/package-info.java @@ -0,0 +1,61 @@ +/* + * 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. + * + *

======================= IAMPolicyClient ======================= + * + *

Service Description: ## API Overview + * + *

Manages Identity and Access Management (IAM) policies. + * + *

Any implementation of an API that offers access control features implements the + * google.iam.v1.IAMPolicy interface. + * + *

## Data model + * + *

Access control is applied when a principal (user or service account), takes some action on a + * resource exposed by a service. Resources, identified by URI-like names, are the unit of access + * control specification. Service implementations can choose the granularity of access control and + * the supported permissions for their resources. For example one database service may allow access + * control to be specified only at the Table level, whereas another might allow access control to + * also be specified at the Column level. + * + *

## Policy Structure + * + *

See google.iam.v1.Policy + * + *

This is intentionally not a CRUD style API because access control policies are created and + * deleted implicitly with the resources to which they are attached. + * + *

Sample for IAMPolicyClient: + * + *

{@code
+ * try (IAMPolicyClient iAMPolicyClient = IAMPolicyClient.create()) {
+ *   SetIamPolicyRequest request =
+ *       SetIamPolicyRequest.newBuilder()
+ *           .setResource("SetIamPolicyRequest1223629066".toString())
+ *           .setPolicy(Policy.newBuilder().build())
+ *           .build();
+ *   Policy response = iAMPolicyClient.setIamPolicy(request);
+ * }
+ * }
+ */ +@Generated("by gapic-generator-java") +package com.google.iam.v1; + +import javax.annotation.Generated; diff --git a/test/integration/iam_grpc_service_config.json b/test/integration/iam_grpc_service_config.json new file mode 100644 index 0000000000..caed5be6bb --- /dev/null +++ b/test/integration/iam_grpc_service_config.json @@ -0,0 +1,21 @@ +{ + "methodConfig": [ + { + "name": [ + { + "service": "google.iam.v1.IAMPolicy" + } + ], + "timeout": "10s", + "retryPolicy": { + "maxAttempts": 5, + "initialBackoff": "0.5s", + "maxBackoff": "10s", + "backoffMultiplier": 2.0, + "retryableStatusCodes": [ + "UNAVAILABLE" + ] + } + } + ] +}