|
| 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