diff --git a/bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryServiceFactory.java b/bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryServiceFactory.java index 4a657935012..9e9901953c8 100644 --- a/bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryServiceFactory.java +++ b/bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryServiceFactory.java @@ -16,6 +16,7 @@ package com.google.cloud.bigquery.samples; +// [START imports] import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; @@ -23,6 +24,7 @@ import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.BigqueryScopes; +// [END imports] import java.io.IOException; import java.util.Collection; @@ -67,21 +69,26 @@ public static Bigquery getService() throws IOException { /** * Creates an authorized client to Google Bigquery. + * * @return The BigQuery Service * @throws IOException Thrown if there is an error connecting */ // [START get_service] private static Bigquery createAuthorizedClient() throws IOException { - Collection bigqueryScopes = BigqueryScopes.all(); + // Create the credential HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); - GoogleCredential credential = GoogleCredential.getApplicationDefault( - transport, jsonFactory); + GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); + + // Some credential types require you to specify scopes, and service entry points may not inject + // them. Check for this case, and inject the scopes explicitly if required. if (credential.createScopedRequired()) { + Collection bigqueryScopes = BigqueryScopes.all(); credential = credential.createScoped(bigqueryScopes); } + return new Bigquery.Builder(transport, jsonFactory, credential) - .setApplicationName("BigQuery Samples").build(); + .setApplicationName("BigQuery Samples").build(); } // [END get_service]