diff --git a/README.md b/README.md index 6708ba3d358d..6bd1e7211f2c 100644 --- a/README.md +++ b/README.md @@ -84,8 +84,9 @@ Most `gcloud-java` libraries require a project ID. There are multiple ways to s 1. Project ID supplied when building the service options 2. Project ID specified by the environment variable `GCLOUD_PROJECT` 3. App Engine project ID -4. Google Cloud SDK project ID -5. Compute Engine project ID +4. Project ID specified in the JSON credentials file pointed by the `GOOGLE_APPLICATION_CREDENTIALS` environment variable +5. Google Cloud SDK project ID +6. Compute Engine project ID Authentication -------------- diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java b/gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java index 1c5289bbcda9..d53cfcdafe24 100644 --- a/gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java +++ b/gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java @@ -30,8 +30,13 @@ import com.google.common.io.Files; import com.google.gcloud.spi.ServiceRpcFactory; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; + import java.io.BufferedReader; import java.io.File; +import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; @@ -378,7 +383,10 @@ protected String defaultHost() { protected String defaultProject() { String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME)); if (projectId == null) { - projectId = getAppEngineProjectId(); + projectId = appEngineProjectId(); + } + if (projectId == null) { + projectId = serviceAccountProjectId(); } return projectId != null ? projectId : googleCloudProjectId(); } @@ -461,7 +469,7 @@ private static boolean isWindows() { return System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows"); } - protected static String getAppEngineProjectId() { + protected static String appEngineProjectId() { try { Class factoryClass = Class.forName("com.google.appengine.api.appidentity.AppIdentityServiceFactory"); @@ -479,6 +487,20 @@ protected static String getAppEngineProjectId() { } } + protected static String serviceAccountProjectId() { + String project = null; + String credentialsPath = System.getenv("GOOGLE_APPLICATION_CREDENTIALS"); + if(credentialsPath != null) { + try (InputStream credentialsStream = new FileInputStream(credentialsPath)) { + JSONObject json = new JSONObject(new JSONTokener(credentialsStream)); + project = json.getString("project_id"); + } catch (IOException | JSONException ex) { + // ignore + } + } + return project; + } + @SuppressWarnings("unchecked") public ServiceT service() { if (service == null) {