Uni*_*ter 7 java java-ee firebase-realtime-database
我遇到了与Firebase和Java EE相关的问题.
我正在为我的项目编写一些Java servlet,我第一次使用Firebase因为我想尝试新的东西.
我的实际问题如下:我有一个servlet负责在用户数据库中交换iOS设备令牌.这对于将远程推送通知发送到设备是必需的.我在google教程中完成了这个,但我得到以下异常:
java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
Run Code Online (Sandbox Code Playgroud)
我访问Firebase数据库的方式是通过Java SDK.
我使用以下代码执行此操作:
连接方法
// gets called by the servlet to configure Firebase
public static void connect() {
try {
// for authentication purpose
Map<String, Object> auth = new HashMap<>();
auth.put("uid", "my-service-account");
// Setting up the FirebaseOptions object
// constant FIREBASE_DATABASE_URL = "url to my database"
// constant FIREBASE_KEY_PATH = "path to my json key"
options = new FirebaseOptions.Builder()
.setDatabaseUrl(FIREBASE_DATABASE_URL)
.setServiceAccount(new FileInputStream(FIREBASE_KEY_PATH))
.setDatabaseAuthVariableOverride(auth)
.build();
FirebaseApp.initializeApp(options);
// calling the method for exchanging the token
exchangeIosDeviceToken("testmail@example.com", "5bf53173c9ef0a37638f3ddaa59cf2c0687c14ca0dcd47ccf57f9f09bd6368ab");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
exchangeIosDeviceToken方法
public static boolean exchangeIosDeviceToken(String email, String newDeviceToken) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
// getting a reference to my "employee" child
DatabaseReference employeeReference = database.getReference("/employee");
Map<String, Object> employeeUpdates = new HashMap<>();
// updating the device token with child "iosDeviceToken" of "employee"
employeeUpdates.put(email+"/iosDeviceToken", newDeviceToken);
// update the actual children
employeeReference.updateChildren(employeeUpdates);
return true;
}
Run Code Online (Sandbox Code Playgroud)
有趣的是,当我尝试在独立的主类中执行此代码时(使用main方法替换connect方法),代码正在运行.
在您说"有很多与此主题相关的问题"之前......他们几乎都与Android有关,与我的问题相关的问题很少得到解答.
问候
小智 8
这对于未来的用户,您可以检查默认应用程序是否像这样初始化。
FirebaseApp firebaseApp = null;
List<FirebaseApp> firebaseApps = FirebaseApp.getApps();
if(firebaseApps!=null && !firebaseApps.isEmpty()){
for(FirebaseApp app : firebaseApps){
if(app.getName().equals(FirebaseApp.DEFAULT_APP_NAME))
firebaseApp = app;
}
}
else
firebaseApp = FirebaseApp.initializeApp(options);
Run Code Online (Sandbox Code Playgroud)