Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(bigquery): add table/view samples to cloud-client (3/3) #10036

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bigquery/cloud-client/snippets/pom.xml
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
<?xml version='1.0' encoding='UTF-8'?>
<!--
Copyright 2025 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.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright 2025 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.bigquery;

// [START bigquery_view_table_or_view_access_policy]

import com.google.cloud.Policy;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.TableId;

public class GetTableOrViewAccessPolicy {

public static void main(String[] args) {
// TODO(developer): Replace these variables before running the sample.
// Project, dataset and resource (table or view) from which to get the access policy.
String projectId = "MY_PROJECT_ID";
String datasetName = "MY_DATASET_NAME";
String resourceName = "MY_RESOURCE_NAME";
Comment on lines +30 to +34

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider using environment variables for these values instead of hardcoding them, to make the sample more configurable and secure. This would also align with the checklist item regarding environment variables.

Suggested change
// TODO(developer): Replace these variables before running the sample.
// Project, dataset and resource (table or view) from which to get the access policy.
String projectId = "MY_PROJECT_ID";
String datasetName = "MY_DATASET_NAME";
String resourceName = "MY_RESOURCE_NAME";
// Project, dataset and resource (table or view) from which to get the access policy.
String projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
String datasetName = System.getenv("BIGQUERY_DATASET_NAME");
String resourceName = System.getenv("BIGQUERY_RESOURCE_NAME");

getTableOrViewAccessPolicy(projectId, datasetName, resourceName);
}

public static void getTableOrViewAccessPolicy(
String projectId, String datasetName, String resourceName) {
try {
// Initialize client that will be used to send requests. This client only needs
// to be created once, and can be reused for multiple requests.
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

// Create table identity given the projectId, the datasetName and the resourceName.
TableId tableId = TableId.of(projectId, datasetName, resourceName);

// Get the table IAM policy.
Policy policy = bigquery.getIamPolicy(tableId);

// Show policy details.
// Find more information about the Policy Class here:
// https://cloud.google.com/java/docs/reference/google-cloud-core/latest/com.google.cloud.Policy
System.out.println(
"IAM policy info of resource \"" + resourceName + "\" retrieved succesfully");
System.out.println();
System.out.println("IAM policy info: " + policy.toString());
} catch (BigQueryException e) {
System.out.println("IAM policy info not retrieved. \n" + e.toString());
}
}
}
// [END bigquery_view_table_or_view_access_policy]
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright 2025 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.bigquery;

// [START bigquery_grant_access_to_table_or_view]
import com.google.cloud.Identity;
import com.google.cloud.Policy;
import com.google.cloud.Role;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.TableId;

public class GrantAccessToTableOrView {

public static void main(String[] args) {
// TODO(developer): Replace these variables before running the sample.
// Project, dataset and resource (table or view) from which to get the access policy.
String projectId = "MY_PROJECT_ID";
String datasetName = "MY_DATASET_NAME";
String resourceName = "MY_TABLE_NAME";
Comment on lines +31 to +35

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider using environment variables for these values instead of hardcoding them, to make the sample more configurable and secure. This would also align with the checklist item regarding environment variables.

Suggested change
// TODO(developer): Replace these variables before running the sample.
// Project, dataset and resource (table or view) from which to get the access policy.
String projectId = "MY_PROJECT_ID";
String datasetName = "MY_DATASET_NAME";
String resourceName = "MY_TABLE_NAME";
// Project, dataset and resource (table or view) from which to get the access policy.
String projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
String datasetName = System.getenv("BIGQUERY_DATASET_NAME");
String resourceName = System.getenv("BIGQUERY_RESOURCE_NAME");

// Role to add to the policy access
Role role = Role.of("roles/bigquery.dataViewer");
// Identity to add to the policy access
Identity identity = Identity.user("[email protected]");
Comment on lines +37 to +39

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider using environment variables for these values instead of hardcoding them, to make the sample more configurable and secure. This would also align with the checklist item regarding environment variables.

Suggested change
Role role = Role.of("roles/bigquery.dataViewer");
// Identity to add to the policy access
Identity identity = Identity.user("[email protected]");
// Role to add to the policy access
Role role = Role.of(System.getenv("BIGQUERY_ROLE"));
// Identity to add to the policy access
Identity identity = Identity.user(System.getenv("BIGQUERY_USER"));

grantAccessToTableOrView(projectId, datasetName, resourceName, role, identity);
}

public static void grantAccessToTableOrView(
String projectId, String datasetName, String resourceName, Role role, Identity identity) {
try {
// Initialize client that will be used to send requests. This client only needs
// to be created once, and can be reused for multiple requests.
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

// Create table identity given the projectId, the datasetName and the resourceName.
TableId tableId = TableId.of(projectId, datasetName, resourceName);

// Add new user identity to current IAM policy.
Policy policy = bigquery.getIamPolicy(tableId);
policy = policy.toBuilder().addIdentity(role, identity).build();

// Update the IAM policy by setting the new one.
bigquery.setIamPolicy(tableId, policy);

System.out.println("IAM policy of resource \"" + resourceName + "\" updated successfully");
} catch (BigQueryException e) {
System.out.println("IAM policy was not updated. \n" + e.toString());
}
}
}
// [END bigquery_grant_access_to_table_or_view]
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Copyright 2025 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.bigquery;

// [START bigquery_revoke_access_to_table_or_view]
import com.google.cloud.Identity;
import com.google.cloud.Policy;
import com.google.cloud.Role;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.TableId;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class RevokeAccessToTableOrView {

public static void main(String[] args) {
// TODO(developer): Replace these variables before running the sample.
// Project, dataset and resource (table or view) from which to get the access policy
String projectId = "MY_PROJECT_ID";
String datasetName = "MY_DATASET_NAME";
String resourceName = "MY_RESOURCE_NAME";
Comment on lines +35 to +39

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider using environment variables for these values instead of hardcoding them, to make the sample more configurable and secure. This would also align with the checklist item regarding environment variables.

Suggested change
// TODO(developer): Replace these variables before running the sample.
// Project, dataset and resource (table or view) from which to get the access policy
String projectId = "MY_PROJECT_ID";
String datasetName = "MY_DATASET_NAME";
String resourceName = "MY_RESOURCE_NAME";
// Project, dataset and resource (table or view) from which to get the access policy
String projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
String datasetName = System.getenv("BIGQUERY_DATASET_NAME");
String resourceName = System.getenv("BIGQUERY_RESOURCE_NAME");

// Role to remove from the access policy
Role role = Role.of("roles/bigquery.dataViewer");
// Identity to remove from the access policy
Identity user = Identity.user("[email protected]");
Comment on lines +41 to +43

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider using environment variables for these values instead of hardcoding them, to make the sample more configurable and secure. This would also align with the checklist item regarding environment variables.

Suggested change
Role role = Role.of("roles/bigquery.dataViewer");
// Identity to remove from the access policy
Identity user = Identity.user("[email protected]");
// Role to remove from the access policy
Role role = Role.of(System.getenv("BIGQUERY_ROLE"));
// Identity to remove from the access policy
Identity user = Identity.user(System.getenv("BIGQUERY_USER"));

revokeAccessToTableOrView(projectId, datasetName, resourceName, role, user);
}

public static void revokeAccessToTableOrView(
String projectId, String datasetName, String resourceName, Role role, Identity identity) {
try {
// Initialize client that will be used to send requests. This client only needs
// to be created once, and can be reused for multiple requests.
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

// Create table identity given the projectId, the datasetName and the resourceName.
TableId tableId = TableId.of(projectId, datasetName, resourceName);

// Remove either identities or roles, or both from bindings and replace it in
// the current IAM policy.
Policy policy = bigquery.getIamPolicy(tableId);
// Create a copy of a inmutable map.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Typo: inmutable should be immutable.

Suggested change
// Create a copy of a inmutable map.
// Create a copy of an immutable map.

Map<Role, Set<Identity>> bindings = new HashMap<>(policy.getBindings());

// Remove all identities with a specific role.
bindings.remove(role);
// Update bindings.
policy = policy.toBuilder().setBindings(bindings).build();

// Remove one identity in all the existing roles.
for (Role roleKey : bindings.keySet()) {
if (bindings.get(roleKey).contains(identity)) {
// Create a copy of a inmutable set if the identity is present in the role.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Typo: inmutable should be immutable.

Suggested change
// Create a copy of a inmutable set if the identity is present in the role.
// Create a copy of an immutable set if the identity is present in the role.

Set<Identity> identities = new HashSet<>(bindings.get(roleKey));
// Remove identity.
identities.remove(identity);
bindings.put(roleKey, identities);
if (bindings.get(roleKey).isEmpty()) {
// Remove the role if it has no identities.
bindings.remove(roleKey);
}
}
}
// Update bindings.
policy = policy.toBuilder().setBindings(bindings).build();

// Update the IAM policy by setting the new one.
bigquery.setIamPolicy(tableId, policy);

System.out.println("IAM policy of resource \"" + resourceName + "\" updated successfully");
} catch (BigQueryException e) {
System.out.println("IAM policy was not updated. \n" + e.toString());
}
}
}
// [END bigquery_revoke_access_to_table_or_view]
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* Copyright 2025 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.bigquery;

import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;

import com.google.cloud.bigquery.Field;
import com.google.cloud.bigquery.Schema;
import com.google.cloud.bigquery.StandardSQLTypeName;
import com.google.cloud.bigquery.testing.RemoteBigQueryHelper;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class GetTableOrViewAccessPolicyIT {

private final Logger log = Logger.getLogger(this.getClass().getName());
private String datasetName;
private String tableName;
private String viewName;
private ByteArrayOutputStream bout;
private PrintStream out;
private PrintStream originalPrintStream;

private static final String GOOGLE_CLOUD_PROJECT = System.getenv("GOOGLE_CLOUD_PROJECT");

private static String requireEnvVar(String varName) {
String value = System.getenv(varName);
assertNotNull(
"Environment variable " + varName + " is required to perform these tests.",
System.getenv(varName));
return value;
}

@BeforeClass
public static void checkRequirements() {
requireEnvVar("GOOGLE_CLOUD_PROJECT");
}

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

// Create temporary dataset.
datasetName = RemoteBigQueryHelper.generateDatasetName();
Util.setUpTest_createDataset(GOOGLE_CLOUD_PROJECT, datasetName);

// Create temporary table.
tableName = "get_access_policy_table_test_" + UUID.randomUUID().toString().substring(0, 8);
Schema schema =
Schema.of(
Field.of("stringField", StandardSQLTypeName.STRING),
Field.of("isBooleanField", StandardSQLTypeName.BOOL));
Util.setUpTest_createTable(GOOGLE_CLOUD_PROJECT, datasetName, tableName, schema);

// Create a temporary view.
viewName = "get_access_policy_view_test_" + UUID.randomUUID().toString().substring(0, 8);
String query =
String.format("SELECT stringField, isBooleanField FROM %s.%s", datasetName, tableName);
Util.setUpTest_createView(GOOGLE_CLOUD_PROJECT, datasetName, viewName, query);
}

@After
public void tearDown() {
// Clean up.
Util.tearDownTest_deleteTableOrView(GOOGLE_CLOUD_PROJECT, datasetName, viewName);
Util.tearDownTest_deleteTableOrView(GOOGLE_CLOUD_PROJECT, datasetName, tableName);
Util.tearDownTest_deleteDataset(GOOGLE_CLOUD_PROJECT, datasetName);

// Restores print statements to the original output stream.
System.out.flush();
System.setOut(originalPrintStream);
log.log(Level.INFO, bout.toString());
}

@Test
public void testGetTableOrViewAccessPolicy_getTableAccessPolicy() {
GetTableOrViewAccessPolicy.getTableOrViewAccessPolicy(
GOOGLE_CLOUD_PROJECT, datasetName, tableName);
assertThat(bout.toString())
.contains("IAM policy info of resource \"" + tableName + "\" retrieved succesfully");
}

@Test
public void testGetTableOrViewAccessPolicy_getViewAccessPolicy() {
GetTableOrViewAccessPolicy.getTableOrViewAccessPolicy(
GOOGLE_CLOUD_PROJECT, datasetName, viewName);
assertThat(bout.toString())
.contains("IAM policy info of resource \"" + viewName + "\" retrieved succesfully");
}
}
Loading