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

Fbg Script Tag

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 in your page:

#{fbg.script /}

Facebook Namespace

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">

Facebook Login Button

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

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

If you need access to more information, such as the user’s birthday or wall, you must request permissions for this information. You can do this by adding the permissions you need to the perms attribute of the fb:login-button (e.g. perms="email,user_birthday,publish_stream").

A full list of permissions is available here.

JavaScript Function and Controller Action Method

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) and put the user’s name into the session:

public static void facebookLogin() {
    try {
        JsonObject profile = FbGraph.getObject("me"); // fetch the logged in user
        String email = profile.get("email").getAsString(); // retrieve the email
        // do useful things
        Session.current().put("username", email); // put the email into the session (for the Secure module)
    } catch (FbGraphException fbge) {
        flash.error(fbge.getMessage());
        if (fbge.getType() != null && fbge.getType().equals("OAuthException")) {
            Session.current().remove("username");
        }
    }
    redirect("/");
}

Examples

Reading

// Objects
JsonObject user             = FbGraph.getObject("btaylor");
JsonObject page             = FbGraph.getObject("cocacola");
// Connections
JsonArray friends           = FbGraph.getConnection("me/friends");
JsonArray newsFeed          = FbGraph.getConnection("me/home");
// Selection
JsonObject fields           = FbGraph.getObject("bgolub", Parameter.with("fields", "id,name,picture").parameters());
JsonElement ids             = FbGraph.api("", Parameter.with("ids", "arjun,vernal").parameters());
// Picture
String profilePicUrl        = FbGraph.getPicture("me");
// 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());

Searching

JsonArray publicPostSearch  = FbGraph.getConnection("search", Parameter.with("q", "watermelon").and("type", "post").parameters());
JsonArray publicUserSearch  = FbGraph.getConnection("search", Parameter.with("q", "mark").and("type", "user").parameters());

Publishing

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

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

Deleting

Boolan deleted = FbGraph.delete(OBJECT_ID);

Alternatives

Fbg Script Tag

You can replace the fbg.script tag with 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>

RestFB Client

The module also provides a RestFB client that you can invoke 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();
    // do useful things
    Session.current().put("username", email);
    redirect("/");
}

Known Issues