Repository navigation
Expand file tree
/
Copy pathFirebaseDatabase.java
More file actions
427 lines (385 loc) · 14.7 KB
/
Copy pathFirebaseDatabase.java
File metadata and controls
427 lines (385 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/*
* Copyright 2017 Google Inc.
*
* 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.google.firebase.database;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.ImplFirebaseTrampolines;
import com.google.firebase.database.core.DatabaseConfig;
import com.google.firebase.database.core.Path;
import com.google.firebase.database.core.Repo;
import com.google.firebase.database.core.RepoInfo;
import com.google.firebase.database.core.RepoManager;
import com.google.firebase.database.util.EmulatorHelper;
import com.google.firebase.database.utilities.ParsedUrl;
import com.google.firebase.database.utilities.Utilities;
import com.google.firebase.database.utilities.Validation;
import com.google.firebase.internal.FirebaseService;
import com.google.firebase.internal.SdkUtils;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The entry point for accessing a Firebase Database. You can get an instance by calling {@link
* FirebaseDatabase#getInstance()}. To access a location in the database and read or write data, use
* {@link FirebaseDatabase#getReference()}.
*/
public class FirebaseDatabase {
private final FirebaseApp app;
private final RepoInfo repoInfo;
private final DatabaseConfig config;
private Repo repo; // Usage must be guarded by a call to ensureRepo().
private final AtomicBoolean destroyed = new AtomicBoolean(false);
// Lock for synchronizing internal state changes. Protects accesses to repo and destroyed
// members.
private final Object lock = new Object();
private FirebaseDatabase(FirebaseApp app, RepoInfo repoInfo, DatabaseConfig config) {
this.app = app;
this.repoInfo = repoInfo;
this.config = config;
}
/**
* Gets the default FirebaseDatabase instance.
*
* @return A FirebaseDatabase instance.
*/
public static FirebaseDatabase getInstance() {
FirebaseApp instance = FirebaseApp.getInstance();
if (instance == null) {
throw new DatabaseException("You must call FirebaseApp.initialize() first.");
}
return getInstance(instance, instance.getOptions().getDatabaseUrl());
}
/**
* Gets a FirebaseDatabase instance for the specified URL.
*
* @param url The URL to the Firebase Database instance you want to access.
* @return A FirebaseDatabase instance.
*/
public static FirebaseDatabase getInstance(String url) {
FirebaseApp instance = FirebaseApp.getInstance();
if (instance == null) {
throw new DatabaseException("You must call FirebaseApp.initialize() first.");
}
return getInstance(instance, url);
}
/**
* Gets an instance of FirebaseDatabase for a specific FirebaseApp.
*
* @param app The FirebaseApp to get a FirebaseDatabase for.
* @return A FirebaseDatabase instance.
*/
public static FirebaseDatabase getInstance(FirebaseApp app) {
return getInstance(app, app.getOptions().getDatabaseUrl());
}
/**
* Gets a FirebaseDatabase instance for the specified URL, using the specified FirebaseApp.
*
* @param app The FirebaseApp to get a FirebaseDatabase for.
* @param url The URL to the Firebase Database instance you want to access.
* @return A FirebaseDatabase instance.
*/
public static synchronized FirebaseDatabase getInstance(FirebaseApp app, String url) {
FirebaseDatabaseService service = ImplFirebaseTrampolines.getService(app, SERVICE_ID,
FirebaseDatabaseService.class);
if (service == null) {
service = ImplFirebaseTrampolines.addService(app, new FirebaseDatabaseService());
}
if (url == null || url.isEmpty()) {
throw new DatabaseException(
"Failed to get FirebaseDatabase instance: Specify DatabaseURL within "
+ "FirebaseApp or from your getInstance() call.");
}
ParsedUrl parsedUrl;
boolean connectingToEmulator = false;
String possibleEmulatorUrl = EmulatorHelper
.getEmulatorUrl(url, EmulatorHelper.getEmulatorHostFromEnv());
if (!Strings.isNullOrEmpty(possibleEmulatorUrl)) {
parsedUrl = Utilities.parseUrl(possibleEmulatorUrl);
connectingToEmulator = true;
} else {
parsedUrl = Utilities.parseUrl(url);
}
if (!parsedUrl.path.isEmpty()) {
throw new DatabaseException(
"Specified Database URL '"
+ url
+ "' is invalid. It should point to the root of a "
+ "Firebase Database but it includes a path: "
+ parsedUrl.path.toString());
}
DatabaseInstances dbInstances = service.getInstance();
FirebaseDatabase database = dbInstances.get(parsedUrl.repoInfo);
if (database == null) {
DatabaseConfig config = new DatabaseConfig();
// If this is the default app, don't set the session persistence key so that we use our
// default ("default") instead of the FirebaseApp default ("[DEFAULT]") so that we
// preserve the default location used by the legacy Firebase SDK.
if (!ImplFirebaseTrampolines.isDefaultApp(app)) {
config.setSessionPersistenceKey(app.getName());
}
config.setFirebaseApp(app);
if (connectingToEmulator) {
config.setCustomCredentials(new EmulatorCredentials(), true);
}
database = new FirebaseDatabase(app, parsedUrl.repoInfo, config);
dbInstances.put(parsedUrl.repoInfo, database);
}
return database;
}
/** This exists so Repo can create FirebaseDatabase objects to keep legacy tests working. */
static FirebaseDatabase createForTests(
FirebaseApp app, RepoInfo repoInfo, DatabaseConfig config) {
FirebaseDatabase db = new FirebaseDatabase(app, repoInfo, config);
db.ensureRepo();
return db;
}
/**
* @return The version for this build of the Firebase Database client
*/
public static String getSdkVersion() {
return SdkUtils.getVersion();
}
/**
* Returns the FirebaseApp instance to which this FirebaseDatabase belongs.
*
* @return The FirebaseApp instance to which this FirebaseDatabase belongs.
*/
public FirebaseApp getApp() {
return this.app;
}
/**
* Gets a DatabaseReference for the database root node.
*
* @return A DatabaseReference pointing to the root node.
*/
public DatabaseReference getReference() {
return new DatabaseReference(ensureRepo(), Path.getEmptyPath());
}
/**
* Gets a DatabaseReference for the provided path.
*
* @param path Path to a location in your FirebaseDatabase.
* @return A DatabaseReference pointing to the specified path.
*/
public DatabaseReference getReference(String path) {
checkNotNull(path,
"Can't pass null for argument 'pathString' in FirebaseDatabase.getReference()");
Validation.validateRootPathString(path);
Path childPath = new Path(path);
return new DatabaseReference(ensureRepo(), childPath);
}
/**
* Gets a DatabaseReference for the provided URL. The URL must be a URL to a path within this
* FirebaseDatabase. To create a DatabaseReference to a different database, create a {@link
* FirebaseApp} with a {@link FirebaseOptions} object configured with the appropriate database
* URL.
*
* @param url A URL to a path within your database.
* @return A DatabaseReference for the provided URL.
*/
public DatabaseReference getReferenceFromUrl(String url) {
checkNotNull(url,
"Can't pass null for argument 'url' in FirebaseDatabase.getReferenceFromUrl()");
String possibleEmulatorUrl = EmulatorHelper
.getEmulatorUrl(url, EmulatorHelper.getEmulatorHostFromEnv());
if (!Strings.isNullOrEmpty(possibleEmulatorUrl)) {
url = possibleEmulatorUrl;
}
ParsedUrl parsedUrl = Utilities.parseUrl(url);
Repo repo = ensureRepo();
if (!parsedUrl.repoInfo.host.equals(repo.getRepoInfo().host)) {
throw new DatabaseException(
"Invalid URL ("
+ url
+ ") passed to getReference(). "
+ "URL was expected to match configured Database URL: "
+ getReference().toString());
}
return new DatabaseReference(repo, parsedUrl.path);
}
/**
* The Firebase Database client automatically queues writes and sends them to the server at the
* earliest opportunity, depending on network connectivity. In some cases (e.g. offline usage)
* there may be a large number of writes waiting to be sent. Calling this method will purge all
* outstanding writes so they are abandoned.
*
* <p>All writes will be purged, including transactions and {@link DatabaseReference#onDisconnect}
* writes. The writes will be rolled back locally, perhaps triggering events for affected event
* listeners, and the client will not (re-)send them to the Firebase backend.
*/
public void purgeOutstandingWrites() {
final Repo repo = ensureRepo();
repo.scheduleNow(
new Runnable() {
@Override
public void run() {
repo.purgeOutstandingWrites();
}
});
}
/**
* Resumes our connection to the Firebase Database backend after a previous {@link #goOffline()}
* call.
*/
public void goOnline() {
RepoManager.resume(ensureRepo());
}
/**
* Shuts down our connection to the Firebase Database backend until {@link #goOnline()} is called.
*/
public void goOffline() {
RepoManager.interrupt(ensureRepo());
}
/**
* The Firebase Database client will cache synchronized data and keep track of all writes you've
* initiated while your application is running. It seamlessly handles intermittent network
* connections and re-sends write operations when the network connection is restored.
*
* <p>However by default your write operations and cached data are only stored in-memory and will
* be lost when your app restarts. By setting this value to {@code true}, the data will be
* persisted to on-device (disk) storage and will thus be available again when the app is
* restarted (even when there is no network connectivity at that time). Note that this method
* must be called before creating your first Database reference and only needs to be called once
* per application.
*
* @param isEnabled Set to true to enable disk persistence, set to false to disable it.
*/
public synchronized void setPersistenceEnabled(boolean isEnabled) {
synchronized (lock) {
assertUnfrozen("setPersistenceEnabled");
this.config.setPersistenceEnabled(isEnabled);
}
}
/**
* By default Firebase Database will use up to 10MB of disk space to cache data. If the cache
* grows beyond this size, Firebase Database will start removing data that hasn't been recently
* used. If you find that your application caches too little or too much data, call this method to
* change the cache size. This method must be called before creating your first Database reference
* and only needs to be called once per application.
*
* <p>Note that the specified cache size is only an approximation and the size on disk may
* temporarily exceed it at times. Cache sizes smaller than 1 MB or greater than 100 MB are not
* supported.
*
* @param cacheSizeInBytes The new size of the cache in bytes.
*/
public void setPersistenceCacheSizeBytes(long cacheSizeInBytes) {
synchronized (lock) {
assertUnfrozen("setPersistenceCacheSizeBytes");
this.config.setPersistenceCacheSizeBytes(cacheSizeInBytes);
}
}
private void assertUnfrozen(String methodCalled) {
synchronized (lock) {
checkNotDestroyed();
if (this.repo != null) {
throw new DatabaseException(
"Calls to "
+ methodCalled
+ "() must be made before any "
+ "other usage of FirebaseDatabase instance.");
}
}
}
/**
* Initializes the Repo if not already initialized.
*/
private Repo ensureRepo() {
synchronized (lock) {
checkNotDestroyed();
if (repo == null) {
repo = RepoManager.createRepo(this.config, this.repoInfo, this);
}
return repo;
}
}
void checkNotDestroyed() {
synchronized (lock) {
checkState(!destroyed.get(),
"FirebaseDatabase instance is no longer alive. This happens when "
+ "the parent FirebaseApp instance has been deleted.");
}
}
// for testing
DatabaseConfig getConfig() {
return this.config;
}
void destroy() {
synchronized (lock) {
if (destroyed.get()) {
return;
}
RepoManager.destroy(getConfig());
destroyed.compareAndSet(false, true);
}
}
private static final String SERVICE_ID = FirebaseDatabase.class.getName();
private static class DatabaseInstances {
private final Map<RepoInfo, FirebaseDatabase> databases =
Collections.synchronizedMap(new HashMap<RepoInfo, FirebaseDatabase>());
void put(RepoInfo repo, FirebaseDatabase database) {
databases.put(repo, database);
}
FirebaseDatabase get(RepoInfo repo) {
return databases.get(repo);
}
void destroy() {
synchronized (databases) {
for (FirebaseDatabase database : databases.values()) {
database.destroy();
}
databases.clear();
}
}
}
private static class FirebaseDatabaseService extends FirebaseService<DatabaseInstances> {
FirebaseDatabaseService() {
super(SERVICE_ID, new DatabaseInstances());
}
@Override
public void destroy() {
instance.destroy();
}
}
private static class EmulatorCredentials extends GoogleCredentials {
EmulatorCredentials() {
super(newToken());
}
private static AccessToken newToken() {
return new AccessToken("owner",
new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)));
}
@Override
public AccessToken refreshAccessToken() {
return newToken();
}
@Override
public Map<String, List<String>> getRequestMetadata() throws IOException {
return ImmutableMap.of();
}
}
}