JavaEE和Firebase管理员sdk – setValueAsync不将数据推送到实时firebase

huangapple go评论88阅读模式
英文:

JavaEE and Firebase admin sdk - setValueAsync not pushing data to realtime firebase

问题

Am using firebase admin sdk and JavaEE on intellij built on gradle and glassfish server.

am trying to push a value to realtime database, but sadly am unable to do so. I've been searching online for weeks now and gotten nothing. I also followed some solutions in stackoverflow answers like : link but nothing works for me.

I've read a lot of reasons why such a problem would occur with firebase admin sdk but i have no solutions.

here's my code:

package sample;

import com.google.api.core.ApiFuture;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseToken;
import com.google.firebase.auth.UserRecord;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import sample.model.FireBaseAuth;
import sample.model.FireBaseUtils;
import sample.model.Owner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@WebServlet("/success")
public class SuccessServlet extends HttpServlet {

    public void init() throws ServletException {
        super.init();
        FireBaseUtils.initilizeFirebase();
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String email = request.getParameter("email");
        String password  = request.getParameter("pass");

        //System.out.println(name);

        try{
            //a hashmap for the number of shopsOwned
            HashMap<String, String> shopsOwned = new HashMap<>();
            shopsOwned.put("shopName" , "shopName");

            //get the database instance and the database reference
            FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference ref = database.getReference("Business");

            DatabaseReference ownersRef = ref.child("Owners"); //further get the reference to the owners node

            //create a new owner with the values of the new user, using the Owner class
            Owner newOwner = new Owner("userRecord2.getUid()", "userRecord2.getDisplayName()",
                    "userRecord2.getPhoneNumber()", "userRecord2.getEmail()", shopsOwned);

            //create a hashmap of the users, in this case, just one user
            Map<String, Owner> users = new HashMap<>();
            users.put("userRecord2getPhoneNumber", newOwner); //add the new owner to the hashmap

            System.out.println("this is the user :" + newOwner.getFull_name());

            //push the new owner hashmap to the database reference
            ApiFuture<Void> future = ownersRef.push().setValueAsync(users);

            //Object o = future.get(8, TimeUnit.SECONDS);
            System.out.println(future.isDone());
            //System.out.println(future.isDone());

            request.getRequestDispatcher("success.jsp").forward(request, response);

        }catch(Exception e){e.printStackTrace();}



    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        doGet(request, response);

    }

}

any ideas will be appreciated.

Edit : I dont get any errors whatsoever, the webapp runs normally but the realtime db at firebase isn't updated

英文:

Am using firebase admin sdk and JavaEE on intellij built on gradle and glassfish server.

am trying to push a value to realtime database, but sadly am unable to do so. I've been searching online for weeks now and gotten nothing. I also followed some solutions in stackoverflow answers like : https://stackoverflow.com/questions/43693797/firebase-java-admin-sdk-dont-work/43694454#43694454 but nothing works for me.

I've read a lot of reasons why such a problem would occur with firebase admin sdk but i have no solutions.

here's my code:

package sample;

package sample;
import com.google.api.core.ApiFuture;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseToken;
import com.google.firebase.auth.UserRecord;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import sample.model.FireBaseAuth;
import sample.model.FireBaseUtils;
import sample.model.Owner;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@WebServlet(&quot;/success&quot;)
public class SuccessServlet extends HttpServlet {
public void init() throws ServletException {
super.init();
FireBaseUtils.initilizeFirebase();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String email = request.getParameter(&quot;email&quot;);
String password  = request.getParameter(&quot;pass&quot;);
//System.out.println(name);
try{
//a hashmap for the number of shopsOwned
HashMap&lt;String, String&gt; shopsOwned = new HashMap&lt;&gt;();
shopsOwned.put(&quot;shopName&quot; , &quot;shopName&quot;);
//get the database instance and the database reference
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference(&quot;Business&quot;);
DatabaseReference ownersRef = ref.child(&quot;Owners&quot;); //further get the reference to the owners node
//create a new owner with the values of the new user, using the Owner class
Owner newOwner = new Owner(&quot;userRecord2.getUid()&quot;, &quot;userRecord2.getDisplayName()&quot;,
&quot;userRecord2.getPhoneNumber()&quot;, &quot;userRecord2.getEmail()&quot;, shopsOwned);
//create a hashmap of the users, in this case, just one user
Map&lt;String, Owner&gt; users = new HashMap&lt;&gt;();
users.put(&quot;userRecord2getPhoneNumber&quot;, newOwner); //add the new owner to the hashmap
System.out.println(&quot;this is the user :&quot; + newOwner.getFull_name());
//push the new owner hashmap to the database reference
ApiFuture&lt;Void&gt; future = ownersRef.push().setValueAsync(users);
//Object o = future.get(8, TimeUnit.SECONDS);
System.out.println(future.isDone());
//System.out.println(future.isDone());
request.getRequestDispatcher(&quot;success.jsp&quot;).forward(request, response);
}catch(Exception e){e.printStackTrace();}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doGet(request, response);
}
}

any ideas will be appreciated.

Edit : I dont get any errors whatsoever, the webapp runs normally but the realtime db at firebase isn't updated

答案1

得分: 1

你需要等待未来完成后,再返回请求线程。否则不能保证更新已完成,并且任何错误都会被静默丢弃。所以尝试类似以下的操作:

ApiFuture<Void> future = ownersRef.push().setValueAsync(users);
future.get();
request.getRequestDispatcher("success.jsp").forward(request, response);
英文:

You need to wait until the future is complete, before the request thread is returned. Otherwise there's no guarantee that the update is completed, and any errors are silently discarded. So try something like the following:

ApiFuture&lt;Void&gt; future = ownersRef.push().setValueAsync(users);
future.get();
request.getRequestDispatcher(&quot;success.jsp&quot;).forward(request, response);

答案2

得分: 0

写入到Firestore(以及大多数云API的交互)是异步进行的,而且在不同的线程上。当你调用future.isDone()时,操作尚未完成。

你需要添加一个回调,在操作完成时被调用:

ApiFuture<Void> future = ownersRef.push().setValueAsync(users);
future.addCallback(future, new ApiFutureCallback<String>() {
    @Override
    public void onSuccess(String result) {
      System.out.println("操作完成,结果为:" + result);
      System.out.println(future.isDone());
      request.getRequestDispatcher("success.jsp").forward(request, response);
    }

    @Override
    public void onFailure(Throwable t) {
      System.err.println("操作失败,错误为:" + t);
    }

另请参阅:

英文:

Writing to Firestore (like interaction with most cloud APIs) happens asynchronously, and on a different thread. When you call future.isDone(), the operation isn't done yet.

You'll want to add a callback that gets called when the operation has completed:

ApiFuture&lt;Void&gt; future = ownersRef.push().setValueAsync(users);
future.addCallback(future, new ApiFutureCallback&lt;String&gt;() {
@Override
public void onSuccess(String result) {
System.out.println(&quot;Operation completed with result: &quot; + result);
System.out.println(future.isDone());
request.getRequestDispatcher(&quot;success.jsp&quot;).forward(request, response);
}
@Override
public void onFailure(Throwable t) {
System.err.println(&quot;Operation failed with error: &quot; + t);
}

Also see:

huangapple
  • 本文由 发表于 2020年4月5日 22:01:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61043813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定