Skip to content

Commit eb18721

Browse files
donghez-googleminherz
authored andcommitted
samples: Add samples for AnalyzerIamPolicy and AnalyzeIamPolicyLongrunning (#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
1 parent ba8086c commit eb18721

File tree

4 files changed

+360
-0
lines changed

4 files changed

+360
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.asset;
18+
19+
// [START asset_quickstart_analyze_iam_policy]
20+
import com.google.api.gax.rpc.ApiException;
21+
import com.google.cloud.asset.v1.AnalyzeIamPolicyRequest;
22+
import com.google.cloud.asset.v1.AnalyzeIamPolicyResponse;
23+
import com.google.cloud.asset.v1.AssetServiceClient;
24+
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery;
25+
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.Options;
26+
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.ResourceSelector;
27+
import java.io.IOException;
28+
29+
public class AnalyzeIamPolicyExample {
30+
31+
public static void main(String[] args) {
32+
// TODO(developer): Replace these variables before running the sample.
33+
String scope = "organizations/ORG_ID";
34+
String fullResourceName = "//cloudresourcemanager.googleapis.com/projects/PROJ_ID";
35+
analyzeIamPolicy(scope, fullResourceName);
36+
}
37+
38+
// Analyzes accessible IAM policies that match a request.
39+
public static void analyzeIamPolicy(String scope, String fullResourceName) {
40+
ResourceSelector resourceSelector =
41+
ResourceSelector.newBuilder().setFullResourceName(fullResourceName).build();
42+
Options options = Options.newBuilder().setExpandGroups(true).setOutputGroupEdges(true).build();
43+
IamPolicyAnalysisQuery query =
44+
IamPolicyAnalysisQuery.newBuilder()
45+
.setScope(scope)
46+
.setResourceSelector(resourceSelector)
47+
.setOptions(options)
48+
.build();
49+
AnalyzeIamPolicyRequest request =
50+
AnalyzeIamPolicyRequest.newBuilder().setAnalysisQuery(query).build();
51+
52+
// Initialize client that will be used to send requests. This client only needs to be created
53+
// once, and can be reused for multiple requests. After completing all of your requests, call
54+
// the "close" method on the client to safely clean up any remaining background resources.
55+
try (AssetServiceClient client = AssetServiceClient.create()) {
56+
AnalyzeIamPolicyResponse response = client.analyzeIamPolicy(request);
57+
System.out.println("Analyze completed successfully:\n" + response);
58+
} catch (IOException e) {
59+
System.out.println("Failed to create client:\n" + e.toString());
60+
} catch (ApiException e) {
61+
System.out.println("Error during AnalyzeIamPolicy:\n" + e.toString());
62+
}
63+
}
64+
}
65+
// [END asset_quickstart_analyze_iam_policy]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.asset;
18+
19+
// [START asset_quickstart_analyze_iam_policy_longrunning_bigquery]
20+
import com.google.api.gax.longrunning.OperationFuture;
21+
import com.google.api.gax.rpc.ApiException;
22+
import com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningRequest;
23+
import com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningResponse;
24+
import com.google.cloud.asset.v1.AssetServiceClient;
25+
import com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig;
26+
import com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig.BigQueryDestination;
27+
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery;
28+
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.Options;
29+
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.ResourceSelector;
30+
import java.io.IOException;
31+
import java.util.concurrent.ExecutionException;
32+
33+
public class AnalyzeIamPolicyLongrunningBigqueryExample {
34+
35+
public static void main(String[] args) {
36+
// TODO(developer): Replace these variables before running the sample.
37+
String scope = "organizations/ORG_ID";
38+
String fullResourceName = "//cloudresourcemanager.googleapis.com/projects/PROJ_ID";
39+
String dataset = "projects/PROJ_ID/datasets/DATASET_ID";
40+
String tablePrefix = "TABLE_PREFIX";
41+
analyzeIamPolicyLongrunning(scope, fullResourceName, dataset, tablePrefix);
42+
}
43+
44+
// Analyzes accessible IAM policies that match a request.
45+
public static void analyzeIamPolicyLongrunning(
46+
String scope, String fullResourceName, String dataset, String tablePrefix) {
47+
ResourceSelector resourceSelector =
48+
ResourceSelector.newBuilder().setFullResourceName(fullResourceName).build();
49+
Options options = Options.newBuilder().setExpandGroups(true).setOutputGroupEdges(true).build();
50+
IamPolicyAnalysisQuery query =
51+
IamPolicyAnalysisQuery.newBuilder()
52+
.setScope(scope)
53+
.setResourceSelector(resourceSelector)
54+
.setOptions(options)
55+
.build();
56+
57+
BigQueryDestination bigQueryDestination =
58+
BigQueryDestination.newBuilder().setDataset(dataset).setTablePrefix(tablePrefix).build();
59+
IamPolicyAnalysisOutputConfig outputConfig =
60+
IamPolicyAnalysisOutputConfig.newBuilder()
61+
.setBigqueryDestination(bigQueryDestination)
62+
.build();
63+
64+
AnalyzeIamPolicyLongrunningRequest request =
65+
AnalyzeIamPolicyLongrunningRequest.newBuilder()
66+
.setAnalysisQuery(query)
67+
.setOutputConfig(outputConfig)
68+
.build();
69+
70+
// Initialize client that will be used to send requests. This client only needs to be created
71+
// once, and can be reused for multiple requests. After completing all of your requests, call
72+
// the "close" method on the client to safely clean up any remaining background resources.
73+
try (AssetServiceClient client = AssetServiceClient.create()) {
74+
OperationFuture<AnalyzeIamPolicyLongrunningResponse, AnalyzeIamPolicyLongrunningRequest>
75+
future = client.analyzeIamPolicyLongrunningAsync(request);
76+
System.out.println("Analyze completed successfully:\n" + future.getMetadata().get());
77+
} catch (IOException e) {
78+
System.out.println("Failed to create client:\n" + e.toString());
79+
} catch (InterruptedException e) {
80+
System.out.println("Operation was interrupted:\n" + e.toString());
81+
} catch (ExecutionException e) {
82+
System.out.println("Operation was aborted:\n" + e.toString());
83+
} catch (ApiException e) {
84+
System.out.println("Error during AnalyzeIamPolicyLongrunning:\n" + e.toString());
85+
}
86+
}
87+
}
88+
// [END asset_quickstart_analyze_iam_policy_longrunning_bigquery]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.asset;
18+
19+
// [START asset_quickstart_analyze_iam_policy_longrunning_gcs]
20+
import com.google.api.gax.longrunning.OperationFuture;
21+
import com.google.api.gax.rpc.ApiException;
22+
import com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningRequest;
23+
import com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningResponse;
24+
import com.google.cloud.asset.v1.AssetServiceClient;
25+
import com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig;
26+
import com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig.GcsDestination;
27+
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery;
28+
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.Options;
29+
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.ResourceSelector;
30+
import java.io.IOException;
31+
import java.util.concurrent.ExecutionException;
32+
33+
public class AnalyzeIamPolicyLongrunningGcsExample {
34+
35+
public static void main(String[] args) {
36+
// TODO(developer): Replace these variables before running the sample.
37+
String scope = "organizations/ORG_ID";
38+
String fullResourceName = "//cloudresourcemanager.googleapis.com/projects/PROJ_ID";
39+
String uri = "gs://BUCKET_NAME/OBJECT_NAME";
40+
analyzeIamPolicyLongrunning(scope, fullResourceName, uri);
41+
}
42+
43+
// Analyzes accessible IAM policies that match a request.
44+
public static void analyzeIamPolicyLongrunning(
45+
String scope, String fullResourceName, String uri) {
46+
ResourceSelector resourceSelector =
47+
ResourceSelector.newBuilder().setFullResourceName(fullResourceName).build();
48+
Options options = Options.newBuilder().setExpandGroups(true).setOutputGroupEdges(true).build();
49+
IamPolicyAnalysisQuery query =
50+
IamPolicyAnalysisQuery.newBuilder()
51+
.setScope(scope)
52+
.setResourceSelector(resourceSelector)
53+
.setOptions(options)
54+
.build();
55+
56+
GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(uri).build();
57+
IamPolicyAnalysisOutputConfig outputConfig =
58+
IamPolicyAnalysisOutputConfig.newBuilder()
59+
.setGcsDestination(GcsDestination.newBuilder().setUri(uri).build())
60+
.build();
61+
62+
AnalyzeIamPolicyLongrunningRequest request =
63+
AnalyzeIamPolicyLongrunningRequest.newBuilder()
64+
.setAnalysisQuery(query)
65+
.setOutputConfig(outputConfig)
66+
.build();
67+
68+
// Initialize client that will be used to send requests. This client only needs to be created
69+
// once, and can be reused for multiple requests. After completing all of your requests, call
70+
// the "close" method on the client to safely clean up any remaining background resources.
71+
try (AssetServiceClient client = AssetServiceClient.create()) {
72+
OperationFuture<AnalyzeIamPolicyLongrunningResponse, AnalyzeIamPolicyLongrunningRequest>
73+
future = client.analyzeIamPolicyLongrunningAsync(request);
74+
System.out.println("Analyze completed successfully:\n" + future.getMetadata().get());
75+
} catch (IOException e) {
76+
System.out.println("Failed to create client:\n" + e.toString());
77+
} catch (InterruptedException e) {
78+
System.out.println("Operation was interrupted:\n" + e.toString());
79+
} catch (ExecutionException e) {
80+
System.out.println("Operation was aborted:\n" + e.toString());
81+
} catch (ApiException e) {
82+
System.out.println("Error during AnalyzeIamPolicyLongrunning:\n" + e.toString());
83+
}
84+
}
85+
}
86+
// [END asset_quickstart_analyze_iam_policy_longrunning_gcs]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.asset;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
21+
import com.google.cloud.bigquery.BigQuery;
22+
import com.google.cloud.bigquery.BigQuery.DatasetDeleteOption;
23+
import com.google.cloud.bigquery.BigQueryOptions;
24+
import com.google.cloud.bigquery.DatasetId;
25+
import com.google.cloud.bigquery.DatasetInfo;
26+
import com.google.cloud.bigquery.testing.RemoteBigQueryHelper;
27+
import com.google.cloud.storage.Blob;
28+
import com.google.cloud.storage.BlobInfo;
29+
import com.google.cloud.storage.Storage;
30+
import com.google.cloud.storage.Storage.BlobListOption;
31+
import com.google.cloud.storage.StorageOptions;
32+
import java.io.ByteArrayOutputStream;
33+
import java.io.PrintStream;
34+
import java.util.UUID;
35+
import org.junit.After;
36+
import org.junit.Before;
37+
import org.junit.Test;
38+
import org.junit.runner.RunWith;
39+
import org.junit.runners.JUnit4;
40+
41+
/** Tests for search samples. */
42+
@RunWith(JUnit4.class)
43+
@SuppressWarnings("checkstyle:abbreviationaswordinname")
44+
public class Analyze {
45+
46+
private static final String projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
47+
private static final String scope = "projects/" + projectId;
48+
private static final String fullResourceName =
49+
"//cloudresourcemanager.googleapis.com/projects/" + projectId;
50+
51+
private ByteArrayOutputStream bout;
52+
private PrintStream out;
53+
54+
private static final void deleteObjects(String bucketName, String objectName) {
55+
Storage storage = StorageOptions.getDefaultInstance().getService();
56+
Iterable<Blob> blobs =
57+
storage
58+
.list(
59+
bucketName,
60+
BlobListOption.versions(true),
61+
BlobListOption.currentDirectory(),
62+
BlobListOption.prefix(objectName))
63+
.getValues();
64+
for (BlobInfo info : blobs) {
65+
storage.delete(info.getBlobId());
66+
}
67+
}
68+
69+
@Before
70+
public void setUp() {
71+
bout = new ByteArrayOutputStream();
72+
out = new PrintStream(bout);
73+
System.setOut(out);
74+
}
75+
76+
@After
77+
public void tearDown() {
78+
System.setOut(null);
79+
bout.reset();
80+
}
81+
82+
@Test
83+
public void testAnalyzeIamPolicyExample() throws Exception {
84+
AnalyzeIamPolicyExample.analyzeIamPolicy(scope, fullResourceName);
85+
String got = bout.toString();
86+
assertThat(got).contains(fullResourceName);
87+
}
88+
89+
@Test
90+
public void testAnalyzeIamPolicyLongrunningBigQueryExample() throws Exception {
91+
String datasetName = RemoteBigQueryHelper.generateDatasetName();
92+
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
93+
if (bigquery.getDataset(datasetName) == null) {
94+
bigquery.create(DatasetInfo.newBuilder(datasetName).build());
95+
}
96+
97+
String dataset = "projects/" + projectId + "/datasets/" + datasetName;
98+
String tablePrefix = "client_library_table";
99+
AnalyzeIamPolicyLongrunningBigqueryExample.analyzeIamPolicyLongrunning(
100+
scope, fullResourceName, dataset, tablePrefix);
101+
String got = bout.toString();
102+
assertThat(got).contains("output_config");
103+
104+
DatasetId datasetId = DatasetId.of(bigquery.getOptions().getProjectId(), datasetName);
105+
bigquery.delete(datasetId, DatasetDeleteOption.deleteContents());
106+
}
107+
108+
@Test
109+
public void testAnalyzeIamPolicyLongrunningGcsExample() throws Exception {
110+
// The developer needs to have bucket create permission or use an exsiting bucket.
111+
String bucketName = "java-docs-samples-testing";
112+
String objectName = UUID.randomUUID().toString();
113+
114+
String uri = "gs://" + bucketName + "/" + objectName;
115+
AnalyzeIamPolicyLongrunningGcsExample.analyzeIamPolicyLongrunning(scope, fullResourceName, uri);
116+
String got = bout.toString();
117+
assertThat(got).contains("output_config");
118+
119+
deleteObjects(bucketName, objectName);
120+
}
121+
}

0 commit comments

Comments
 (0)