Writing Facebook Applications with Java EE (part 2)

In the first part of this blog, I showed how to register your application with facebook, create a web application and deal with Facebook authentication. In this part, I will show how to write a simple application, that shows the user their own Facebook UID and a list of all their friends. Nothing earth shatteringly useful, because this is just introduce you to the mechanics of writing a simple application.

Step 5: Write the application

Our application user is now authenticated. We can begin to make FQL calls and read/publish information to facebook. Our little sample, will use FQL to know more about the logged in user and the friends list.We told facebook that our application will run as an iframe in Facebook chrome. All we have to do is return some well formed html. We will do the "Hello World" type functionality and also show how to use FQL queries to extract information on all of the user's friends.

We will create a helper class Friend to hold the details of each facebbok user.  Later, I will show how to make this an Entity and store the data periststently, rather than make expensive and slow queries to facebook, repeatedly. The data could get stale and that is another issue to deal with later. Facebook does not encourage data caching.

public class Friend {

    private Long id;
    private String name;
    private String picurl;
    private String phone;

    public Friend() {
    }

    public Friend(Long id) {
        this.id = id;
    }

    public Friend(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Friend(Long id, String name, String pic) {
        this.id = id;
        this.name = name;
        this.picurl = pic;
    }

   // getters and setters have been omitted for brevity

}

The authenticated Facebook client is now available as a request attribute. We simply extract it and use it to make Facebook API calls. A helper method auth_getUserId provided by FacebookJsonRestClient extracts the facebook id of the logged in user. We will use this to get information on the user and friends.

 public class Canvas extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            FacebookJsonRestClient fbc = (FacebookJsonRestClient) request.getAttribute("auth.client");

            PrintWriter out = response.getWriter();
            long myUid = 0; Friend me = null;
            try {
                myUid = fbc.auth_getUserId(request.getParameter("auth_token"));
                me = findFacebookName("" + myUid, fbc);
            } catch (FacebookException ex) {
                Logger.getLogger(Canvas.class.getName()).log(Level.SEVERE, null, ex);
            }

            ArrayList<Friend> myFriends = findFacebookFriends(fbc);

// TODO: later in the blog,  show how data is output
    }

The method findFacebookName illustrates basic use of FQL that returns one result object. 

    private Friend findFacebookName(String fid, FacebookJsonRestClient fbc) {
        String name = null;
        String pic = null;
        try {
            String query = "SELECT name,pic FROM user WHERE uid=" + fid;
            org.json.JSONArray fa = null;
            fa = (org.json.JSONArray) fbc.fql_query(query);
            name = fa.getJSONObject(0).getString("name");
            pic = fa.getJSONObject(0).getString("pic");
        } catch (FacebookException ex) {
            Logger.getLogger(Canvas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSONException ex) {
            Logger.getLogger(Canvas.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new Friend(new Long(fid), pic, name);
    }

The method findFacebookFriends illustrates friends_get() that returns an array of Facebook Ids of all the user's friends. 

private ArrayList<Friend> findFacebookFriends(FacebookJsonRestClient fbc) {
        org.json.JSONArray resultArray = null;
        ArrayList friends = new ArrayList();
        try {
            resultArray = fbc.friends_get();
            for (int i = 0; i < resultArray.length(); i++) {
                try {
                    Long fid = resultArray.getLong(i);
                    String query = "SELECT name,pic FROM user WHERE uid=" + fid;
                    org.json.JSONArray fa = null;
                    try {
                        fa = (org.json.JSONArray) fbc.fql_query(query);
                        String pic = fa.getJSONObject(0).getString("pic");
                        String name = fa.getJSONObject(0).getString("name");
                        friends.add(new Friend(fid, name, pic));
                    } catch (FacebookException ex) {
                        Logger.getLogger(Canvas.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } catch (JSONException ex) {
                    Logger.getLogger(Canvas.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (FacebookException ex) {
            Logger.getLogger(Canvas.class.getName()).log(Level.SEVERE, null, ex);
        }
        return friends;
    }

Spitting it all out

After getting all the data we need, it is time to output something that will be shown to the end user, as the output a HTML page is shown in an iframe.

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {

            // Data Extraction: See Above
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<body>");
            out.println("Your Facebook Id:" + me.getId());

            out.println("Your friends:");
            out.println("<ol>");
            Iterator it = myFriends.iterator();
            while (it.hasNext()) {
                Friend f = (Friend) it.next();
                out.println("<li>Friend Name" + f.getName() + "</li>");
            }
            out.println("");
            out.println("</ol>");
            out.println("</body>");
            out.println("</html>");
            return;
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            return;
        }
    }

Conclusion

Deploy the web application to a Java EE server that is visible to the internet and is accessible at the Canvas callback URL you used when the application was registered at Facebook.

The sample application can be accessed directly specifying the Canvas Callback URL specified at registration (http://sailfin.webhop.net/FacebookSample/Canvas)  or  http://apps.facebook.com/glassbook.  It produces output as expected showing my Facebook Id and the names of all my friends. Real applications are of course, going to be a lot more interesting... This should get you, the Java EE developer, going..


Comments:

Post a Comment:
Comments are closed for this entry.
About

Various things I do at Sun Microsystems.

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today