我正在尝试使用Firebase为Java桌面应用程序构建后端 [英] I am trying to use Firebase to build a Backend for a Java Desktop Application

查看:363
本文介绍了我正在尝试使用Firebase为Java桌面应用程序构建后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试用Java(不是Android)和Firebase进行简单用户身份验证。在开始使用Firebase的用户身份验证类之前,我尝试使用Java在Firebase Reference上进行简单的保存和检索,但没有成功。没有错误报告,但Firebase没有任何反应(没有更改数据)。过去,我已经能够将Firebase与Android SDK集成起来,没有任何问题。我为JVM使用了Firebase JAR,但没有发生任何事情。

  import com.firebase.client.AuthData; 
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
$ b $ ** b
$ b * @author Chidi
* /
public class Auth {
private final Firebase usersRef;
private boolean isNewUser = false;
private String uid = null;
私有HashMap< String,Object> userHash;

public Auth(){
Firebase rootRef = new Firebase(https://tranzchat.firebaseio.com/);
this.usersRef = rootRef.child(users);
userHash = new HashMap<>();

$ b $ public void createUser(final String email,final String password,String name,String default_lang){
userHash.put(email,email);
userHash.put(password,this.hashPassword(password));
userHash.put(name,name);
userHash.put(default_lang,default_lang);
Vars.dbcon.createUser(email,password,new Firebase.ResultHandler(){
@Override
public void onSuccess(){
System.out.println(Created the新用户);
//在创建新用户后将isNewUser设置为true $ b $ isNewUser = true;
signIn(email,password); $ b $ if(uid!= null) {
//尝试存储使用信息
Firebase newUserRef = usersRef.child(uid);
newUserRef.setValue(userHash,new Firebase.CompletionListener(){
@Override
public void onComplete(FirebaseError fe,Firebase frbs){
System.out.println(完成数据库插入);
}

});
} else {
System.out.println(Could not retrieve ve UID);


$ b $覆盖
public void onError(FirebaseError fe){
System.out.println(创建用户时发生错误。);
}
});

$ b $ public void signIn(String email,String password){
Vars.dbcon.authWithPassword(email,password,new Firebase.AuthResultHandler(){
@覆盖
public void onAuthenticated(AuthData authData){
uid = authData.getUid();
if(!isNewUser){
//尝试获取新的用户信息并将其存储在用户对象
usersRef.child(uid).addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot snapshot){
userHash =(HashMap< String ,Object>)snapshot.getValue();
}
@Override
public void onCancelled(FirebaseError firebaseError){
System.out.println(The read failed:+ firebaseError.getMessag E());
}
});

$ b @Override
public void onAuthenticationError(FirebaseError firebaseError){
//出现错误
}
});

public String hashPassword(String password){
String md5 = null;
if(password == null)return null;
尝试{
//为MD5创建MessageDigest对象
MessageDigest digest = MessageDigest.getInstance(MD5);
//更新消息摘要中的输入字符串
digest.update(password.getBytes(),0,password.length());
//以16为基数(十六进制)转换消息摘要值
md5 = new BigInteger(1,digest.digest())。toString();
} catch(NoSuchAlgorithmException e){
e.printStackTrace();
}
返回md5;


Test Suite
public static void main(String [] args)throws InterruptedException {
Vars.init();
线程firebaseAuth = new Thread(new Runnable(){
@Override
public void run(){
Auth au = new Auth();
au.createUser (chidiebere.nnadi@gmail.com,password,Chidiebere Nnadi,en);
}
});
firebaseAuth.start();
firebaseAuth.join();



$ div $解析方案

刚刚发现它的问题。线程在Firebase可以调用onComplete函数之前结束。你可以在应用程序的最后一行代码之后的一个循环内调用一个 Thread.sleep(x_ms)


I have been trying for a few days to do Simple User Authentication with Java (not Android) and Firebase. Before I started out with Firebase's user authentication classes I tried using Java to do a simple save and retrieve on my Firebase Reference with no success. No errors are reported but nothing happens in Firebase (no changes to the data). In the past, I have been able to integrate Firebase with Android SDK with no issues. I am making use of Firebase JAR for JVM but nothing is happening.

import com.firebase.client.AuthData;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

/**
 *
 * @author Chidi
 */
public class Auth {
    private final Firebase usersRef;
    private boolean isNewUser = false;
    private String uid = null;
    private HashMap<String, Object> userHash;

    public Auth() {
        Firebase rootRef = new Firebase("https://tranzchat.firebaseio.com/");
        this.usersRef = rootRef.child("users");  
        userHash = new HashMap<>();
    }

    public void createUser(final String email, final String password, String name, String default_lang) {
        userHash.put("email", email);
        userHash.put("password", this.hashPassword(password));
        userHash.put("name", name);
        userHash.put("default_lang", default_lang);
        Vars.dbcon.createUser(email, password, new Firebase.ResultHandler() {
            @Override
            public void onSuccess() {
                System.out.println("Created the new user");
                // Sets isNewUser to true after creating the new user
                isNewUser = true;
                signIn(email, password);
                if(uid != null) {
                    // Try to store use information
                    Firebase newUserRef = usersRef.child(uid);
                    newUserRef.setValue(userHash, new Firebase.CompletionListener(){
                        @Override
                        public void onComplete(FirebaseError fe, Firebase frbs) {
                            System.out.println("Completed Database Insertion");
                        }

                    });
                } else {
                    System.out.println("Could not retrieve UID");
                }
            }

            @Override
            public void onError(FirebaseError fe) {
                System.out.println("An error occured while creating the user.");
            }
        });
    }

    public void signIn(String email, String password) {
        Vars.dbcon.authWithPassword(email, password, new Firebase.AuthResultHandler() {
            @Override
            public void onAuthenticated(AuthData authData) {
                uid = authData.getUid();
                if(!isNewUser) {
                    // Try to get new user information and store it in the user object
                    usersRef.child(uid).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot snapshot) {
                            userHash = (HashMap<String, Object>) snapshot.getValue();
                        }
                        @Override
                        public void onCancelled(FirebaseError firebaseError) {
                            System.out.println("The read failed: " + firebaseError.getMessage());
                        }
                    });
                }
            }
            @Override
            public void onAuthenticationError(FirebaseError firebaseError) {
                // there was an error
            }
        });
    }
    public String hashPassword(String password) {
        String md5 = null;
        if(password == null) return null;
        try {
            // Create MessageDigest object for MD5
            MessageDigest digest = MessageDigest.getInstance("MD5");
            // Update input string in message digest
            digest.update(password.getBytes(), 0, password.length());
            // Converts message digest value in base 16 (hex)
            md5 = new BigInteger(1, digest.digest()).toString();
        } catch(NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return md5;
    }

    // Test Suite
    public static void main(String[] args) throws InterruptedException {
        Vars.init();
        Thread firebaseAuth = new Thread(new Runnable() {
            @Override
            public void run() {
                Auth au = new Auth();
                au.createUser("chidiebere.nnadi@gmail.com", "password", "Chidiebere Nnadi", "en");
            }
        });
        firebaseAuth.start();
        firebaseAuth.join();
    }
}

解决方案

I just found out the issue with it. The thread was ending before Firebase could call the onComplete function. You can just call a Thread.sleep(x_ms) within a loop after the last line of code in the application.

这篇关于我正在尝试使用Firebase为Java桌面应用程序构建后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆