|
16 | 16 |
|
17 | 17 | package com.google.cloud.bigquery.samples;
|
18 | 18 |
|
| 19 | +// [START imports] |
19 | 20 | import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
|
20 | 21 | import com.google.api.client.http.HttpTransport;
|
21 | 22 | import com.google.api.client.http.javanet.NetHttpTransport;
|
22 | 23 | import com.google.api.client.json.JsonFactory;
|
23 | 24 | import com.google.api.client.json.jackson2.JacksonFactory;
|
24 | 25 | import com.google.api.services.bigquery.Bigquery;
|
25 | 26 | import com.google.api.services.bigquery.BigqueryScopes;
|
| 27 | +// [END imports] |
26 | 28 |
|
27 | 29 | import java.io.IOException;
|
28 | 30 | import java.util.Collection;
|
@@ -67,21 +69,27 @@ public static Bigquery getService() throws IOException {
|
67 | 69 |
|
68 | 70 | /**
|
69 | 71 | * Creates an authorized client to Google Bigquery.
|
| 72 | + * |
70 | 73 | * @return The BigQuery Service
|
71 | 74 | * @throws IOException Thrown if there is an error connecting
|
72 | 75 | */
|
73 | 76 | // [START get_service]
|
74 | 77 | private static Bigquery createAuthorizedClient() throws IOException {
|
75 |
| - Collection<String> bigqueryScopes = BigqueryScopes.all(); |
| 78 | + // Create the credential |
76 | 79 | HttpTransport transport = new NetHttpTransport();
|
77 | 80 | JsonFactory jsonFactory = new JacksonFactory();
|
78 |
| - GoogleCredential credential = GoogleCredential.getApplicationDefault( |
79 |
| - transport, jsonFactory); |
| 81 | + GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); |
| 82 | + |
| 83 | + // Depending on the environment that provides the default credentials (eg Compute Engine, App |
| 84 | + // Engine), the credentials may require us to specify the scopes we need explicitly. |
| 85 | + // Check for this case, and inject the Bigquery scope if required. |
80 | 86 | if (credential.createScopedRequired()) {
|
| 87 | + Collection<String> bigqueryScopes = BigqueryScopes.all(); |
81 | 88 | credential = credential.createScoped(bigqueryScopes);
|
82 | 89 | }
|
| 90 | + |
83 | 91 | return new Bigquery.Builder(transport, jsonFactory, credential)
|
84 |
| - .setApplicationName("BigQuery Samples").build(); |
| 92 | + .setApplicationName("BigQuery Samples").build(); |
85 | 93 | }
|
86 | 94 | // [END get_service]
|
87 | 95 |
|
|
0 commit comments