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

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

问题描述

几天以来,我一直在尝试使用 Java(不是 Android)和 Firebase 进行简单的用户身份验证.在我开始使用 Firebase 的用户身份验证类之前,我尝试使用 Java 在我的 Firebase 参考上进行简单的保存和检索,但没有成功.没有错误报告,但 Firebase 中没有任何反应(数据没有变化).过去,我能够毫无问题地将 Firebase 与 Android SDK 集成.我正在为 JVM 使用 Firebase JAR,但没有任何反应.

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();
    }
}

推荐答案

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

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天全站免登陆