diff --git a/config/README.md b/config/README.md index 070dcc8..111fc6e 100644 --- a/config/README.md +++ b/config/README.md @@ -15,7 +15,7 @@ Getting started 1. [Add Firebase to your Android Project](https://firebase.google.com/docs/android/setup). 2. Create a service account as described in [Adding Firebase to your Server](https://firebase.google.com/docs/admin/setup) and download the JSON file. - - Copy the private key JSON file to this folder and rename it to `service-account.json`. + - Set `GOOGLE_APPLICATION_CREDENTIALS` environment variable to path of downloaded credential file. 3. Change the `PROJECT_ID` variable in `Configure.java` to your project ID. Run diff --git a/config/src/main/java/com/google/firebase/samples/config/Configure.java b/config/src/main/java/com/google/firebase/samples/config/Configure.java index fe79e15..851bbca 100644 --- a/config/src/main/java/com/google/firebase/samples/config/Configure.java +++ b/config/src/main/java/com/google/firebase/samples/config/Configure.java @@ -35,17 +35,23 @@ public class Configure { /** * Retrieve a valid access token that can be use to authorize requests to the Remote Config REST - * API. + * API. If there is no existing access token or if the existing one will expire in less than + * five minutes a fresh token is fetched. + * + * This method must be called in either a trusted Google environment like GCP or if running + * elsewhere the GOOGLE_APPLICATION_CREDENTIALS environment variable must be set to the path + * of the service account credentials file. * * @return Access token. * @throws IOException */ // [START retrieve_access_token] private static String getAccessToken() throws IOException { - GoogleCredential googleCredential = GoogleCredential - .fromStream(new FileInputStream("service-account.json")) + GoogleCredential googleCredential = GoogleCredential.getApplicationDefault() .createScoped(Arrays.asList(SCOPES)); - googleCredential.refreshToken(); + if (googleCredential.getAccessToken() == null || googleCredential.getExpiresInSeconds() < 300) { + googleCredential.refreshToken(); + } return googleCredential.getAccessToken(); } // [END retrieve_access_token] @@ -83,7 +89,9 @@ private static void getTemplate() throws IOException { String etag = httpURLConnection.getHeaderField("ETag"); System.out.println("ETag from server: " + etag); } else { - System.out.println(inputstreamToString(httpURLConnection.getErrorStream())); + System.out.println("Error:"); + InputStream inputStream = new GZIPInputStream(httpURLConnection.getErrorStream()); + System.out.println(inputstreamToString(inputStream)); } }