Community contributed extensions

Facebook Graph API support

The FbGraph module enables your application to access all the features of the Facebook Graph API via Java and the Play Framework. It is inspired by the Grails Facebook Graph Plugin and uses the JavaScript SDK to provide simple login and signup.

Prerequisites

The FbGraph module requires that you register your application with Facebook to get an application id for your site.

Installation and configuration

Start by installing the FbGraph module from the modules repository:

play install fbgraph-{version}

Then, edit the application.conf file to enable the FbGraph module:

# Additional modules
# ~~~~~
# A module is another play! application. Add a line for each module you want
# to add to your application. Modules path are either absolutes or relative to
# the application root.
# They get loaded from top to bottom; Syntax: module.{name}={path}
#
# Keep the next line as is to help the play script to manage modules.
# ---- MODULES ----
module.fbgraph=${play.path}/modules/fbgraph-{version}

Finally, configure the module by setting these properties in your application.conf:

# FbGraph
# ~~~~~
fbg.appId={YOUR_APP_ID}
fbg.appSecret={YOUR_APP_SECRET}

Usage

The FbGraph module provides a tag for loading the JavaScript SDK. It uses the standard script element, calls FB.init() and specifies a div element named fb-root within the document.

First, include the following tag at the bottom of your page:

#{fbg.script /}

You are free to add your own full code, like this:

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
    FB.init({appId: 'YOUR_APP_ID', status: true, cookie: true, xfbml : true});
</script>

Next, add the fb namespace in your html tag:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

Then, add the following Facebook tag anywhere you want in your page to render the standard Facebook login button:

<fb:login-button perms="email,publish_stream" size="medium" onlogin="facebookLogin();"></fb:login-button>

Finally, implements a javascript function that will be called if the Facebook login is successful:

<script type="text/javascript">
    function facebookLogin() {
        // get current login status from facebook.com
        FB.getLoginStatus(function(response) {
            if (response.session) {
                // logged in and connected user, someone you know
                window.location = "@{Application.facebookLogin()}";
            } else {
                window.location = "@{Secure.logout()}";
            }
        });
    }
</script>

In this example, the application will redirect the browser to the action /application/facebookLogin. The URL will invoke the controllers.Application.facebookLogin() action method. In this action, you can do useful things like retrieving an object of the domain class that represents a user (or create one if it doesn’t exist):

public static void facebookLogin() {
    try {
        JsonObject profile = FbGraph.getObject("me");
        // or use the basic api method directly -> JsonObject profile = FbGraph.api("me").getAsJsonObject();
        String email = profile.get("email").getAsString();
        User user = User.findByEmail(email);
        if (user == null) {
            user = new User();
            user.firstName = profile.get("first_name").getAsString();
            user.lastName = profile.get("last_name").getAsString();
            user.email = email;
            user.gender = profile.get("gender").getAsString();
            user.insert();
        }
        Session.current().put("username", email);
    } catch (FbGraphException fbge) {
        if (fbge.getType().equals("OAuthException")) {
            flash.error("Facebook Authentication Failure", "");
        }
    }
    redirect("/");
}

The module also provides a RestFB client that you can use like this:

public static void facebookLogin() {
    com.restfb.FacebookClient fbClient = FbGraph.getFacebookClient();
    com.restfb.types.User profile = fbClient.fetchObject("me", com.restfb.types.User.class);
    String email = profile.getEmail();
    User user = User.findByEmail(email);
    if (user == null) {
        user = new User();
        user.firstName = profile.getFirstName();
        user.lastName = profile.getLastName();
        user.email = email;
        user.gender = profile.getGender();
        user.insert();
    }
    Session.current().put("username", email);
    redirect("/");
}

Some examples

Getting an object

JsonObject user = FbGraph.getObject("btaylor");
JsonObject page = FbGraph.getObject("cocacola");

Getting a connection

JsonArray friends = FbGraph.getConnection("me/friends");
JsonArray likes = FbGraph.getConnection("me/likes");

Getting a picture URL

String picUrl = FbGraph.getPicture("me");
<img src="${picUrl}" />

Searching

JsonArray publicSearch = FbGraph.getConnection("search", Parameter.with("q", "watermelon").and("type", "post").parameters());
JsonArray targetedSearch = FbGraph.getConnection("me/home", Parameter.with("q", "mark").and("type", "user").parameters());

Paging

JsonArray filteredLikes = FbGraph.getConnection("me/likes", Parameter.with("limit", "3").parameters());
JsonArray filteredSearch = FbGraph.getConnection("search", Parameter.with("until", "yesterday").and("q", "orange").parameters());

Publishing

FbGraph.publish("me/feed", Parameter.with("message", "Hello World!").parameters());

Note: Most write operations require extended permissions for the active user.