Ph: 0140714545
What's new? | Help | Directory | Sign in
Google
facebook-java-api
A Facebook API client implemented in Java, derived from the poorly-maintained official Facebook client.
  
  
  
  
    
Code License:
MIT License

Introduction

A Facebook API client implemented in Java, derived from the poorly-maintained official Facebook client.

Note that as of May 2008, Facebook has discontinued any support of their official Java client, directing users interested developing Facebook applications in Java to use one of the various third-party clients out there. As such, the purpose of this project is now to maintain, support, and extend the abandoned codebase to provide a high-quality, up to date version of the Facebook API client for Java developers, and to keep the Java client up to date as the Facebook Platform API changes and evolves.

In this project, we strive to preserve backwards compatibility between releases, and to be drop-in compatible for anyone using the "official" Facebook Java API client, insofar as is possible. However, Facebook is not particularly shy about changing thier platform API in ways that introduce breaking changes for developers, so there is no guarantee that compatibility can be preserved 100% of the time going forward. If that bothers you as much as it bothers me, I encourage you to complain to Facebook's development team and urge them to give a higher priority to issues of backwards compatibility when they are refactoring their platform API.

So while we strive to retain backwards compatibility in each new release, the need to keep the Java client compatible with the latest changes made to the Facebook Platform may override this goal. There's little sense in retaining compatibility with a client that won't even work properly, so the need to support the latest version of the Facebook Platform API may override backwards compatibility from time to time.

For more information, please download the README file or check out the latest project javadoc.

About the Beta

As discussed on the following page:

http://wiki.developers.facebook.com/index.php/New_Design_Platform_Changes

...Facebook is in the process of rolling out some substantial changes to portions of their API. Namely, the way applications integrate with the user's profile page and feeds, and how sessions are handled.

As of version 1.8-final, the beta process is considered over. The only feature that remains unverified in the Permissions API. Everything else should be working. If you find that it is not, please submit a bug report. Thanks.

Quick Start

1. Download the latest project JAR file at http://facebook-java-api.googlecode.com/files/facebook-java-api-1.8-final.jar

2. Download the required JSON library at http://facebook-java-api.googlecode.com/files/json-1.0.jar

3. If (and only if) you are using Java 5, also download the following libraries:

4. If you (and only if) will be running your application in an environment that does not automatically include the Sun activation framework (nearly all application servers will do this by default), also download the following library:

5. Deploy all of the downloaded JAR files onto your application server, or otherwise place them on your runtime classpath. This will allow you to use the Facebook Platform API.

6. If you need help using the API, consult the Project Javadoc, or scroll down for code examples.

Companion Utility (non-desktop apps)

As of v1.6.1, there is an optional companion JAR that enables additional enhanced features for FBML/Iframe apps. In essence, it provides many of the convenience methods that PHP Facebook developers have had available for some time now, such as automatic signature verification, and a simplified login API.

The companion utility relies on the servlet-api (which is why desktop apps cannot use it), so it requires a small amount of extra setup:

1. Configure the Facebook Java API by following the instructions above.

2. Download the latest companion JAR file at http://facebook-java-api.googlecode.com/files/facebook-util-1.8-final.jar.

3. Download the required servlet-api library at http://facebook-java-api.googlecode.com/files/servlet-api-2.4.jar.

4. Deploy all of the downloaded JAR files onto your application server, or otherwise place them on your runtime classpath. This will allow you to use the companion utility.

5. If you need help using the API, consult the Companion Utility Javadoc.

Additional details regarding the use of this utility can be found in the discussion group.

Comparison Matrix

Feature facebook-java-api Official Facebook API (2/9/2008) Official Facebook API 1.0 (July 2007)
Non-disruptive Updates Yes No No
Available as Binary Yes Yes No
Available as Source Yes Yes Yes
Javadoc Available Yes No No
64-bit UID's Yes No No
JAXB Integration Yes No No
Backwards Compatible Yes No Not Applicable
Cross-compatible Yes No No
'Pair' implemented correctly Yes Yes No
Configurable connection timeouts Yes, since v1.6.1 No No
Support feed_templatizedAction Yes, since v1.1 Yes No
Support data.setUserPreference(s) Yes, since v1.2 No No
Support data.getUserPreference(s) Yes, since v1.2 No No
Support SMS API Yes, since v1.2 Yes No
Support Marketplace API Yes, since v1.3 Yes No
Support Admin API Yes, since v1.6.1 Yes No
Support data.setCookie Yes, since v1.6.1 Yes No
Support data.getCookie Yes, since v1.6.1 Yes No
Support Batch API Yes, since v1.7.1 No No
Support All non-beta API calls Yes, since v1.3 No (missing Admin.getAllocation, photos_addTag throws NPE) No
Actively Maintained Yes No No
Time Between Releases ~1 month Development Discontinued Not Applicable

Project Changelog

From 1.8-beta to 1.8-final
Fix numerous bugs from the project issue list (credit goes to fernman, thanks dude!). Refresh JAXB bindings with latest official schema. Fix bug with calling profile_setFBML from desktop-mode apps. Add Feed.deactivateTemplateBundleByID API call. Support 'general'/'announcement' flag to Notifications.send. Support images in Feed.publishUserAction calls.
From 1.8-alpha to 1.8-beta
Update feed_registerTemplateBundle to latest specs (Facebook changed some params). Add 'setServerUrl()' and 'useBetaApiServer()' utility methods to change API server URL/point client at beta server. Fix several bugs in new feed and profile methods. Allow TemplatizedAction to use UID's/Photo ID's to specify images. Add support for LiveMessage.send API call. Add support for Admin.getMetrics API call. New feed and profile methods are tested and should work.
From 1.7.4 to 1.8-alpha
Implement all new methods described at http://wiki.developers.facebook.com/index.php/New_Design_Platform_Changes. Implement all session changes described at http://wiki.developers.facebook.com/index.php/New_Design_Platform_Changes. Add support for Permissions API [NOT TESTED!]. Refresh all JAXB generated classes using latest Facebook schema document. Cache JAXBContext instead of creating a new one on each API call. Add auth.promoteSession and auth_expireSession API calls. Add admin.getDailyMetrics API call. Reduce output when not running in debug mode. Add missing ApplicationProperty fields to enum.
From v1.7.3 to 1.7.4
Disable admin.getAppProperties, admin.setAppProperties, and fbml.setRefHandle from desktop apps (as per API spec). Fix bug where FacebookXmlRestClient/FacebookJsonRestClient could not call admin.getAllocation. Improve parsing of multiline field values from XML. Add getters/setters for some internal client vars.
From v1.7.2 to 1.7.3
Fix bug where calling 'Admin.getAllocation' would always throw an exception. Minor optimizations to user-id caching.
From v1.7.1 to 1.7.2
Add 'Application.getPublicInfo' API call. Update JAXB bindings (adds support for several newer API calls). Add 'Admin.getAllocation' API call. Fold in official API changes made on 2/8/09.
From v1.7 to 1.7.1
Implement the 'batch' API. Fix some bugs in the JSON and JAXB clients. Fix some NPE bugs.
From v1.6.2 to 1.7
Merge in changes from official Facebook API made on 1/20/2008. Add 'pageActorId' attribute to TemplatizedAction utility class. Fix several NPE issues in feed_publishTemplatizedAction. Fix ClassCastException in FacebookJsonRestClient.
From v1.6.1 to 1.6.2
Fix bug where calling admin_getAppProperties would throw an Exception. Add ability to retrieve app properties as a Map<ApplicationProperty, String> (admin_getAppPropertiesMap). Fix bug where sms_sendMessage would call the wrong API method. Fix multiple bugs in feed_publishTemplatizedAction (encode maps properly, don't ignore actorId parameter). Add ability to lookup an ApplicationProperty by name.
From v1.6 to 1.6.1
Add 'Facebook' utility class (in seperate JAR file). Add support for admin.getAppProperties and admin.setAppProperties. Add support for data.getCookies and data.setCookie. Add support for configurable connection timeout settings for Facebook API requests. Add autoVerifySignature convenience method. Update JAXB bindings (add has 'has_added_app' property to user, support new API methods, etc.). Set 'expires' field correctly when getting a session. Fix logic error in photos_addTag (avoid NPE when trying to add a text tag instead of a UID-based tag). Remove some unimplemented methods that are now provided by the official API.
From v1.5.2 to 1.6
Fix parsing bug in JAXB client. Support upcoming API changes to profile.setFBML. Allow notifications.sendEmail to be called without a session when using a non-desktop app. Merge in changes from official Facebook API made on 12/11/2007.
From v1.5.1 to 1.5.2
Add support for the notifications.sendEmail API call. Deprecate 'email' parameter of notifications.send, provide an alternate version with no 'email' parameter. Update users.setStatus to include the 'status_includes_verb' parameter. Made session-key optional when using 'Pages' API calls. Minor updates to the Facebook 'sig' parameter list.
From v1.5 to 1.5.1
Fix minor bug with international characters screwing up the 'sig' utilities. Rebuild the JAR with Java 5 to ensure its compatibility for Java 5 users.
From v1.4 to v1.5
Fix various bugs in FacebookJsonRestClient (should actually be usable now). Merge in changes from official Facebook API made on 11/7/2007.
From v1.3 to v1.4
Merge in changes from official Facebook API made on 10/30/2007. Refactor changes so that they don't break reverse compatibility for anyone using the official API. Refactor changes so that they don't break reverse compatibility for anyone using a previous version this API. Add a 'FacebookJaxbRestClient' that returns JAXB objects when making API calls. Extend the 'IFacebookRestClient' interface to include sms and data API calls. Refactor any UID's that were expressed as Integers in the new Facebook code to use Longs. Remove dependency on the simple-json library, the previous json library is still used. Add some new utility methods to 'FacebookXmlRestClient' and 'FacebookJsonRestClient'. Cleanup, add documentation, deprecate things where appropriate.
From v1.2 to v1.3
Add support for all 'marketplace' API calls. Add support for users.hasAppPermission and users.setStatus API calls. Add support for fbml.setRefHandle API call. Add support for 'sms' API calls. Add support for data.setUserPreference(s) and data.getUserPreference(s) API calls. Add JAXB bindings for all 'marketplace' and 'data' API calls. Add MarketListing utility class to assist in creating marketplace listings. Define enum's that can be used for specifying marketplace categories, subcategories, and status codes. client now supports all "official" API methods as specified at http://wiki.developers.facebook.com/index.php/API
From v1.1 to v1.2:
Add JAXB bindings for all FacebookRestClient methods that return a Document. Add utility method to get the JAXB response object corresponding to the last API call made through the client.
From v1.0 ("official" Facebook release in July) to v1.1:
The 'Pair' class has been factored out of FacebookRestClient, and is now public. All object id's use 64-bit longs as their datatype to be compatible with pending Facebook platform changes. 'notifications_sendRequest' is marked as deprecated (it is no longer supported by Facebook). 'feed_publishActionOfUser' is marked as deprecated (it is being replaced with 'feed_publishTemplatizedAction'). Add support for 'feed_publishTemplatizedAction' API call. Add 'TemplatizedAction' utility class to assist in creating feed entries through 'feed_publishTemplatizedAction'. Add ability to retrieve the raw XML/text snippet returned by the Facebook API server (note that this can only be called once per API call). Update/add javadoc comments. Provide more useful error messages and debugging output. Removed 'ExampleClient' sample application (removes spurious dependency on BrowserLauncher). Fixed various bugs in 'PhotoTag' class.

Code Examples

Getting a User's Friends:

    FacebookRestClient client = new FacebookRestClient("apiKey", "secretKey", "sessionId");
    client.friends_get();
    FriendsGetResponse response = (FriendsGetResponse)client.getResponsePOJO();
    List<Long> friends = response.getUid();

Executing a Batch Query

    //set the client to run in batch mode
    client.beginBatch();
            
    //these commands will be batched
    client.users_getLoggedInUser();
    client.friends_get();
            
    //execute the batch (which also terminates batch mode until beginBatch is called again)
    List<? extends Object> batchResponse = client.executeBatch(false);
            
    //the list contains the results of the queries, in the same order they were defined
    Long userId = (Long) batchResponse.get(0);
    Document friends = (Document)batchResponse.get(1);
    NodeList nodes = friends.getElementsByTagName("uid");
            
    //print the results
    System.out.println("USER:  " + userId);
    for (int index = 0; index < nodes.getLength(); index++) {
        System.out.println("FRIEND:  " + nodes.item(index).getFirstChild().getTextContent());
    }

Update a User's Status Message:

    if (client.users_hasAppPermission(Permission.STATUS_UPDATE)) {
        client.users_setStatus("developing Facebook apps in Java because the new Java client kicks the PHP client's ass!", false);
    }

Send SMS to a User:

    FacebookRestClient client = new FacebookRestClient("apiKey", "secretKey", "sessionId");
    if (client.sms_canSend()) {
        client.sms_send("I can send you text messages now!", null, false);
    }

Publishing a Templatized Feed Entry:

    //using the TemplatizedAction utility class helps keep things sane
    TemplatizedAction action = new TemplatizedAction("{actor} recommends {book}");                      //the user has recommended a book

    action.addTitleParam("book", "<a href='http://www.amazon.com/Hamlet/dp/0140714545/'>Hamlet</a>");   //specify the specific book
    action.setBodyTemplate("{actor} is using BooksApp!");                                               //set a body template (optional)
    action.setBodyGeneral("100 other people recommend this book!");                                     //set general body content (optional)
    action.addPicture("http://code.google.com/hosting/images/code_sm.png", "http://www.google.com");    //add up to 4 pictures (optional)
    action.addPicture("http://code.google.com/hosting/images/code_sm.png", "http://www.google.com");
    action.addPicture("http://code.google.com/hosting/images/code_sm.png", "http://www.google.com");
    action.addPicture("http://code.google.com/hosting/images/code_sm.png", "http://www.google.com");
    
    client.feed_PublishTemplatizedAction(action);                                                       //publish to feed

Playing With User Preferences:

    FacebookRestClient client = new FacebookRestClient("apiKey", "secretKey", "sessionId");
    Map<Integer, String> prefs = client.data_getUserPreferences();
    
    //show any preferences that are currently set for the user, all at once
    System.out.println("Preferences already set:");
    for (Integer key : prefs.keySet()) {
        System.out.println("\tkey " + key + " = " + prefs.get(key));
    }
        
    //set the values of some preferences, one at a time    
    client.data_setUserPreference(1, "test1");
    client.data_setUserPreference(2, "test2");
    client.data_setUserPreference(3, "0");
    
    //retrieve some of the set values, one at a time    
    System.out.println("Preference 2 is:  " + client.data_getUserPreference(2));
    System.out.println("Preference 1 is:  " + client.data_getUserPreference(1));
        
    //retrieve all the values at once
    System.out.println("All current preferences:");
    prefs = client.data_getUserPreferences();
    for (Integer key : prefs.keySet()) {
        System.out.println("\tkey " + key + " = " + prefs.get(key));
    }
        
    //set several new preference values at once, preserving any existing values    
    Map<Integer, String> vals = new HashMap<Integer, String>();
    vals.put(4, "test4");
    vals.put(5, "test5");
    vals.put(6, "test6");
    client.data_setUserPreferences(vals, false);

    //retrieve all the values at once
    System.out.println("All current preferences:");
    prefs = client.data_getUserPreferences();
    for (Integer key : prefs.keySet()) {
        System.out.println("\tkey " + key + " = " + prefs.get(key));
    }
    
    //set several new preference values at once, *removing* any existing values   
    client.data_setUserPreferences(vals, true);
    
    //retrieve all the values at once (to show that anything not in 'vals' is now gone) 
    System.out.println("All current preferences:");
    prefs = client.data_getUserPreferences();
    for (Integer key : prefs.keySet()) {
        System.out.println("\tkey " + key + " = " + prefs.get(key));
    }



You are viewing a mobilized version of this site...
View original page here

Mobilized by Mowser Mowser