Skip to content

Commit 65dffac

Browse files
author
Praful Makani
authored
docs(samples): add auth user flow and query (#478)
* docs(samples): add auth user flow and query * docs(samples): add dependencies * docs(samples): rename methods * docs(samples): address feedback * docs(samples): set auto * docs(samples): modified code and remove deps
1 parent 9253218 commit 65dffac

File tree

5 files changed

+280
-2
lines changed

5 files changed

+280
-2
lines changed

samples/install-without-bom/pom.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,16 @@
4949
</dependency>
5050
<!-- [END bigquery_install_without_bom] -->
5151

52+
<dependency>
53+
<groupId>com.google.oauth-client</groupId>
54+
<artifactId>google-oauth-client-java6</artifactId>
55+
<version>1.30.6</version>
56+
</dependency>
57+
<dependency>
58+
<groupId>com.google.oauth-client</groupId>
59+
<artifactId>google-oauth-client-jetty</artifactId>
60+
<version>1.30.6</version>
61+
</dependency>
5262
<!-- Test dependencies -->
5363
<dependency>
5464
<groupId>junit</groupId>

samples/snapshot/pom.xml

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,16 @@
4747
<version>1.116.7-SNAPSHOT</version>
4848
</dependency>
4949
<!-- {x-version-update-end} -->
50-
50+
<dependency>
51+
<groupId>com.google.oauth-client</groupId>
52+
<artifactId>google-oauth-client-java6</artifactId>
53+
<version>1.30.6</version>
54+
</dependency>
55+
<dependency>
56+
<groupId>com.google.oauth-client</groupId>
57+
<artifactId>google-oauth-client-jetty</artifactId>
58+
<version>1.30.6</version>
59+
</dependency>
5160
<!-- Test dependencies -->
5261
<dependency>
5362
<groupId>junit</groupId>
@@ -61,7 +70,6 @@
6170
<version>1.0.1</version>
6271
<scope>test</scope>
6372
</dependency>
64-
6573
</dependencies>
6674

6775
<!-- compile and run all snippet tests -->

samples/snippets/pom.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,16 @@
5959
<!-- [END bigquery_java_dependencies] -->
6060
<!-- [END bigquery_install_with_bom] -->
6161

62+
<dependency>
63+
<groupId>com.google.oauth-client</groupId>
64+
<artifactId>google-oauth-client-java6</artifactId>
65+
<version>1.30.6</version>
66+
</dependency>
67+
<dependency>
68+
<groupId>com.google.oauth-client</groupId>
69+
<artifactId>google-oauth-client-jetty</artifactId>
70+
<version>1.30.6</version>
71+
</dependency>
6272
<!-- Test dependencies -->
6373
<dependency>
6474
<groupId>junit</groupId>
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
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.bigquery;
18+
19+
// [START bigquery_auth_user_flow]
20+
import com.google.api.client.auth.oauth2.Credential;
21+
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
22+
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
23+
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
24+
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
25+
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
26+
import com.google.api.client.json.JsonFactory;
27+
import com.google.api.client.json.jackson2.JacksonFactory;
28+
import com.google.api.client.util.store.FileDataStoreFactory;
29+
import com.google.api.gax.paging.Page;
30+
import com.google.auth.oauth2.GoogleCredentials;
31+
import com.google.auth.oauth2.UserCredentials;
32+
import com.google.cloud.bigquery.BigQuery;
33+
import com.google.cloud.bigquery.BigQueryException;
34+
import com.google.cloud.bigquery.BigQueryOptions;
35+
import com.google.cloud.bigquery.Dataset;
36+
import com.google.common.collect.ImmutableList;
37+
import java.io.File;
38+
import java.io.IOException;
39+
import java.io.InputStream;
40+
import java.io.InputStreamReader;
41+
import java.nio.file.Files;
42+
import java.nio.file.Path;
43+
import java.nio.file.Paths;
44+
import java.security.GeneralSecurityException;
45+
import java.util.List;
46+
47+
// Sample to authenticate by using a user credential
48+
public class AuthUserFlow {
49+
50+
private static final File DATA_STORE_DIR =
51+
new File(AuthUserFlow.class.getResource("/").getPath(), "credentials");
52+
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
53+
// i.e redirect_uri http://localhost:61984/Callback
54+
private static final int LOCAL_RECEIVER_PORT = 61984;
55+
56+
public static void runAuthUserFlow() {
57+
// TODO(developer): Replace these variables before running the sample.
58+
/**
59+
* Download your OAuth2 configuration from the Google Developers Console API Credentials page.
60+
* https://console.cloud.google.com/apis/credentials
61+
*/
62+
Path credentialsPath = Paths.get("path/to/your/client_secret.json");
63+
List<String> scopes = ImmutableList.of("https://www.googleapis.com/auth/bigquery");
64+
authUserFlow(credentialsPath, scopes);
65+
}
66+
67+
public static void authUserFlow(Path credentialsPath, List<String> selectedScopes) {
68+
// Reading credentials file
69+
try (InputStream inputStream = Files.newInputStream(credentialsPath)) {
70+
71+
// Load client_secret.json file
72+
GoogleClientSecrets clientSecrets =
73+
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(inputStream));
74+
String clientId = clientSecrets.getDetails().getClientId();
75+
String clientSecret = clientSecrets.getDetails().getClientSecret();
76+
77+
// Generate the url that will be used for the consent dialog.
78+
GoogleAuthorizationCodeFlow flow =
79+
new GoogleAuthorizationCodeFlow.Builder(
80+
GoogleNetHttpTransport.newTrustedTransport(),
81+
JSON_FACTORY,
82+
clientSecrets,
83+
selectedScopes)
84+
.setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR))
85+
.setAccessType("offline")
86+
.setApprovalPrompt("auto")
87+
.build();
88+
89+
// Exchange an authorization code for refresh token
90+
LocalServerReceiver receiver =
91+
new LocalServerReceiver.Builder().setPort(LOCAL_RECEIVER_PORT).build();
92+
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
93+
94+
// OAuth2 Credentials representing a user's identity and consent
95+
GoogleCredentials credentials =
96+
UserCredentials.newBuilder()
97+
.setClientId(clientId)
98+
.setClientSecret(clientSecret)
99+
.setRefreshToken(credential.getRefreshToken())
100+
.build();
101+
102+
// Initialize client that will be used to send requests. This client only needs to be created
103+
// once, and can be reused for multiple requests.
104+
BigQuery bigquery =
105+
BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();
106+
107+
Page<Dataset> datasets = bigquery.listDatasets(BigQuery.DatasetListOption.pageSize(100));
108+
if (datasets == null) {
109+
System.out.println("Dataset does not contain any models");
110+
return;
111+
}
112+
datasets
113+
.iterateAll()
114+
.forEach(
115+
dataset -> System.out.printf("Success! Dataset ID: %s ", dataset.getDatasetId()));
116+
117+
} catch (BigQueryException | IOException | GeneralSecurityException ex) {
118+
System.out.println("Project does not contain any datasets \n" + ex.toString());
119+
}
120+
}
121+
}
122+
// [END bigquery_auth_user_flow]
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
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.bigquery;
18+
19+
// [START bigquery_auth_user_query]
20+
import com.google.api.client.auth.oauth2.Credential;
21+
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
22+
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
23+
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
24+
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
25+
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
26+
import com.google.api.client.json.JsonFactory;
27+
import com.google.api.client.json.jackson2.JacksonFactory;
28+
import com.google.api.client.util.store.FileDataStoreFactory;
29+
import com.google.auth.oauth2.GoogleCredentials;
30+
import com.google.auth.oauth2.UserCredentials;
31+
import com.google.cloud.bigquery.BigQuery;
32+
import com.google.cloud.bigquery.BigQueryException;
33+
import com.google.cloud.bigquery.BigQueryOptions;
34+
import com.google.cloud.bigquery.QueryJobConfiguration;
35+
import com.google.cloud.bigquery.TableResult;
36+
import com.google.common.collect.ImmutableList;
37+
import java.io.File;
38+
import java.io.IOException;
39+
import java.io.InputStream;
40+
import java.io.InputStreamReader;
41+
import java.nio.file.Files;
42+
import java.nio.file.Path;
43+
import java.nio.file.Paths;
44+
import java.security.GeneralSecurityException;
45+
import java.util.List;
46+
47+
// Sample to query by using a user credential
48+
public class AuthUserQuery {
49+
50+
private static final File DATA_STORE_DIR =
51+
new File(AuthUserQuery.class.getResource("/").getPath(), "credentials");
52+
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
53+
// i.e redirect_uri http://localhost:61984/Callback
54+
private static final int LOCAL_RECEIVER_PORT = 61984;
55+
56+
public static void runAuthUserQuery() {
57+
// TODO(developer): Replace these variables before running the sample.
58+
/**
59+
* Download your OAuth2 configuration from the Google Developers Console API Credentials page.
60+
* https://console.cloud.google.com/apis/credentials
61+
*/
62+
Path credentialsPath = Paths.get("path/to/your/client_secret.json");
63+
List<String> scopes = ImmutableList.of("https://www.googleapis.com/auth/bigquery");
64+
String query =
65+
"SELECT name, SUM(number) as total"
66+
+ " FROM `bigquery-public-data.usa_names.usa_1910_current`"
67+
+ " WHERE name = 'William'"
68+
+ " GROUP BY name;";
69+
authUserQuery(credentialsPath, scopes, query);
70+
}
71+
72+
public static void authUserQuery(
73+
Path credentialsPath, List<String> selectedScopes, String query) {
74+
// Reading credentials file
75+
try (InputStream inputStream = Files.newInputStream(credentialsPath)) {
76+
77+
// Load client_secret.json file
78+
GoogleClientSecrets clientSecrets =
79+
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(inputStream));
80+
String clientId = clientSecrets.getDetails().getClientId();
81+
String clientSecret = clientSecrets.getDetails().getClientSecret();
82+
83+
// Generate the url that will be used for the consent dialog.
84+
GoogleAuthorizationCodeFlow flow =
85+
new GoogleAuthorizationCodeFlow.Builder(
86+
GoogleNetHttpTransport.newTrustedTransport(),
87+
JSON_FACTORY,
88+
clientSecrets,
89+
selectedScopes)
90+
.setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR))
91+
.setAccessType("offline")
92+
.setApprovalPrompt("auto")
93+
.build();
94+
95+
// Exchange an authorization code for refresh token
96+
LocalServerReceiver receiver =
97+
new LocalServerReceiver.Builder().setPort(LOCAL_RECEIVER_PORT).build();
98+
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
99+
100+
// OAuth2 Credentials representing a user's identity and consent
101+
GoogleCredentials credentials =
102+
UserCredentials.newBuilder()
103+
.setClientId(clientId)
104+
.setClientSecret(clientSecret)
105+
.setRefreshToken(credential.getRefreshToken())
106+
.build();
107+
108+
// Initialize client that will be used to send requests. This client only needs to be created
109+
// once, and can be reused for multiple requests.
110+
BigQuery bigquery =
111+
BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();
112+
113+
QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(query).build();
114+
115+
TableResult results = bigquery.query(queryConfig);
116+
117+
results
118+
.iterateAll()
119+
.forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString())));
120+
121+
System.out.println("Query performed successfully.");
122+
123+
} catch (BigQueryException | IOException | GeneralSecurityException | InterruptedException ex) {
124+
System.out.println("Query not performed \n" + ex.toString());
125+
}
126+
}
127+
}
128+
// [END bigquery_auth_user_query]

0 commit comments

Comments
 (0)