Skip to content
This repository has been archived by the owner on Sep 16, 2023. It is now read-only.

Commit

Permalink
samples: Add samples for AnalyzerIamPolicy and AnalyzeIamPolicyLongru…
Browse files Browse the repository at this point in the history
…nning (#459)

* Asset:Add samples for AnalyzerIamPolicy and AnalyzeIamPolicyLongrunning

* samples:Add samples for AnalyzerIamPolicy and AnalyzeIamPolicyLongrunning

* fixing reviewer's comments

* fixing check errors

* catching exceptions specificly
  • Loading branch information
donghez-google committed Dec 8, 2020
1 parent 0cdd449 commit 6aee237
Show file tree
Hide file tree
Showing 4 changed files with 360 additions and 0 deletions.
@@ -0,0 +1,65 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.asset;

// [START asset_quickstart_analyze_iam_policy]
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.asset.v1.AnalyzeIamPolicyRequest;
import com.google.cloud.asset.v1.AnalyzeIamPolicyResponse;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.Options;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.ResourceSelector;
import java.io.IOException;

public class AnalyzeIamPolicyExample {

public static void main(String[] args) {
// TODO(developer): Replace these variables before running the sample.
String scope = "organizations/ORG_ID";
String fullResourceName = "//cloudresourcemanager.googleapis.com/projects/PROJ_ID";
analyzeIamPolicy(scope, fullResourceName);
}

// Analyzes accessible IAM policies that match a request.
public static void analyzeIamPolicy(String scope, String fullResourceName) {
ResourceSelector resourceSelector =
ResourceSelector.newBuilder().setFullResourceName(fullResourceName).build();
Options options = Options.newBuilder().setExpandGroups(true).setOutputGroupEdges(true).build();
IamPolicyAnalysisQuery query =
IamPolicyAnalysisQuery.newBuilder()
.setScope(scope)
.setResourceSelector(resourceSelector)
.setOptions(options)
.build();
AnalyzeIamPolicyRequest request =
AnalyzeIamPolicyRequest.newBuilder().setAnalysisQuery(query).build();

// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (AssetServiceClient client = AssetServiceClient.create()) {
AnalyzeIamPolicyResponse response = client.analyzeIamPolicy(request);
System.out.println("Analyze completed successfully:\n" + response);
} catch (IOException e) {
System.out.println("Failed to create client:\n" + e.toString());
} catch (ApiException e) {
System.out.println("Error during AnalyzeIamPolicy:\n" + e.toString());
}
}
}
// [END asset_quickstart_analyze_iam_policy]
@@ -0,0 +1,88 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.asset;

// [START asset_quickstart_analyze_iam_policy_longrunning_bigquery]
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningRequest;
import com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningResponse;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig;
import com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig.BigQueryDestination;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.Options;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.ResourceSelector;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class AnalyzeIamPolicyLongrunningBigqueryExample {

public static void main(String[] args) {
// TODO(developer): Replace these variables before running the sample.
String scope = "organizations/ORG_ID";
String fullResourceName = "//cloudresourcemanager.googleapis.com/projects/PROJ_ID";
String dataset = "projects/PROJ_ID/datasets/DATASET_ID";
String tablePrefix = "TABLE_PREFIX";
analyzeIamPolicyLongrunning(scope, fullResourceName, dataset, tablePrefix);
}

// Analyzes accessible IAM policies that match a request.
public static void analyzeIamPolicyLongrunning(
String scope, String fullResourceName, String dataset, String tablePrefix) {
ResourceSelector resourceSelector =
ResourceSelector.newBuilder().setFullResourceName(fullResourceName).build();
Options options = Options.newBuilder().setExpandGroups(true).setOutputGroupEdges(true).build();
IamPolicyAnalysisQuery query =
IamPolicyAnalysisQuery.newBuilder()
.setScope(scope)
.setResourceSelector(resourceSelector)
.setOptions(options)
.build();

BigQueryDestination bigQueryDestination =
BigQueryDestination.newBuilder().setDataset(dataset).setTablePrefix(tablePrefix).build();
IamPolicyAnalysisOutputConfig outputConfig =
IamPolicyAnalysisOutputConfig.newBuilder()
.setBigqueryDestination(bigQueryDestination)
.build();

AnalyzeIamPolicyLongrunningRequest request =
AnalyzeIamPolicyLongrunningRequest.newBuilder()
.setAnalysisQuery(query)
.setOutputConfig(outputConfig)
.build();

// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (AssetServiceClient client = AssetServiceClient.create()) {
OperationFuture<AnalyzeIamPolicyLongrunningResponse, AnalyzeIamPolicyLongrunningRequest>
future = client.analyzeIamPolicyLongrunningAsync(request);
System.out.println("Analyze completed successfully:\n" + future.getMetadata().get());
} catch (IOException e) {
System.out.println("Failed to create client:\n" + e.toString());
} catch (InterruptedException e) {
System.out.println("Operation was interrupted:\n" + e.toString());
} catch (ExecutionException e) {
System.out.println("Operation was aborted:\n" + e.toString());
} catch (ApiException e) {
System.out.println("Error during AnalyzeIamPolicyLongrunning:\n" + e.toString());
}
}
}
// [END asset_quickstart_analyze_iam_policy_longrunning_bigquery]
@@ -0,0 +1,86 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.asset;

// [START asset_quickstart_analyze_iam_policy_longrunning_gcs]
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningRequest;
import com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningResponse;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig;
import com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig.GcsDestination;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.Options;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.ResourceSelector;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class AnalyzeIamPolicyLongrunningGcsExample {

public static void main(String[] args) {
// TODO(developer): Replace these variables before running the sample.
String scope = "organizations/ORG_ID";
String fullResourceName = "//cloudresourcemanager.googleapis.com/projects/PROJ_ID";
String uri = "gs://BUCKET_NAME/OBJECT_NAME";
analyzeIamPolicyLongrunning(scope, fullResourceName, uri);
}

// Analyzes accessible IAM policies that match a request.
public static void analyzeIamPolicyLongrunning(
String scope, String fullResourceName, String uri) {
ResourceSelector resourceSelector =
ResourceSelector.newBuilder().setFullResourceName(fullResourceName).build();
Options options = Options.newBuilder().setExpandGroups(true).setOutputGroupEdges(true).build();
IamPolicyAnalysisQuery query =
IamPolicyAnalysisQuery.newBuilder()
.setScope(scope)
.setResourceSelector(resourceSelector)
.setOptions(options)
.build();

GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(uri).build();
IamPolicyAnalysisOutputConfig outputConfig =
IamPolicyAnalysisOutputConfig.newBuilder()
.setGcsDestination(GcsDestination.newBuilder().setUri(uri).build())
.build();

AnalyzeIamPolicyLongrunningRequest request =
AnalyzeIamPolicyLongrunningRequest.newBuilder()
.setAnalysisQuery(query)
.setOutputConfig(outputConfig)
.build();

// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (AssetServiceClient client = AssetServiceClient.create()) {
OperationFuture<AnalyzeIamPolicyLongrunningResponse, AnalyzeIamPolicyLongrunningRequest>
future = client.analyzeIamPolicyLongrunningAsync(request);
System.out.println("Analyze completed successfully:\n" + future.getMetadata().get());
} catch (IOException e) {
System.out.println("Failed to create client:\n" + e.toString());
} catch (InterruptedException e) {
System.out.println("Operation was interrupted:\n" + e.toString());
} catch (ExecutionException e) {
System.out.println("Operation was aborted:\n" + e.toString());
} catch (ApiException e) {
System.out.println("Error during AnalyzeIamPolicyLongrunning:\n" + e.toString());
}
}
}
// [END asset_quickstart_analyze_iam_policy_longrunning_gcs]
121 changes: 121 additions & 0 deletions samples/snippets/src/test/java/com/example/asset/Analyze.java
@@ -0,0 +1,121 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.asset;

import static com.google.common.truth.Truth.assertThat;

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQuery.DatasetDeleteOption;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.DatasetId;
import com.google.cloud.bigquery.DatasetInfo;
import com.google.cloud.bigquery.testing.RemoteBigQueryHelper;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.BlobListOption;
import com.google.cloud.storage.StorageOptions;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for search samples. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class Analyze {

private static final String projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
private static final String scope = "projects/" + projectId;
private static final String fullResourceName =
"//cloudresourcemanager.googleapis.com/projects/" + projectId;

private ByteArrayOutputStream bout;
private PrintStream out;

private static final void deleteObjects(String bucketName, String objectName) {
Storage storage = StorageOptions.getDefaultInstance().getService();
Iterable<Blob> blobs =
storage
.list(
bucketName,
BlobListOption.versions(true),
BlobListOption.currentDirectory(),
BlobListOption.prefix(objectName))
.getValues();
for (BlobInfo info : blobs) {
storage.delete(info.getBlobId());
}
}

@Before
public void setUp() {
bout = new ByteArrayOutputStream();
out = new PrintStream(bout);
System.setOut(out);
}

@After
public void tearDown() {
System.setOut(null);
bout.reset();
}

@Test
public void testAnalyzeIamPolicyExample() throws Exception {
AnalyzeIamPolicyExample.analyzeIamPolicy(scope, fullResourceName);
String got = bout.toString();
assertThat(got).contains(fullResourceName);
}

@Test
public void testAnalyzeIamPolicyLongrunningBigQueryExample() throws Exception {
String datasetName = RemoteBigQueryHelper.generateDatasetName();
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
if (bigquery.getDataset(datasetName) == null) {
bigquery.create(DatasetInfo.newBuilder(datasetName).build());
}

String dataset = "projects/" + projectId + "/datasets/" + datasetName;
String tablePrefix = "client_library_table";
AnalyzeIamPolicyLongrunningBigqueryExample.analyzeIamPolicyLongrunning(
scope, fullResourceName, dataset, tablePrefix);
String got = bout.toString();
assertThat(got).contains("output_config");

DatasetId datasetId = DatasetId.of(bigquery.getOptions().getProjectId(), datasetName);
bigquery.delete(datasetId, DatasetDeleteOption.deleteContents());
}

@Test
public void testAnalyzeIamPolicyLongrunningGcsExample() throws Exception {
// The developer needs to have bucket create permission or use an exsiting bucket.
String bucketName = "java-docs-samples-testing";
String objectName = UUID.randomUUID().toString();

String uri = "gs://" + bucketName + "/" + objectName;
AnalyzeIamPolicyLongrunningGcsExample.analyzeIamPolicyLongrunning(scope, fullResourceName, uri);
String got = bout.toString();
assertThat(got).contains("output_config");

deleteObjects(bucketName, objectName);
}
}

0 comments on commit 6aee237

Please sign in to comment.