I am using firebase admin sdk for java. When I created a java console application, this code below works as expected. But if I put the same code, in the initialization of a bean in a springboot application, it never goes inside the onDataChange EventHandler.
I even tried putting a Thread.sleep() with a sufficient delay at the end, to check if this was happening because the thread initializing the bean was exiting. However that did not help.
What is the right way to do this inside a spring bean?
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Repository;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
@Repository
@EnableAsync
public class MyBean {
FirebaseDatabase db;
public MyBean() {
try {
File file = new File(
getClass().getClassLoader().getResource("myKey.json").getFile()
);
FileInputStream fis = new FileInputStream(file);
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(fis))
.setDatabaseUrl("https://myUrl/")
.build();
FirebaseApp.initializeApp(options);
db = FirebaseDatabase.getInstance();
DatabaseReference ref = db
.getReference("/a/b/c");
ref.addValueEventListener(new ValueEventListener() {
//The code execution never comes in here
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("dataSnapshot.exists() :"+ dataSnapshot.exists());
}
public void onCancelled(DatabaseError error) {
System.out.print("Error: " + error.getMessage());
}
});
// Thread.sleep(10000);
} catch (Exception ex) {
String err=ex.getMessage();
}
}
`