Skip to content

Commit f7f53f0

Browse files
committed
Switch Dynamic Config example code to use Admin SDK
1 parent a837ee7 commit f7f53f0

3 files changed

Lines changed: 90 additions & 158 deletions

File tree

config/build.gradle

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ repositories {
88
mavenCentral()
99
}
1010

11+
run.doFirst { environment 'GOOGLE_APPLICATION_CREDENTIALS', '/Users/chongshao/dev/quickstart-java/config/service-account.json' }
12+
1113
run {
1214
if (project.hasProperty("action")) {
1315
args = args << "${action}"
@@ -25,4 +27,5 @@ dependencies {
2527
testCompile group: 'junit', name: 'junit', version: '4.12'
2628
compile 'com.google.auth:google-auth-library-oauth2-http:0.26.0'
2729
compile 'com.google.code.gson:gson:2.8.7'
30+
implementation 'com.google.firebase:firebase-admin:9.1.1'
2831
}

config/src/main/java/com/google/firebase/samples/config/Configure.java

Lines changed: 84 additions & 157 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
package com.google.firebase.samples.config;
22

33
import com.google.auth.oauth2.GoogleCredentials;
4+
import com.google.firebase.FirebaseApp;
5+
import com.google.firebase.FirebaseOptions;
6+
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
7+
import com.google.firebase.remoteconfig.FirebaseRemoteConfigException;
8+
import com.google.firebase.remoteconfig.ListVersionsOptions;
9+
import com.google.firebase.remoteconfig.ListVersionsPage;
10+
import com.google.firebase.remoteconfig.Template;
11+
import com.google.firebase.remoteconfig.Version;
412
import com.google.gson.Gson;
513
import com.google.gson.GsonBuilder;
614
import com.google.gson.JsonElement;
715
import com.google.gson.JsonObject;
16+
import com.google.gson.JsonArray;
817
import com.google.gson.JsonParser;
9-
1018
import java.io.File;
1119
import java.io.FileInputStream;
1220
import java.io.FileNotFoundException;
@@ -18,55 +26,28 @@
1826
import java.net.HttpURLConnection;
1927
import java.net.URL;
2028
import java.util.Arrays;
29+
import java.util.ArrayList;
30+
import java.util.List;
2131
import java.util.Scanner;
2232
import java.util.zip.GZIPInputStream;
2333
import java.util.zip.GZIPOutputStream;
2434

35+
2536
/**
2637
* Retrieve and publish templates for Firebase Remote Config using the REST API.
2738
*/
2839
public class Configure {
2940

30-
private final static String PROJECT_ID = "PROJECT_ID";
31-
private final static String BASE_URL = "https://firebaseremoteconfig.googleapis.com";
32-
private final static String REMOTE_CONFIG_ENDPOINT = "/v1/projects/" + PROJECT_ID + "/remoteConfig";
33-
private final static String[] SCOPES = { "https://www.googleapis.com/auth/firebase.remoteconfig" };
34-
35-
/**
36-
* Retrieve a valid access token that can be use to authorize requests to the Remote Config REST
37-
* API.
38-
*
39-
* @return Access token.
40-
* @throws IOException
41-
*/
42-
// [START retrieve_access_token]
43-
private static String getAccessToken() throws IOException {
44-
GoogleCredentials googleCredentials = GoogleCredentials
45-
.fromStream(new FileInputStream("service-account.json"))
46-
.createScoped(Arrays.asList(SCOPES));
47-
googleCredentials.refreshAccessToken();
48-
return googleCredentials.getAccessToken().getTokenValue();
49-
}
50-
// [END retrieve_access_token]
51-
5241
/**
53-
* Get current Firebase Remote Config template from server and store it locally.
42+
* Gets current Firebase Remote Config template from server and store it locally.
5443
*
5544
* @throws IOException
5645
*/
5746
private static void getTemplate() throws IOException {
58-
HttpURLConnection httpURLConnection = getCommonConnection(BASE_URL + REMOTE_CONFIG_ENDPOINT);
59-
httpURLConnection.setRequestMethod("GET");
60-
httpURLConnection.setRequestProperty("Accept-Encoding", "gzip");
61-
62-
int code = httpURLConnection.getResponseCode();
63-
if (code == 200) {
64-
InputStream inputStream = new GZIPInputStream(httpURLConnection.getInputStream());
65-
String response = inputstreamToString(inputStream);
66-
47+
try {
48+
Template template = FirebaseRemoteConfig.getInstance().getTemplate();
6749
JsonParser jsonParser = new JsonParser();
68-
JsonElement jsonElement = jsonParser.parse(response);
69-
50+
JsonElement jsonElement = jsonParser.parse(template.toJSON());
7051
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
7152
String jsonStr = gson.toJson(jsonElement);
7253

@@ -75,119 +56,85 @@ private static void getTemplate() throws IOException {
7556
printWriter.print(jsonStr);
7657
printWriter.flush();
7758
printWriter.close();
78-
7959
System.out.println("Template retrieved and has been written to config.json");
8060

8161
// Print ETag
82-
String etag = httpURLConnection.getHeaderField("ETag");
62+
String etag = template.getETag();
8363
System.out.println("ETag from server: " + etag);
84-
} else {
85-
System.out.println(inputstreamToString(httpURLConnection.getErrorStream()));
64+
} catch (FirebaseRemoteConfigException e) {
65+
System.out.println(e.getHttpResponse().getContent());
8666
}
87-
8867
}
89-
68+
9069
/**
91-
* Print the last 5 available Firebase Remote Config template metadata from the server.
92-
*
93-
* @throws IOException
70+
* Prints the last 5 available Firebase Remote Config template metadata from the server.
9471
*/
95-
private static void getVersions() throws IOException {
96-
HttpURLConnection httpURLConnection = getCommonConnection(BASE_URL + REMOTE_CONFIG_ENDPOINT
97-
+ ":listVersions?pageSize=5");
98-
httpURLConnection.setRequestMethod("GET");
99-
100-
int code = httpURLConnection.getResponseCode();
101-
if (code == 200) {
102-
String versions = inputstreamToPrettyString(httpURLConnection.getInputStream());
103-
104-
System.out.println("Versions:");
105-
System.out.println(versions);
106-
} else {
107-
System.out.println(inputstreamToString(httpURLConnection.getErrorStream()));
72+
private static void getVersions() {
73+
ListVersionsOptions listVersionsOptions = ListVersionsOptions.builder().setPageSize(5).build();
74+
try {
75+
ListVersionsPage page = FirebaseRemoteConfig.getInstance().listVersions(listVersionsOptions);
76+
System.out.println("Versions: ");
77+
System.out.println(versionsToJSONString(page));
78+
} catch (FirebaseRemoteConfigException e) {
79+
System.out.println(e.getHttpResponse().getContent());
10880
}
10981
}
11082

11183
/**
112-
* Roll back to an available version of Firebase Remote Config template.
84+
* Rolls back to an available version of Firebase Remote Config template.
11385
*
11486
* @param version The version to roll back to.
115-
*
116-
* @throws IOException
11787
*/
118-
private static void rollback(int version) throws IOException {
119-
HttpURLConnection httpURLConnection = getCommonConnection(BASE_URL + REMOTE_CONFIG_ENDPOINT
120-
+ ":rollback");
121-
httpURLConnection.setDoOutput(true);
122-
httpURLConnection.setRequestMethod("POST");
123-
httpURLConnection.setRequestProperty("Accept-Encoding", "gzip");
124-
125-
JsonObject jsonObject = new JsonObject();
126-
jsonObject.addProperty("version_number", version);
127-
128-
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
129-
outputStreamWriter.write(jsonObject.toString());
130-
outputStreamWriter.flush();
131-
outputStreamWriter.close();
132-
133-
int code = httpURLConnection.getResponseCode();
134-
if (code == 200) {
88+
private static void rollback(int version) {
89+
try {
90+
Template template = FirebaseRemoteConfig.getInstance().rollback(version);
13591
System.out.println("Rolled back to: " + version);
136-
InputStream inputStream = new GZIPInputStream(httpURLConnection.getInputStream());
137-
System.out.println(inputstreamToPrettyString(inputStream));
138-
139-
// Print ETag
140-
String etag = httpURLConnection.getHeaderField("ETag");
141-
System.out.println("ETag from server: " + etag);
142-
} else {
92+
System.out.println(template.toJSON());
93+
System.out.println("ETag from server: " + template.getETag());
94+
} catch (FirebaseRemoteConfigException e) {
14395
System.out.println("Error:");
144-
InputStream inputStream = new GZIPInputStream(httpURLConnection.getErrorStream());
145-
System.out.println(inputstreamToString(inputStream));
146-
}
96+
System.out.println(e.getHttpResponse().getContent());
97+
}
14798
}
14899

149100
/**
150-
* Publish local template to Firebase server.
101+
* Publishes local template to Firebase server.
151102
*
152103
* @throws IOException
153104
*/
154105
private static void publishTemplate(String etag) throws IOException {
155-
if (etag.equals("*")) {
106+
if (etag.equals("*")) {
156107
Scanner scanner = new Scanner(System.in);
157108
System.out.println("Are you sure you would like to force replace the template? Yes (y), No (n)");
158109
String answer = scanner.nextLine();
159110
if (!answer.equalsIgnoreCase("y")) {
160111
System.out.println("Publish canceled.");
161112
return;
162113
}
163-
}
164-
114+
}
115+
165116
System.out.println("Publishing template...");
166-
HttpURLConnection httpURLConnection = getCommonConnection(BASE_URL + REMOTE_CONFIG_ENDPOINT);
167-
httpURLConnection.setDoOutput(true);
168-
httpURLConnection.setRequestMethod("PUT");
169-
httpURLConnection.setRequestProperty("If-Match", etag);
170-
httpURLConnection.setRequestProperty("Content-Encoding", "gzip");
171-
172-
String configStr = readConfig();
173-
174-
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(httpURLConnection.getOutputStream());
175-
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gzipOutputStream);
176-
outputStreamWriter.write(configStr);
177-
outputStreamWriter.flush();
178-
outputStreamWriter.close();
179-
180-
int code = httpURLConnection.getResponseCode();
181-
if (code == 200) {
117+
118+
String templateStr = readConfig();
119+
try {
120+
Template template = Template.fromJSON(templateStr);
121+
if (etag.equals("*")) {
122+
Template publishedTemplate = FirebaseRemoteConfig.getInstance()
123+
.forcePublishTemplate(template);
124+
} else {
125+
Template publishedTemplate = FirebaseRemoteConfig.getInstance()
126+
.publishTemplate(template);
127+
}
182128
System.out.println("Template has been published.");
183-
} else {
184-
System.out.println(inputstreamToString(httpURLConnection.getErrorStream()));
185129
}
186-
130+
catch (FirebaseRemoteConfigException e) {
131+
System.out.println("Error:");
132+
System.out.println(e.getHttpResponse().getContent());
133+
}
187134
}
188135

189136
/**
190-
* Read the Firebase Remote Config template from config.json file.
137+
* Reads the Firebase Remote Config template from config.json file.
191138
*
192139
* @return String with contents of config.json file.
193140
* @throws FileNotFoundException
@@ -202,58 +149,38 @@ private static String readConfig() throws FileNotFoundException {
202149
}
203150
return stringBuilder.toString();
204151
}
205-
206-
/**
207-
* Format content from an InputStream as pretty JSON.
208-
*
209-
* @param inputStream Content to be formatted.
210-
* @return Pretty JSON formatted string.
211-
*
212-
* @throws IOException
213-
*/
214-
private static String inputstreamToPrettyString(InputStream inputStream) throws IOException {
215-
String response = inputstreamToString(inputStream);
216-
217-
JsonParser jsonParser = new JsonParser();
218-
JsonElement jsonElement = jsonParser.parse(response);
219-
220-
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
221-
String jsonStr = gson.toJson(jsonElement);
222-
223-
return jsonStr;
224-
}
225-
152+
226153
/**
227-
* Read contents of InputStream into String.
154+
* Converts the list of versions into a formatted JSON string.
228155
*
229-
* @param inputStream InputStream to read.
230-
* @return String containing contents of InputStream.
231-
* @throws IOException
232-
*/
233-
private static String inputstreamToString(InputStream inputStream) throws IOException {
234-
StringBuilder stringBuilder = new StringBuilder();
235-
Scanner scanner = new Scanner(inputStream);
236-
while (scanner.hasNext()) {
237-
stringBuilder.append(scanner.nextLine());
238-
}
239-
return stringBuilder.toString();
156+
* @return String representing the list of versions.
157+
*/
158+
private static String versionsToJSONString(ListVersionsPage page) {
159+
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
160+
JsonParser jsonParser = new JsonParser();
161+
162+
JsonArray versionsJsonArray = new JsonArray();
163+
for (Version version : page.iterateAll()) {
164+
versionsJsonArray.add(jsonParser.parse(gson.toJson(version)));
165+
}
166+
167+
JsonObject jsonObject = new JsonObject();
168+
jsonObject.add("versions", versionsJsonArray);
169+
return gson.toJson(jsonParser.parse(jsonObject.toString()));
240170
}
241-
242-
/**
243-
* Create HttpURLConnection that can be used for both retrieving and publishing.
244-
*
245-
* @return Base HttpURLConnection.
246-
* @throws IOException
247-
*/
248-
private static HttpURLConnection getCommonConnection(String endpoint) throws IOException {
249-
URL url = new URL(endpoint);
250-
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
251-
httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken());
252-
httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
253-
return httpURLConnection;
171+
172+
public static void initializeWithDefaultCredentials() throws IOException {
173+
// [START initialize_sdk_with_application_default]
174+
FirebaseOptions options = new FirebaseOptions.Builder()
175+
.setCredentials(GoogleCredentials.getApplicationDefault())
176+
.build();
177+
178+
FirebaseApp.initializeApp(options);
179+
// [END initialize_sdk_with_application_default]
254180
}
255181

256182
public static void main(String[] args) throws IOException {
183+
initializeWithDefaultCredentials();
257184
if (args.length > 1 && args[0].equals("publish")) {
258185
publishTemplate(args[1]);
259186
} else if (args.length == 1 && args[0].equals("get")) {

messaging/src/main/java/com/google/firebase/quickstart/Messaging.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,8 @@ public class Messaging {
5555
// [START retrieve_access_token]
5656
private static String getAccessToken() throws IOException {
5757
GoogleCredentials googleCredentials = GoogleCredentials
58-
.fromStream(new FileInputStream("service-account.json"))
58+
.fromStream(new FileInputStream("android-gcm-test-519bd-4b2b39c38ceb.json"))
59+
// .fromStream(new FileInputStream("service-account.json"))
5960
.createScoped(Arrays.asList(SCOPES));
6061
googleCredentials.refresh();
6162
return googleCredentials.getAccessToken().getTokenValue();
@@ -197,6 +198,7 @@ public static void initializeWithDefaultCredentials() throws IOException {
197198
}
198199

199200
public static void main(String[] args) throws IOException, FirebaseMessagingException {
201+
System.out.println(getAccessToken());
200202
initializeWithDefaultCredentials();
201203
if (args.length == 1 && args[0].equals("common-message")) {
202204
sendCommonMessage();

0 commit comments

Comments
 (0)