My favorites | Sign in
Project Logo
                
Search
for
Updated May 08, 2009 by david.j.boden
Examples  
This page contains example code of how to use the newer features of the client.

Servlet Filter to run for every request

This servlet filter ensures that the user is logged in, within a frame inside Facebook and obtains the session key for the user.

From your servlet, you just need to call the getUserClient() static method to get hold of the client. You can then make Facebook API calls on the client.

import static com.emobus.stuff.LoggerConstants.facebookUserId;
import static com.emobus.stuff.LoggerConstants.ipAddress;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.w3c.dom.Document;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookWebappHelper;
import com.google.code.facebookapi.FacebookXmlRestClient;
import com.google.code.facebookapi.IFacebookRestClient;

/**
 * The Facebook User Filter ensures that a Facebook client that pertains to
 * the logged in user is available in the session object named "facebook.user.client".
 * 
 * The session ID is stored as "facebook.user.session". It's important to get
 * the session ID only when the application actually needs it. The user has to 
 * authorise to give the application a session key.
 * 
 * @author Dave
 */
public class FacebookUserFilter implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(FacebookUserFilter.class);
	
	private String api_key;
	private String secret;
	
	private static final String FACEBOOK_USER_CLIENT = "facebook.user.client";
	
	public void init(FilterConfig filterConfig) throws ServletException {
		api_key = filterConfig.getServletContext().getInitParameter("facebook_api_key");
		secret = filterConfig.getServletContext().getInitParameter("facebook_secret");
		if(api_key == null || secret == null) {
			throw new ServletException("Cannot initialise Facebook User Filter because the " +
					                   "facebook_api_key or facebook_secret context init " +
					                   "params have not been set. Check that they're there " +
					                   "in your servlet context descriptor.");
		} else {
			logger.info("Using facebook API key: " + api_key);
		}
	}
	
	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		try {
			MDC.put(ipAddress, req.getRemoteAddr());
			
			HttpServletRequest request = (HttpServletRequest)req;
			HttpServletResponse response = (HttpServletResponse)res;
			
			HttpSession session = request.getSession(true);
			IFacebookRestClient<Document> userClient = getUserClient(session); 
			if(userClient == null) {
			    logger.debug("User session doesn't have a Facebook API client setup yet. Creating one and storing it in the user's session.");
			    userClient = new FacebookXmlRestClient(api_key, secret);
			    session.setAttribute(FACEBOOK_USER_CLIENT, userClient);
			}
			
			logger.trace("Creating a FacebookWebappHelper, which copies fb_ request param data into the userClient");
			FacebookWebappHelper<Document> facebook = new FacebookWebappHelper<Document>(request, response, api_key, secret, userClient);
			String nextPage = request.getRequestURI();
			nextPage = nextPage.substring(nextPage.indexOf("/", 1) + 1); //cut out the first /, the context path and the 2nd /
			logger.trace(nextPage);	
			boolean redirectOccurred = facebook.requireLogin(nextPage);
			if(redirectOccurred) {
				return;
			}
			redirectOccurred = facebook.requireFrame(nextPage);
			if(redirectOccurred) {
				return;
			}
			
			long facebookUserID;
			try {
			    facebookUserID = userClient.users_getLoggedInUser();
			} catch(FacebookException ex) {
			    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while fetching user's facebook ID");
			    logger.error("Error while getting cached (supplied by request params) value " +
			    		     "of the user's facebook ID or while fetching it from the Facebook service " +
			    		     "if the cached value was not present for some reason. Cached value = {}", userClient.getCacheUserId());
			    return;
			}
			
			MDC.put(facebookUserId, String.valueOf(facebookUserID));
			
			chain.doFilter(request, response);
		} finally {
			MDC.remove(ipAddress);
			MDC.remove(facebookUserId);
		}
	}

    public static FacebookXmlRestClient getUserClient(HttpSession session) {
	    return (FacebookXmlRestClient)session.getAttribute(FACEBOOK_USER_CLIENT);
	}
}

Getting a User's Friends

You select the FacebookXXXRestClient replacing XXX with either Json, Xml or Jaxb depending on how you want the results to be returned to you:

    FacebookJsonRestClient client = new FacebookJsonRestClient("apiKey", "secretKey", "sessionId");
    JSONArray response = (JSONArray)client.friends_get();

PROBABLY DEPRECATED

Heads up. Most of these examples were created against the 1.8.0 version of the library. But the current latest version is 2.0.x. So there is no guarantee that these examples will work perfectly.

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));
    }

Comment by joebune, Aug 07, 2008

I found this to be the easiest way to get a session. 1st create the application on facebook and setup the callback param. Write this code somewhere in a servlet.

Facebook face = new Facebook(request, response, "apiKey", "secretKey"); face.requireLogin(""); // this will send the user to facebook to login and

// facebook will redirect the user back to the // application with a session.
if ( !face.isLogin() )
return null; // if they are not logged in response will be commited
// and the response was sent to facebook, so exit your // here.

FacebookRestClient? client = face.get_api_client(); // if you get here you have

// a session
client.friends_get(); FriendsGetResponse? response = (FriendsGetResponse?)client.getResponsePOJO(); List<Long> friends = response.getUid();

if ( !face.isLogin() )

return null;

Comment by garth.newton, Aug 12, 2008

Is there any chance of getting an extended example of getting a user's friends?

I've tried the following:

Facebook face = new Facebook(request, response, apiId, secretId);
face.requireLogin("");

if (!face.isLogin()) {
  return;
}

FacebookRestClient client = face.get_api_client();a session
client.friends_get();
FriendsGetResponse response = (FriendsGetResponse) client.getResponsePOJO();
List<Long> friends = response.getUid();

Set<ProfileField> c = new HashSet<ProfileField>();
c.add(ProfileField.FIRST_NAME);
c.add(ProfileField.LAST_NAME);
c.add(ProfileField.NAME);
c.add(ProfileField.SEX);

client.users_getStandardInfo(friends, c);
UsersGetStandardInfoResponse uResponse = (UsersGetStandardInfoResponse) client.getResponsePOJO();

but this gives me

Facebook returns error code 3
...
ERROR [13-08-08 10:20:31] (FacebookCommands.java:89) - MyApp: Facebook exception: 
com.facebook.api.FacebookException: Unknown method
at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:828)
at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:606)
at com.facebook.api.FacebookRestClient.users_getStandardInfo(FacebookRestClient.java:1404)
...
Comment by maxneust, Aug 21, 2008

@garth.newton: try with client.users_getInfo(friends, c) instead of client.users_getStandardInfo(friends, c).

Hope it helps.

Max

Comment by stefanasseg, Aug 22, 2008

for those of you trying to mess with the facebook api within a desktop app, check this out: http://stud3.tuwien.ac.at/~e0525278/facebookapi_getfriends/

hope it's useful ..

stefan

Comment by slopixi, Sep 12, 2008

how get messages and news feed from user, in my investigation i discoverd only publishing this data but cant get them to show on desktop app.

need help.

Comment by Piotr.Skowronek, Sep 17, 2008

Hi,

Regarding: Publishing a Templatized Feed Entry example... Is there anybody that has succeeded with this? I mean, does any feed entry has appeared in the facebook profile/feeds whatever?

Regards, Piotr

Comment by arun.shivaraman, Sep 25, 2008

Can someone please post basic end-end example of using this API?

Thanks Arun

Comment by mroman, Oct 05, 2008

Hi,

I have been trying to use this java library but so far I am having problems. I have tried to use the "requireLogin" from the example above but Facebook comes back with an error saying it cannot load the page (after the code is executed at the servlet). Has anyone been able to implement the requireLogin successfully?

Thanks

Comment by upeksha.dharmatilake, Oct 06, 2008

Hi guys, Can u please update this sample codes so that we can have an idea how to start using this API. Appriciate helps and feedbacks from experts who have already used this.

Thanks in advance Upeksha

Comment by kristjan.ugrin, Oct 06, 2008

I agree. Yesterday I spent just few minutes playing with it, today I'll try to do more.

Anyone got it working at all recently?

Comment by mroman, Oct 08, 2008

I have been playing with the examples and tried to use the requireLogin but no luck so far. I would really appreciate if someone could confirm the code is working at all.

Comment by upeksha.dharmatilake, Oct 09, 2008

hi guys, I use pure Java with JSP pages to do this. I went through the source code and managed to start up as follows

	private void initSession() {
		restClient = new FacebookJsonRestClient(Constants.API_KEY,
				Constants.SEC_KEY);
		facebookWeb = new FacebookWebappHelper(request, response,
				Constants.API_KEY, Constants.SEC_KEY, restClient);

	}

This was the code I used to initialized the facebook related Ojects. I got an exception for FacebookJaxbRestClient restClient I think i can resolve it soon.

As this way I could validate the user session and managed to get the userId using this method (After initializing the clients and facebookWeb objects

public long getUserLogedIn() {
		Long userId = null;
		if (facebookWeb != null) {
			userId = facebookWeb.get_loggedin_user();
		}
		if (userId == null) {
			userId = new Long(0);
		}
				return userId.intValue();
	}

and to check loged in user status

public boolean isLogedIn() {
		if (facebookWeb != null) {
			return facebookWeb.isLogin();
		} else {
			return false;
		}
	}

Hope this will help SOMEONE bec i was crashing my head over this before :)

Good luck guys Upeksha

Comment by olamar72, Oct 19, 2008

Example on how to retreieve groups with the json client:

// Set this up in a filter og servlet:

FacebookWebappHelper?<Object> helper = FacebookWebappHelper?.newInstanceJson

(request, response, "API_KEY", "SECRET" );
helper.requireLogin(null); IFacebookRestClient<Object> facebook = helper.getFacebookRestClient();

// Get all groups

JSONArray groups = (JSONArray)facebook.groups_get(null, null);

// Get first group
JSONObject group = groups.optJSONObject(0);
// Print name of group
System.out.println(group.getString("name"));

It would have been nice to avoid the pain of casting the result though;-)

Comment by shalinjshah, Oct 19, 2008

Hi, I am facing issue while getting friends list of logged in user.

I am using spring mvc controller servlet to do this:

String apiKey = "5f06856d94024c1cad07731ddcb00d8c";
String secret = "60b04d1f66eb5722d7a5202c84324ce5"; FacebookXmlRestClient? client = new FacebookXmlRestClient?(apiKey, secret); FacebookWebappHelper? fwh = new FacebookWebappHelper?(request, response, apiKey, secret, client); fwh.requireLogin("http://apps.facebook.com/iframehp/");

This code redirect user to facebook login page and ask him to authenticate and works fine.

Now my apps url in requireLogin method redirect to another servlet, and this servlet code is as below:

try {

String apiKey = "5f06856d94024c1cad07731ddcb00d8c"; String secret = "60b04d1f66eb5722d7a5202c84324ce5";
String authToken = arg0.getQueryString(); String authKey = authToken.substring(authToken.indexOf("=")+1, authToken.length());
FacebookXmlRestClient? client = new FacebookXmlRestClient?(apiKey, secret, authKey);
client.setIsDesktop(false); try {
client.auth_getSession(authKey); client.friends_get(); FriendsGetResponse? resp = (FriendsGetResponse?)client.getResponsePOJO(); List<Long> friends = resp.getUid();
System.out.println(friends);
} catch (Exception e) {
System.out.println(e.getMessage());
}

} catch (Exception e) {
e.printStackTrace();
}

My problem here is that I get null resp object when I do

FriendsGetResponse? resp = (FriendsGetResponse?)client.getResponsePOJO();

Though in client object I get rawResponse which is as below:\

<?xml version="1.0" encoding="UTF-8"?><friends_get_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true"> <uid>7301348</uid> <uid>509109913</uid> <uid>536041473</uid> <uid>542115546</uid> <uid>547961475</uid> <uid>583870367</uid> <uid>590792034</uid> <uid>609155892</uid> <uid>615901172</uid> <uid>627539438</uid> <uid>627965941</uid> <uid>629934611</uid> <uid>635582190</uid> <uid>638904534</uid> <uid>651945439</uid> <uid>653556098</uid> <uid>730267352</uid> <uid>769868687</uid> <uid>787438161</uid> <uid>1014699981</uid> <uid>1035030036</uid> <uid>1176889834</uid> <uid>1290350373</uid> <uid>1482062872</uid></friends_get_response>

Not sure what is wrong with code but I do not get uids from resp object as it become null after this statement

FriendsGetResponse? resp = (FriendsGetResponse?)client.getResponsePOJO();

I appreciate any help.

Comment by maned.ali, Nov 12, 2008

is there a method that one can use to retrieve facebook's Live Feed?

Comment by slopixi, Nov 24, 2008

not in this api :/

Comment by slopixi, Nov 24, 2008

@ shalinjshah

i think your problem is that you are using xml return, but trying to get result as POJO - plain old java object. Its not same thing.

So change the way you access retrived data or change FBRest Client

If you use JSON client your method should work.

Comment by araichura, Nov 30, 2008

Hello Everyone,

I am new to facebook and new to java-api. I am devloping application for my company where we can push & pull all kinds of data (with user's permission), even when user is not online.

Can you anyone guide me where do I start from ? and it will be good if I can get some example documentation also.

Thanks in Advance.

Comment by araichura, Nov 30, 2008

Sorry I forgot to add in my previous query : This application will be outside the Facebook environment.

Comment by BeowulfEcgtheowing, Dec 01, 2008

I am having some issues with posting to template feeds. Here is the relavent bit of code:

	long templateBundleID = ###########L;
	
        try
        {
            FacebookJaxbRestClient client = facebookHelper.restClient();
            
            TemplateBundle bundle = ((JAXBElement<TemplateBundle>)client.feed_getRegisteredTemplateBundleByID(templateBundleID)).getValue();
            boolean result = client.feed_publishUserAction(bundle.getTemplateBundleId(), message.getParams(), null, null);
        }
        catch (Exception e)
        {
            log.error("Error while trying to post feed messages.", e);
        }

It contains superflouse code like getting the TemplateBundle? by ID when all I need from it is its ID, however this is usefule in showing that the template bundle I want is retrieved. (Which it is)

The message.getParams() returns a Map<String, String> with an entry for all the values in the template except {actor}, there is no use of the {target} and therefore no need to fill in target_ids.

The result of the feed_publishUserAction call results in true, (and deep down in the code its responce is 1 wrapped in a bunch of xml).

However the message never shows up any where in facebook. (Yes I checked things like makeing sure that I am accepting stores from the application)

Any help, insight, is the API broken, this implimentation of the API or am I missing something that is requried?

Comment by kevinrombe, Dec 05, 2008

Hi, is there a way for updating the status

Comment by araichura, Dec 13, 2008

Ca anyone please help me with my previous query.

Comment by slopixi, Dec 16, 2008

@ kevinrombe it's easy, use update_status from api, all you have to configure is permission, check REST doc on update status

Comment by CarmenDelessio, Dec 26, 2008

I have posted my examples at http://www.socialjava.com That might be helpful ... But I am in the process of moving these from 1.8 to 2.0 version.

Comment by CarmenDelessio, Jan 05, 2009

Random Friend -Sample Application with Source Code

  • Displays the profile image of one of your Friends
  • Shows the Random Friend on your profile
  • Shows how to create an application with Java and JSP - including updating the profile.
  • Random Friend Site uses Facebook Connect to display the friend and publish a story to your profile
Random Friend Application: http://apps.facebook.com/randomfriendapp/
Random Friend Site http://www.socialjava.com/random/connect.jsp
Source code: http://github.com/CarmenD/randomfriendfacebookapp/
Comment by rizkyz, Jan 13, 2009

when I try to make java desktop application (http://stud3.tuwien.ac.at/~e0525278/facebookapi_getfriends/) using facebook-java-api 1.8, this error occured :

Facebook returns error code 100

- v -> 1.0 - auth_token -> d1b8a5ba9ae6a0abc5677c798255a3cf - method -> facebook.auth.getSession - call_id -> 1231841816620 - api_key -> 72978d8b0618077229feea61ee431a17 - sig -> 6e0ea4d32226683d74534c4090803c61
com.facebook.api.FacebookException?: Invalid parameter
at com.facebook.api.FacebookRestClient?.callMethod(FacebookRestClient?.jav
a:828)
at com.facebook.api.FacebookRestClient?.callMethod(FacebookRestClient?.jav
a:606)
at com.facebook.api.FacebookRestClient?.auth_getSession(FacebookRestClien?
t.java:1891)
at FacebookGetFriends?.main(FacebookGetFriends?.java:36)

Comment by jlw253, Jan 14, 2009

Anyone have an example of sending a Facebook Request -- the kind that show up on your Facebook home page in the upper right-hand corner as "Requests"?

I have working code for inviting friends and those invitations come over as "Requests" but I want to be able to send requests from the server side on user / application events.

Does what I'm asking for make sense? Anyone have a code sample or the ability to point me in the right direction?

Thanks - jw

Comment by arun.shivaraman, Jan 15, 2009

Experts,

Any of you know how to read the error code after calling feed_publishUserAction on the api client?

I can see error code from the XML I get from client.getRawResponse(). But, I wanted to take some actions programmatically based on the status code from the api call.

Thanks Arun

Comment by arun.shivaraman, Jan 15, 2009

jlw253 : The requests you see in top right hand corner of home page are from "Invite Friends" functionality. For details read http://wiki.developers.facebook.com/index.php/Fb:request-form

Comment by shaheervu, Jan 30, 2009

hi everyone hru ...... ????

How i add event in facebook but using facebook api and desktop application ??

at com.google.code.facebookapi.FacebookJsonRestClient?.parseCallResult(FacebookJsonRestClient?.java:346) at com.google.code.facebookapi.ExtensibleClient?.callMethod(ExtensibleClient?.java:526) at com.google.code.facebookapi.ExtensibleClient?.callMethod(ExtensibleClient?.java:448) at com.google.code.facebookapi.ExtensibleClient?.fql_query(ExtensibleClient?.java:418) at ukdp.wl.facebook.FaceBookDAO.insertEvent(FaceBookDAO.java:137) at ukdp.wl.facebook.FaceBookMain?.main(FaceBookMain?.java:33)

Comment by shaheervu, Jan 30, 2009

com.google.code.facebookapi.FacebookException?: Creating and modifying events requires the extended permission create_event

Error come while i create events manually using facebook api 2.0.4 and java.

help me

thanks

Comment by auduwage, Feb 23, 2009

I was going over some examples and most of the examples are using FacebookRestClient but the latest api i downloaded doesn't have this class. Is it a deprecated class..? or instead of FacebookRestClient should i be using FacebookJsonRestClient or FacebookXmlRestClient?

Comment by nikola.m...@gmail.com, Feb 25, 2009

Is there a way to access user's abailibility for chat; for instance to find out if user is online or offline for chatting? I've searched a bit in the docs, but couldn't find anything.

Thanks in advance.

Comment by craigmit, Mar 06, 2009

This is what I did to get it all working:

FacebookWebappHelper<?> webClient = new FacebookWebappHelper<Object>(
				pReq, 
				pResp, 
				"API Key",
				"Secret Key",
				new FacebookJsonRestClient("API Key", "Secret Key"));
FacebookJsonRestClient facebookClient = (FacebookJsonRestClient)webClient.getFacebookRestClient();
Comment by pulkit00choudhary, Mar 18, 2009

can somebody help me on how to upload photo to facebook from my own application. please give an end to end example.

Comment by IsaacKEarl, Mar 21, 2009

I am trying to make a very simple java based desktop application that updates your facebook status.. I would really appreciate someone explaining or showing me how to get a user logged into facebook without opening up the browser to have them do it in facebook... All I need is real simple example, maybe how to Hard code in the credentials of the user logging in.

Thanks, isaac

Comment by carroll.joshk, Mar 23, 2009

what craig said worked for me after hours and hours.

Comment by giacomini.marco, Apr 01, 2009

Sorry but where can i find Facebook in lib ??? Facebook face = new Facebook(....) Facebook cannot be resolved to a type

Someone can help me ?

Comment by gaguilar.delgado, Apr 02, 2009

There is no Facebook you have to use one of the clients...

Comment by gaguilar.delgado, Apr 02, 2009

Hi, is there any realiable way to show friends of friends? Just 2 levels of friendships... I want to do a kind of map of friends...

Thank you

Comment by thalinfa, Apr 04, 2009

I am having trouble obtaining a sessionKey. If anyone has time, I would really appreciate it if you could help me out. The explanation of my problem is in the following url:

http://forum.developers.facebook.com/viewtopic.php?pid=136546#p136546

Comment by sirnicus, Apr 20, 2009

Why do you need the sessionKey? Just omit the code with it.

Comment by thaicl, Apr 20, 2009

Can anyone show me an example of how to use FQL to extract user data? Suppose I have the following code:

String query = "SELECT " +

"name, profile_url, timezone, birthday, sex, proxied_email " + "FROM user WHERE uid=" + user;
org.json.JSONArray resultArray = (org.json.JSONArray)facebook.fql_query(query); //print the result as an array servletOutput.println(resultArray);

How can I extract each element from the array?

Thanks

Comment by bhanupratapk, Apr 25, 2009

When I try to create a new event I get this error "Creating and modifying events requires the extended permission create_event ". Can some body help me on this.

Comment by andy.beier, Jun 09, 2009

Here is a full example on how to get the friends list and names using the 2.1.1 API:

try{

//This object should be cashed. Don't run "new FacebookXmlRestClient?("facebook", "facebook.secret");" every time. It is just here to show all dependencies. FacebookXmlRestClient? startSession = new FacebookXmlRestClient?("facebook", "facebook.secret");

FacebookJaxbRestClient? client = new FacebookJaxbRestClient?("facebook.api-key", "facebook.secret", startSession.getCacheSessionKey());
client.beginBatch(); client.users_getLoggedInUser(); client.friends_get();

List<? extends Object> batchResponse = client.executeBatch(false);
Long userId = (Long) batchResponse.get(0); FriendsGetResponse? friends = (FriendsGetResponse?)batchResponse.get(1); System.out.println("Friends: " + friends.toString());

Set<ProfileField> c = new HashSet?<ProfileField>();
c.add(ProfileField?.FIRST_NAME); c.add(ProfileField?.LAST_NAME);

System.out.println("client: " + client.users_getInfo(friends.getUid(), c));
UsersGetInfoResponse? ugir = (UsersGetInfoResponse?)client.users_getInfo(friends.getUid(), c); List<User> ul = ugir.getUser(); for(User u : ul){
System.out.println(u.getFirstName() + " " + u.getLastName());
}
}catch (Exception e){e.printStackTrace(); throw new RuntimeException?(e);}

Comment by s.santanu, Jun 16, 2009

Hello, I'm very new in facebook development arena. My question is whether it is possible to extarct the facebook user's ID from his/her login id (which is email id)? This is really urgent, please let me know , if possible. If this is possible, can cny one send me the some sample code/tutorials? Thanks Santanu

Comment by Randgalt, Jun 17, 2009

The example code above tries to store the IFacebookRestClient object in the Java session. My app server requires session stored objects to be Serializable. Is there any reason why IFacebookRestClient isn't?

Comment by amitverma6523, Jun 26, 2009

String loginPage = "http://www.facebook.com/login.php?api_key=" + appapikey + "&v=1.0&canvas=true";

String sessionKey=null;

sessionKey = req.getParameter(FacebookParam?.SESSION_KEY.toString());

// Session Key passed as request parameter
if (sessionKey==null) {
// If there is not session key, they user not logged in
System.out.println("session key not found"); servletOutput.println("session expired");
// Facebook Redirect to login page
res.sendRedirect(loginPage); //loginPage string defined earlier }

else{ user = req.getParameter("fb_sig_user");

// get user as a string. User info passed as request parameter
servletOutput.println("User is " + user);
// displays numeric value
servletOutput.println("<br>"); facebook = new FacebookJsonRestClient?(appapikey, appsecret,sessionKey);
// create Facebook Json Rest Client
servletOutput.println("Facebook Client created"); servletOutput.println("<br>");
// with Facebook client created, now Facebook API calls can be made // In this case, a call to FQL to get username
try{ String query = "SELECT name FROM user WHERE uid=" + user; org.json.JSONArray resultArray =(org.json.JSONArray)facebook.fql_query(query);

// query return an object. Casting it as a String

servletOutput.println("User Name is " + resultArray+ "<br>"); org.json.JSONArray friendsList = facebook.friends_get(); servletOutput.println("Users friends are" + friendsList); for (int i=0;i<=friendsList.length();i++){ String queryToGetFriendName = "SELECT name FROM user WHERE uid=" + friendsList.get(i);

org.json.JSONArray friendsListArray = (org.json.JSONArray)facebook.fql_query(queryToGetFriendName);

servletOutput.println("Friend Name is " + friendsListArray+ "<br>"); } } catch( FacebookException? ex ) { servletOutput.println(">Error: Couldn't talk to Facebook> " + ex ); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } servletOutput.close();

Comment by amitverma6523, Jun 26, 2009

the above provided code was used by me to fetch friends of logged in user.. hope this helps...

Comment by ngoanhtuan, Jun 26, 2009

I'm going to write an application to upload pictures from mobile. So can anyone help me figure out all the steps my application need to do

Can I login to facebook with user/pass the user has given before or I have to show login page for the user to login

thank you

Comment by oyvind.holmstad, Jul 02, 2009

Any of you geniuses might be able to answer this topic I wrote on the Facebook Developers Forum :)

http://forum.developers.facebook.com/viewtopic.php?id=36946

Comment by tediscript, Jul 04, 2009

is there any example for desktop application?

Comment by kniforesare, Jul 07, 2009

Hello, like ngoanhtuan, I'm going to write an application to upload pictures. Same question : Can I login to facebook with user/pass without showing login page?? Thx

Comment by dinesh.awa, Jul 16, 2009

No You can't without login u can't show picture

Comment by dinesh.awa, Jul 16, 2009

I am getting all data in my application but i required email because my application fully depend on email if any way to get email id then plz let me know .

I required any method in api there i can pass email id and get to userid if any method in application then please mail me Thanks "dinesh.awa@gmail.com"

Comment by russellsimpkins, Aug 12, 2009

Question,

I was only able to make this work in my java app by doing this:

FacebookWebappHelper?<Object> helper = FacebookWebappHelper?.newInstanceJson(request, response, api, secret); FacebookJsonRestClient? facebookClient = (FacebookJsonRestClient?) helper.getFacebookRestClient();

I tried putting my client object in the session, but if I attempt to use that client object, it fails to return results. The api suggests that FacebookWebappHelper? should be created with every request. Andy.beier suggested to store the client, but it isn't working for me.

Is this because of an api change?

Thanks,

Russ

Comment by eduardo.solanas, Aug 31, 2009

Hi I've managed to get the facebook user_id and stored it in my database. My problem is that i don't know how to publish in his wall without asking him to loggin, it should be easy or not? anyone can send me some easy example??

note.-My app is a web application

thanks, e_sola

Comment by yuan.w0811, Sep 22, 2009

hi eduardo.solanas I think you can ask user offline_data access permission, in that case, you can use API without ask user to login.

Comment by gauravc.sun, Oct 07, 2009

can anyone help me in importing

import static com.emobus.stuff.LoggerConstants.facebookUserId;
import static com.emobus.stuff.LoggerConstants.ipAddress;

i am not able to find out from where i can import these

Comment by snirco, Oct 08, 2009

Hello I tryed to Publishing a Templatized Feed as the abov example but I got exeption: This method can only be used to publish Mini-Feed stories to Facebook Pages. Its use for posting feed stories to user pages has been deprecated.null

Comment by peggy6668, Oct 08, 2009

Can anyone help me...I can't find out this import

import org.slf4j.Logger; import org.slf4j.LoggerFactory?; import org.slf4j.MDC;

Comment by arunpatil884, Oct 08, 2009

Re:peggy6668 Follow this link http://www.slf4j.org/download.html. download the required jar file.

And please help me out. I m not able to find the following imports.

import static com.emobus.stuff.LoggerConstants?.facebookUserId; import static com.emobus.stuff.LoggerConstants?.ipAddress;

Comment by jselvas, Oct 20, 2009

I've a problem with this code:

FacebookXmlRestClient? client = new FacebookXmlRestClient?(apiKey,
secretKey);
client.setIsDesktop(true);

String token = client.auth_createToken(); System.out.println("LOGIN - Authentication Token created upon login: " + token); HttpClientParams? params = new HttpClientParams?(); HttpState? initialState = new HttpState?(); http.setParams(params); http.setState(initialState); GetMethod? get = new GetMethod?("/login.php?api_key=" + apiKey
+ "&v=1.0&auth_token=" + token);
int getStatus = http.executeMethod(get); token = client.auth_createToken(); System.out.println("LOGIN - Http status returned when executing GET: "
+ getStatus);
PostMethod? post = new PostMethod?("/login.php?login_attempt=1"); post.addParameter("api_key", apiKey); post.addParameter("v", "1.0"); post.addParameter("auth_token", token); post.addParameter("email", "jselva@dtic.ua.es"); post.addParameter("pass", "dTic25"); // new value here (new change from facebook) // String newValue = getNonUserIdEnc(get); // post.addParameter("non_user_id_enc", newValue); int postStatus = http.executeMethod(post); System.out.println("LOGIN - Http status returned when executing POST: "
+ postStatus);
String sessionId = client.auth_getSession(token); System.out.println("Session key is " + sessionId);

// keep track of the logged in user id Long userId = client.users_getLoggedInUser(); System.out.println("Fetching friends for user " + userId);
// Get friends list client.friends_get();

And my problem is when i call client.friends_get();

The result is: com.google.code.facebookapi.FacebookException?: Incorrect signature

at com.google.code.facebookapi.FacebookXmlRestClientBase?.parseCallResult(FacebookXmlRestClientBase?.java:196) at com.google.code.facebookapi.FacebookXmlRestClientBase?.parseCallResult(FacebookXmlRestClientBase?.java:169) at com.google.code.facebookapi.FacebookXmlRestClient?.friends_get(FacebookXmlRestClient?.java:412) at es.ua.dtic.facebook.Sesion.prueba(Sesion.java:63) at es.ua.dtic.facebook.Sesion.main(Sesion.java:86)

I'm developing on windows.

Any Idea?

Comment by poubelledunet, Oct 21, 2009

Methods like "photos_get" don't work anymore because the album ids (aid)are now String like "100000455430721_27" and the facebook-java-api take a Long.

Comment by bpvse...@btdb.net, Oct 25, 2009

Anybody want to complete this example by revealing the source for the referenced package: com.emobus.stuff.LoggerConstants?? Several people have asked on here but I haven't yet seen an answer. Maybe some of your own code that you forgot to post with the example Dave? I am going to create a session context for these data, but am still curious. Thanks for the contribution!

Comment by tuanphan.dev, Oct 26, 2009

Hi all ! I want to code a Java Application to load this page "http://apps.facebook.com/friendsforsale/users/show/121461057" with a Username and Password of my FB account sothat i can use htmlparse to calculator something on this body text! Please show me the way to do that. Im sorry about my bad english !

Thanks in advance !

Comment by 12675...@qq.com, Oct 28, 2009

Anybody who could get me a example that use email/passwd to login in facebook

Comment by theunical, Nov 07, 2009

Thanks team for fixing up bugs and releasing the new version. We have created an application in java to publish in facebook http://blog.theunical.com/facebook-integration/facebook-java-api-example-to-publish-on-wall/. Also we posted image in facebook http://blog.theunical.com/facebook-integration/facebook-java-api-example-to-publish-on-wall/. Hope this examples helps for New guys.

Comment by pep.informatics, Nov 19, 2009

Some notes to the the given example.

1) The two imports:

import static com.emobus.stuff.LoggerConstants.facebookUserId;
import static com.emobus.stuff.LoggerConstants.ipAddress;

define only the string constants facebookUserId and facebookUserId.

I substituted them with:

        private String facebookUserId = "id";
	private String ipAddress = "ip";

2) Because of the instructions

		api_key = filterConfig.getServletContext().getInitParameter(
				"facebook_api_key");
		secret = filterConfig.getServletContext().getInitParameter(
				"facebook_secret");

the web.xml has to contain:

	<context-param>
		<param-name>facebook_api_key</param-name>
		<param-value>your_key_goes_here</param-value>
	</context-param>
	<context-param>
		<param-name>facebook_secret</param-name>
		<param-value>your_key_goes_here</param-value>
	</context-param>

where you have to substitute "your_key_goes_here" with the real values.

3) Since this class is a filter, the web.xml has to contain:

	<filter>
		<display-name>FacebookUserFilter</display-name>
		<filter-name>FacebookUserFilter</filter-name>
		<filter-class>test.FacebookUserFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>FacebookUserFilter</filter-name>
		<url-pattern>/test/*</url-pattern>
	</filter-mapping>

where "test" is the package of your servlets.

Comment by pep.informatics, Nov 19, 2009

If you want, you can use org.apache.log4j. instead of org.slf4j. with little changes, so it runs with Tomcat without any additional library (except facebook-java-api-xxxx). Here it is my complete code for filter and web.xml that also includes the things that I suggested in the previous post.

FacebookUserFilter?.java

package test;

//import static com.emobus.stuff.LoggerConstants.facebookUserId;
//import static com.emobus.stuff.LoggerConstants.ipAddress;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.slf4j.MDC;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.w3c.dom.Document;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookWebappHelper;
import com.google.code.facebookapi.FacebookXmlRestClient;
import com.google.code.facebookapi.IFacebookRestClient;

/**
 * The Facebook User Filter ensures that a Facebook client that pertains to the
 * logged in user is available in the session object named
 * "facebook.user.client".
 * 
 * The session ID is stored as "facebook.user.session". It's important to get
 * the session ID only when the application actually needs it. The user has to
 * authorise to give the application a session key.
 * 
 * @author Dave
 */
public class FacebookUserFilter implements Filter {

	private static final Logger logger = Logger
			.getLogger(FacebookUserFilter.class);

	private String api_key;
	private String secret;

	private String facebookUserId = "id";
	private String ipAddress = "ip";

	private static final String FACEBOOK_USER_CLIENT = "facebook.user.client";

	public void init(FilterConfig filterConfig) throws ServletException {
		logger.info("partito");
		api_key = filterConfig.getServletContext().getInitParameter(
				"facebook_api_key");
		secret = filterConfig.getServletContext().getInitParameter(
				"facebook_secret");
		if (api_key == null || secret == null) {
			throw new ServletException(
					"Cannot initialise Facebook User Filter because the "
							+ "facebook_api_key or facebook_secret context init "
							+ "params have not been set. Check that they're there "
							+ "in your servlet context descriptor.");
		} else {
			logger.info("Using facebook API key: " + api_key);
		}
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		try {
			MDC.put(ipAddress, req.getRemoteAddr());

			HttpServletRequest request = (HttpServletRequest) req;
			HttpServletResponse response = (HttpServletResponse) res;

			HttpSession session = request.getSession(true);
			IFacebookRestClient<Document> userClient = getUserClient(session);
			if (userClient == null) {
				logger
						.debug("User session doesn't have a Facebook API client setup yet. Creating one and storing it in the user's session.");
				userClient = new FacebookXmlRestClient(api_key, secret);
				session.setAttribute(FACEBOOK_USER_CLIENT, userClient);
			}

			logger
					.trace("Creating a FacebookWebappHelper, which copies fb_ request param data into the userClient");
			FacebookWebappHelper<Document> facebook = new FacebookWebappHelper<Document>(
					request, response, api_key, secret, userClient);
			String nextPage = request.getRequestURI();
			/* cut out the first /, the context path and the 2nd / */
			nextPage = nextPage.substring(nextPage.indexOf("/", 1) + 1);
			logger.trace(nextPage);
			boolean redirectOccurred = facebook.requireLogin(nextPage);
			if (redirectOccurred) {
				return;
			}
			redirectOccurred = facebook.requireFrame(nextPage);
			if (redirectOccurred) {
				return;
			}

			long facebookUserID;
			try {
				facebookUserID = userClient.users_getLoggedInUser();
			} catch (FacebookException ex) {
				response.sendError(
						HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
						"Error while fetching user's facebook ID");
				logger
						.error("Error while getting cached (supplied by request params) value "
								+ "of the user's facebook ID or while fetching it from the Facebook service "
								+ "if the cached value was not present for some reason. Cached value = {}"
								+ userClient.getCacheUserId());
				return;
			}

			MDC.put(facebookUserId, String.valueOf(facebookUserID));

			chain.doFilter(request, response);
		} finally {
			MDC.remove(ipAddress);
			MDC.remove(facebookUserId);
		}
	}

	public static FacebookXmlRestClient getUserClient(HttpSession session) {
		return (FacebookXmlRestClient) session
				.getAttribute(FACEBOOK_USER_CLIENT);
	}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>FacebookTest</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<context-param>
		<param-name>facebook_api_key</param-name>
		<param-value>xxxxxxx</param-value>
	</context-param>
	<context-param>
		<param-name>facebook_secret</param-name>
		<param-value>xxxxxx</param-value>
	</context-param>


	<servlet>
		<description></description>
		<display-name>TestServlet</display-name>
		<servlet-name>TestServlet</servlet-name>
		<servlet-class>test.TestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>TestServlet</servlet-name>
		<url-pattern>/TestServlet</url-pattern>
	</servlet-mapping>
	<filter>
		<display-name>FacebookUserFilter</display-name>
		<filter-name>FacebookUserFilter</filter-name>
		<filter-class>test.FacebookUserFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>FacebookUserFilter</filter-name>
		<url-pattern>/test/*</url-pattern>
	</filter-mapping>
</web-app>
Comment by Lydonchandra, Dec 01, 2009

Hi,

I am using this library in Google App Engine, and I got

Uncaught exception from servlet java.lang.RuntimeException?: java.io.NotSerializableException?: com.google.code.facebookapi.FacebookXmlRestClient?

when the code does if (userClient == null) {

userClient = new FacebookXmlRestClient?( api_key, secret); session.setAttribute(FACEBOOK_USER_CLIENT, userClient);
}

How do I resolve this error?

Please help and many thanks! :)

don

Comment by darioandrade, Dec 08, 2009

This client is not serializable, as it should be (to be session-bound). You can create a hashmap, indexed by some unique key (the session.getID for instance) and store the facebook client in this hashmap. Then you could implement HttpSessionListener? (and put it in web.xml as a session listener) to remove old expired facebook clients (when sessions expire).

Comment by jackiegleason, Dec 12 (5 days ago)

Can you please expand on this I am a little confused about what you mean can you post a snippet?

Comment by jackiegleason, Dec 12 (5 days ago)

And looking back it looks like this class should implement serializeable

com.google.code.facebookapi.ExtensibleClient?


Sign in to add a comment
Hosted by Google Code