我正在使用firebase java sdk作为服务器后端代码。我正在使用保存异步调用并等待它,但是数据库中添加的单值事件侦听器无法正常工作。我什至尝试了googleCompleteableFutureApi以等待异步调用完成,但仍未执行回调。 参见下面的代码:-
package com.stocknap;
import com.google.api.client.util.DateTime;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.FirebaseOptions.Builder;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.*;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
//import com.google.firebase.tasks.TaskCompletionSource;
public enum Firebase {
INSTANCE;
FirebaseApp firebaseApp;
public void initilizeFirebaseApp(ConfigLoader configReader) {
CountDownLatch done = new CountDownLatch(1);
final AtomicInteger message1 = new AtomicInteger(0);
InputStream firebaseSecret = getClass().getClassLoader().getResourceAsStream("ServiceAccount.json");
final GoogleCredentials credentials;
try {
credentials = GoogleCredentials.fromStream(firebaseSecret);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error while reading Firebase config file." + e.toString());
throw new IllegalStateException(e);
}
Map<String, Object> auth = new HashMap<>();
auth.put("uid", "my_resources");
FirebaseOptions options = new Builder()
.setConnectTimeout(1000)
.setCredentials(credentials)
.setDatabaseAuthVariableOverride(auth)
.setDatabaseUrl(configReader.getFirebaseDatabaseURL())
.setStorageBucket(configReader.getFirebaseStorageBucket())
.setProjectId(configReader.getFirebseProjectId())
.build();
firebaseApp = FirebaseApp.initializeApp(options);
System.out.println(firebaseApp.getName());
//System.out.println(firebaseApp.getName());
// Use the shorthand notation to retrieve the default app's service
FirebaseAuth defaultAuth = FirebaseAuth.getInstance();
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance();
// The app only has access as defined in the Security Rules
DatabaseReference ref = FirebaseDatabase
.getInstance()
.getReference("/analyst_profiles");
DateTime dt = new DateTime(java.util.Date.from(Instant.now()), java.util.TimeZone.getDefault());
System.out.println(dt.getValue());
//test data push
// https://firebase.google.com/docs/database/admin/save-data
AnalystProfiles analystProfilesObjTemp = new AnalystProfiles("test2", Long.toString(dt.getValue()), "dsds", "ds", "ds",
"dsa2323", "32ddss232");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
AnalystProfiles post = dataSnapshot.getValue(AnalystProfiles.class);
System.out.println(post);
//done.countDown();
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
CompletableFuture<String> welcomeText = CompletableFuture.supplyAsync(() -> {
try {
ref.push().setValueAsync(analystProfilesObjTemp).get();
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException("Error while waiting for future", e);
}
return "ok";
}).thenApply(x -> {
System.out.println(x);
System.out.println("Listeners code is not executing");
return x;
});
done.countDown();
try {
System.out.println(welcomeText.get());
done.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public void testdataLoad() {
// The app only has access as defined in the Security Rules
DatabaseReference ref = FirebaseDatabase
.getInstance()
.getReference("/analyst_profiles");
DateTime dt = new DateTime(java.util.Date.from(Instant.now()), java.util.TimeZone.getDefault());
System.out.println(dt.getValue());
//test data push
// https://firebase.google.com/docs/database/admin/save-data
AnalystProfiles analystProfilesObjTemp = new AnalystProfiles("test2", Long.toString(dt.getValue()), "dsds", "ds", "ashutsh",
"dsa2323", "32ddss232");
CompletableFuture<String> welcomeText = CompletableFuture.supplyAsync(() -> {
try {
ref.push().setValueAsync(analystProfilesObjTemp).get();
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException("Error while waiting for future", e);
}
return "ok";
}).thenApply(x -> {
System.out.println(x);
return x;
});
try {
System.out.println(welcomeText.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
主驱动程序:-
package com.stocknap;
import com.zerodhatech.kiteconnect.KiteConnect;
import com.zerodhatech.kiteconnect.kitehttp.SessionExpiryHook;
import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException;
import org.json.JSONException;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by sujith on 7/10/16.
* This class has example of how to initialize kiteSdk and make rest api calls to place order, get orders, modify order, cancel order,
* get positions, get holdings, convert positions, get instruments, logout user, get historical data dump, get trades
*/
public class MainStockNap {
static PropertyFileReader propReader;
public static void main(String[] args) throws KiteException, IOException {
try {
ExecutorService executor = Executors.newFixedThreadPool(10);
KiteConnect kiteConnect = new KiteConnect("kbnbnmbnmbnm8877bvbv");
// Set userId
kiteConnect.setUserId("");
//Enable logs for debugging purpose. This will log request and response.
kiteConnect.setEnableLogging(true);
// Get login url
String url = kiteConnect.getLoginURL();
// Set session expiry callback.
kiteConnect.setSessionExpiryHook(new SessionExpiryHook() {
@Override
public void sessionExpired() {
System.out.println("session expired");
}
});
System.out.println(args.toString());
// reading params
if (args.length == 0){
System.out.println("config file path not given");
System.exit(0);
}
else{
//this.setConfigFile(args[2]);
propReader = new PropertyFileReader(args[0]);
}
//PropertyFileReader prop = new PropertyFileReader();
// Properties prop = Main.getConfigFile();
// System.out.println(prop.getConfigFile().getProperty("API_SECRET"));
ConfigLoader configObj= ConfigLoader.getInstance();
configObj.setConfigSource(propReader);
System.out.println("---------zerodha properties----------------");
System.out.println(configObj.get_CLIENT_ID());
System.out.println(configObj.get_API_SECRET());
System.out.println(configObj.get_APITOKEN());
System.out.println(configObj.get_PUBLICTOKEN());
System.out.println(configObj.get_APIKey());
System.out.println("---------firebase properties----------------");
System.out.println(configObj.getFirebaseAPIKey());
System.out.println(configObj.getFirebaseAuthDomain());
System.out.println(configObj.getFirebaseMessagingSenderId());
System.out.println(configObj.getFirebseProjectId());
System.out.println(configObj.getFirebaseStorageBucket());
System.out.println(configObj.getFirebaseDatabaseURL());
Firebase.INSTANCE.initilizeFirebaseApp(configObj);
Firebase.INSTANCE.testdataLoad();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
您的代码进行了很多工作,因此无法弄清您期望看到的内容。我将其略微修改为以下测试用例。这似乎工作正常:
@Test
public void initilizeFirebaseApp() throws Exception {
CountDownLatch done = new CountDownLatch(1);
DatabaseReference ref = FirebaseDatabase
.getInstance()
.getReference("/analyst_profiles");
DatabaseReference newChild = ref.push();
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getKey().equals(newChild.getKey())) {
System.out.println("New data: " + child.getValue());
done.countDown();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Object analystProfilesObjTemp = ImmutableMap.of("key", "value");
newChild.setValueAsync(analystProfilesObjTemp).get();
try {
done.await();
System.out.println("Listener hit for new child: " + newChild.getKey());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
我得到输出:
New data: {key=value}
Listener hit for new child: -LXW0CS2jFjphnoFKQkb