/*-
 * -\-\-
 * Flo BigQuery
 * --
 * Copyright (C) 2016 - 2018 Spotify AB
 * --
 * 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.spotify.flo.contrib.bigquery;

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;

public class BigQueryClientSingleton {

  public static final BigQuery BIGQUERY_INTERNAL;
  public static final FloBigQueryClient BIGQUERY_CLIENT;

  static {
    BIGQUERY_INTERNAL = BigQueryOptions.getDefaultInstance().getService();
    BIGQUERY_CLIENT = new DefaultBigQueryClient(BIGQUERY_INTERNAL);
  }

}

@@ -689,16 +689,86 @@
 query;%0A%0A
+import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;%0A
 import c
@@ -856,16 +856,37 @@
 ns;%0A
-%0Apublic 
+import java.io.IOException;%0A%0A
 clas
@@ -913,29 +913,30 @@
 leton %7B%0A%0A  p
-ublic
+rivate
  static fina
@@ -971,15 +971,8 @@
 ;%0A  
-public 
 stat
@@ -1035,150 +1035,888 @@
     
-BIGQUERY_INTERNAL = BigQueryOptions.getDefaultInstance().getService();%0A    BIGQUERY_CLIENT = new DefaultBigQueryClient(BIGQUERY_INTERNAL);%0A  %7D%0A
+final BigQueryOptions.Builder bigquery = BigQueryOptions.newBuilder();%0A    // Work around a bug in ServiceOptions.getDefaultProjectId() where it will use the project%0A    // returned by the GCE metadata server instead of the service account project%0A    // https://github.com/GoogleCloudPlatform/google-cloud-java/pull/2304/files#diff-966eb51fcb59c92eb46ebd5f532d8e52R404%0A    final String serviceAccountProjectId = getServiceAccountProjectId();%0A    if (serviceAccountProjectId != null) %7B%0A      bigquery.setProjectId(serviceAccountProjectId);%0A    %7D%0A    BIGQUERY_INTERNAL = bigquery.build().getService();%0A    BIGQUERY_CLIENT = new DefaultBigQueryClient(BIGQUERY_INTERNAL);%0A  %7D%0A%0A  private static String getServiceAccountProjectId() %7B%0A    try %7B%0A      return GoogleCredential.getApplicationDefault().getServiceAccountProjectId();%0A    %7D catch (IOException e) %7B%0A      return null;%0A    %7D%0A  %7D
 %0A%7D%0A

use SA project id as default