Example of Firebase.push() in Java.

Google firebase push

Prerequisite


Push
Add to a list of data in the database. Every time you push a new node onto a list, your database generates a unique key, like items/<unique-item-id>/<data>

Push is basically used when you have collection of data like items, users, notifications and you want to generate unique id for each record in collection.

In previous example we've seen How to save data in Firebase?, It saves data as you provided within given path where push will generate unique id as root node of your data.

Source code (Item.java)
public class Item {

    private Long id;
    private String name;
    private Double price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

Source code (FirebasePushObject.java)
package com.javaquery.google.firebase;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.javaquery.bean.Item;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.CountDownLatch;

/**
 * Example of Firebase push.
 *
 * @author javaQuery
 * @date 22nd September, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class FirebasePushObject {
    
    public static void main(String[] args) {
        Item item = new Item();
        item.setId(1L);
        item.setName("MotoG");
        item.setPrice(100.12);
        
        // You can use List<Item> also.
        new FirebasePushObject().saveUsingPush(item);
    }
    
    private FirebaseDatabase firebaseDatabase;

    /**
     * initialize firebase.
     */
    private void initFirebase() {
        try {
            // .setDatabaseUrl("https://fir-66f50.firebaseio.com") - Firebase project url.
            // .setServiceAccount(new FileInputStream(new File("filepath"))) - Firebase private key file path.
            FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
                    .setDatabaseUrl("https://fir-66f50.firebaseio.com")
                    .setServiceAccount(new FileInputStream(new File("C:\\Users\\Vicky\\Documents\\NetBeansProjects\\Examples\\src\\com\\javaquery\\google\\firebase\\Firebase-30f95674f4d5.json")))
                    .build();

            FirebaseApp.initializeApp(firebaseOptions);
            firebaseDatabase = FirebaseDatabase.getInstance();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Save item object in Firebase.
     * @param item 
     */
    private void saveUsingPush(Item item) {
        if (item != null) {
            initFirebase();
            
            /* Get database root reference */
            DatabaseReference databaseReference = firebaseDatabase.getReference("/");
            
            /* Get existing child or will be created new child. */
            DatabaseReference childReference = databaseReference.child("items");

            /**
             * The Firebase Java client uses daemon threads, meaning it will not prevent a process from exiting.
             * So we'll wait(countDownLatch.await()) until firebase saves record. Then decrement `countDownLatch` value
             * using `countDownLatch.countDown()` and application will continues its execution.
             */
            CountDownLatch countDownLatch = new CountDownLatch(1);
            
            /**
             * push()
             * Add to a list of data in the database. Every time you push a new node onto a list, 
             * your database generates a unique key, like items/unique-item-id/data
             */
            childReference.push().setValue(item, new DatabaseReference.CompletionListener() {

                @Override
                public void onComplete(DatabaseError de, DatabaseReference dr) {
                    System.out.println("Record saved!");
                    // decrement countDownLatch value and application will be continues its execution.
                    countDownLatch.countDown();
                }
            });
            try {
                //wait for firebase to saves record.
                countDownLatch.await();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Output
Record saved!
Check Database in Firebase console.



How to save data in Firebase?

Firebase + Google

Prerequisite


Source code (Item.java)
public class Item {

    private Long id;
    private String name;
    private Double price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

Source code (FirebaseSaveObject.java)
package com.javaquery.google.firebase;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.javaquery.bean.Item;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.CountDownLatch;

/**
 * Example of Firebase save.
 *
 * @author javaQuery
 * @date 7th September, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class FirebaseSaveObject {

    public static void main(String[] args) {
        Item item = new Item();
        item.setId(1L);
        item.setName("MotoG");
        item.setPrice(100.12);

        // save item objec to firebase.
        new FirebaseSaveObject().save(item);
    }

    private FirebaseDatabase firebaseDatabase;

    /**
     * initialize firebase.
     */
    private void initFirebase() {
        try {
            // .setDatabaseUrl("https://fir-66f50.firebaseio.com") - Firebase project url.

            // Firebase private key(Generated while creating service account) file path.
            // .setServiceAccount(new FileInputStream(new File("filepath")))
            FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
                    .setDatabaseUrl("https://fir-66f50.firebaseio.com")
                    .setServiceAccount(new FileInputStream(new File("filepath\30f95674f4d5.json")))
                    .build();

            FirebaseApp.initializeApp(firebaseOptions);
            firebaseDatabase = FirebaseDatabase.getInstance();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Save item object in Firebase.
     * @param item 
     */
    private void save(Item item) {
        if (item != null) {
            initFirebase();
            
            /* Get database root reference */
            DatabaseReference databaseReference = firebaseDatabase.getReference("/");
            
            /* Get existing child or will be created new child. */
            DatabaseReference childReference = databaseReference.child("item");

            /**
             * The Firebase Java client uses daemon threads, meaning it will not prevent a process from exiting.
             * So we'll wait(countDownLatch.await()) until firebase saves record. Then decrement `countDownLatch` value
             * using `countDownLatch.countDown()` and application will continues its execution.
             */
            CountDownLatch countDownLatch = new CountDownLatch(1);
            childReference.setValue(item, new DatabaseReference.CompletionListener() {

                @Override
                public void onComplete(DatabaseError de, DatabaseReference dr) {
                    System.out.println("Record saved!");
                    // decrement countDownLatch value and application will be continues its execution.
                    countDownLatch.countDown();
                }
            });
            try {
                //wait for firebase to saves record.
                countDownLatch.await();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Output
Record saved!
Check Database in Firebase console.

Non-Android Runtimes
https://www.firebase.com/docs/android/guide/saving-data.html#section-other-runtimes
The Firebase Java client does not require the Android Runtime and can be used in any Java Runtime, including server-side Java processes or Java desktop applications.

The Firebase Java client uses daemon threads, meaning it will not prevent a process from exiting. When running on a non-Android runtime we may need to take extra steps to make sure that data is written to the server before our process exits. We can attach a CompletionListener to write operations and use a Semaphore or CountDownLatch object to prevent the process from exiting, as shown in the example below.

Reference
If you have collection of data to save in Firebase then you might me interested in reading Firebase.push(). - Example of Firebase.push() in Java.

How to create service accounts in Firebase?

In my previous article I explained How to create a project in Firebase? Now we'll see how you can create Service Accounts in Firebase.

Step 1: Open firebase project console and go to Permissions.

Firebase Permissions

Step 2: Go to Service accounts and click on Create Service Account


Step 3: Provide Service account name, select proper role for the account and check Furnish a new private key.

Note:Private key will be downloaded to your computer as key type you selected. Store it on secure location because this key will provide access to your database.

Firebase create service account

How to create a project in Firebase?


Firebase is realtime cloud database service provide. Firebase is recently acquired by Google Inc. We'll see how to create real time database project on Firebase.

Step 1: Go to https://firebase.google.com and login with Google account.

Step 2: Go to console from top right corner.

Step 3: Click on Create New Project.


Step 4: Provide Project name and select Country/region
Country/region
This represents the country/region of your organization/company. Your selection also sets the appropriate currency for your revenue reporting. The selected country does not determine the location of your data for Firebase features. Google may process and store Customer Data anywhere Google or its agents maintain facilities.


Step 5: You'll be redirected to Firebase database console.


Along with creating new project in Firebase, you may want to read How to create service accounts in Firebase?

Understanding Thread.join in Java


Thread.join()
Waits for this thread to die.

Thread.join(long millis)
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
Thread.join() and Thread.join(long millis) explained with real world example in Image.

Source code (MessageThread.java)
/**
 * Thread that prints message in interval of 4 seconds.
 *
 * @author javaQuery
 * @date 29th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class MessageThread implements Runnable {

    // Display a message, preceded by
    // the name of the current thread
    static void threadMessage(String message) {
        String threadName = Thread.currentThread().getName();
        System.out.format("%s: %s%n", threadName, message);
    }

    @Override
    public void run() {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };
        try {
            for (int i = 0; i < importantInfo.length; i++) {
                // Pause for 4 seconds
                Thread.sleep(4000);
                // Print a message
                threadMessage(importantInfo[i]);
            }
        } catch (InterruptedException e) {
            threadMessage("I wasn't done!");
        }
    }
}

Source code (ThreadJoinExample.java)
/**
 * Thread join example.
 * @author javaQuery
 * @date 29th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ThreadJoinExample {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new MessageThread());
        // start MessageThread.
        t.start();
        /**
         * Main Thread (ThreadJoinExample) will wait for 't' to finish 
         * its task in 5 seconds of it will leave.
         */
        t.join(5000);
        
        /**
         * Main Thread (ThreadJoinExample) will wait until 't' finish its task.
         */
        // t.join(); 
        System.out.println("Main Thread left(finish).");
    }
}

Output
Thread-0: Mares eat oats
Main Thread left(finish).
Thread-0: Does eat oats
Thread-0: Little lambs eat ivy
Thread-0: A kid will eat ivy too

Steps to setup DB2 Data Studio Client for Visual Explain of queries.

As a beginner, It was hard for me to figure out how to prepare visual execution plan in DB2 Data Studio Client. I was ending up with the following error.
com.ibm.datatools.dsoe.common.da.exception.OSCSQLException: com.ibm.db2.jcc.am.SqlSyntaxErrorException: The required Explain table "VICKY.EXPLAIN_INSTANCE" does not exist.. SQLCODE=-219, SQLSTATE=42704, DRIVER=3.68.61
     at com.ibm.datatools.dsoe.explain.luw.impl.ExplainThread.explain(Unknown Source)
     at com.ibm.datatools.dsoe.explain.luw.impl.ExplainThread.buildLUWExplainModelNeedSync(Unknown Source)
     at com.ibm.datatools.dsoe.explain.luw.impl.ExplainThread.commonProcess(Unknown Source)
     at com.ibm.datatools.dsoe.explain.luw.impl.ExplainThread.process(Unknown Source)
     at com.ibm.datatools.dsoe.explain.luw.Explainer.process(Unknown Source)
     at com.ibm.datatools.dsoe.ape.core.LUWAPEModelGenerator.generate(Unknown Source)
     at com.ibm.datatools.dsoe.ape.core.APEModelGenerator.generate(Unknown Source)
     at com.ibm.datatools.visualexplain.common.viewer.popup.LaunchVisualExplainFromEditorAction$1.run(Unknown Source)
     at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(Unknown Source)
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: The required Explain table "VICKY.EXPLAIN_INSTANCE" does not exist.. SQLCODE=-219, SQLSTATE=42704, DRIVER=3.68.61
     at com.ibm.db2.jcc.am.gd.a(Unknown Source)
     at com.ibm.db2.jcc.am.gd.a(Unknown Source)
     at com.ibm.db2.jcc.am.gd.a(Unknown Source)
     at com.ibm.db2.jcc.am.uo.c(Unknown Source)
     at com.ibm.db2.jcc.am.uo.d(Unknown Source)
     at com.ibm.db2.jcc.am.uo.a(Unknown Source)
     at com.ibm.db2.jcc.t4.bb.h(Unknown Source)
     at com.ibm.db2.jcc.t4.bb.b(Unknown Source)
     at com.ibm.db2.jcc.t4.p.a(Unknown Source)
     at com.ibm.db2.jcc.t4.vb.i(Unknown Source)
     at com.ibm.db2.jcc.am.uo.ib(Unknown Source)
     at com.ibm.db2.jcc.am.uo.a(Unknown Source)
     at com.ibm.db2.jcc.am.uo.e(Unknown Source)
     at com.ibm.db2.jcc.am.uo.execute(Unknown Source)
     ... 9 more


Steps to setup Visual Explain

Step 1: Switch Data Studio Activity. Administer Databases to Tune Queries (As shown in Image)

Administer Databases to Tune Queries+ DB2 Data Studio Client

Step 2: Right click Data Source. Analyze and Tune > Configure and Tuning > Guided Configuration (As shown in Image)


Now you can generate visual explain on your queries.

Example of Comparable in Java


Comparable<T>
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

You can use Comparator when you want different sorting option as per requirement. And you would also like to read How to sort List of Bean in Java? using Comparator and Comparable and How to sort Array in Ascending, Descending and Mixed mode in Java?

Source code (ComparableItem.java)
/**
 * Comparable item.
 * @author javaQuery
 * @date 11th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ComparableItem implements Comparable<ComparableItem>{

    private String name;
    private Double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
    
    @Override
    public int compareTo(ComparableItem item) {
        if(item != null && item.getName() != null){
            return this.getName().compareTo(item.getName());
        }
        return -1;
    }

    @Override
    public String toString() {
        return "ComparableItem{" + "name=" + name + ", price=" + price + '}';
    }
}

Source code (ComparableExample.java)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Example of Comparable.
 * @author javaQuery
 * @date 11th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ComparableExample {

    public static void main(String[] args) {
        ComparableItem samsung = new ComparableItem();
        samsung.setName("samsung");

        ComparableItem iphone = new ComparableItem();
        iphone.setName("iphone");

        List<ComparableItem> comparableItems = new ArrayList<ComparableItem>(2);
        comparableItems.add(samsung);
        comparableItems.add(iphone);
        
        new ComparableExample().performSort(comparableItems);
    }

    /**
     * Print list to console
     *
     * @param items
     */
    private void printListData(List<ComparableItem> items) {
        for (ComparableItem item : items) {
            System.out.println(item);
        }
    }
    
    /**
     * Perform sort on give List
     * @param comparableItems 
     */
    private void performSort(List<ComparableItem> comparableItems){
        System.out.println("Before sort:");
        printListData(comparableItems);
        System.out.println("===============================================");
        Collections.sort(comparableItems);
        System.out.println("After sort(orderByNameASC):");
        printListData(comparableItems);
    }
}

Output
Before sort:
ComparableItem{name=samsung, price=null}
ComparableItem{name=iphone, price=null}
===============================================
After sort(orderByNameASC):
ComparableItem{name=iphone, price=null}
ComparableItem{name=samsung, price=null}