Servlet Filter to run for every requestThis 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 FriendsYou select the FacebookXXXRestClient replacing XXX with either Json, Xml or Jaxb depending on how you want the results to be returned to you: - Json - Strings, primative types, JSONArray and JSONObject. This is what most users will need.
- Xml - Return a javax.xml.Document
- Jaxb - Return a Java Object generated using JAXB which referenced the Facebook .xsd schema.
FacebookJsonRestClient client = new FacebookJsonRestClient("apiKey", "secretKey", "sessionId");
JSONArray response = (JSONArray)client.friends_get();PROBABLY DEPRECATEDHeads 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 feedPlaying 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));
}
|
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
if ( !face.isLogin() )FacebookRestClient? client = face.get_api_client(); // if you get here you have
client.friends_get(); FriendsGetResponse? response = (FriendsGetResponse?)client.getResponsePOJO(); List<Long> friends = response.getUid();if ( !face.isLogin() )
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
@garth.newton: try with client.users_getInfo(friends, c) instead of client.users_getStandardInfo(friends, c).
Hope it helps.
Max
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
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.
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
Can someone please post basic end-end example of using this API?
Thanks Arun
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
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
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?
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.
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
Example on how to retreieve groups with the json client:
// Set this up in a filter og servlet:
FacebookWebappHelper?<Object> helper = FacebookWebappHelper?.newInstanceJson
helper.requireLogin(null); IFacebookRestClient<Object> facebook = helper.getFacebookRestClient();JSONArray groups = (JSONArray)facebook.groups_get(null, null);
JSONObject group = groups.optJSONObject(0); System.out.println(group.getString("name"));It would have been nice to avoid the pain of casting the result though;-)
Hi, I am facing issue while getting friends list of logged in user.
I am using spring mvc controller servlet to do this:
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 {
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.
is there a method that one can use to retrieve facebook's Live Feed?
not in this api :/
@ 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.
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.
Sorry I forgot to add in my previous query : This application will be outside the Facebook environment.
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?
Hi, is there a way for updating the status
Ca anyone please help me with my previous query.
@ kevinrombe it's easy, use update_status from api, all you have to configure is permission, check REST doc on update status
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.
Random Friend -Sample Application with Source Code
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
com.facebook.api.FacebookException?: Invalid parameter a:828) a:606) t.java:1891)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
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
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
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)
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
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?
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.
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();can somebody help me on how to upload photo to facebook from my own application. please give an end to end example.
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
what craig said worked for me after hours and hours.
Sorry but where can i find Facebook in lib ??? Facebook face = new Facebook(....) Facebook cannot be resolved to a type
Someone can help me ?
There is no Facebook you have to use one of the clients...
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
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
Why do you need the sessionKey? Just omit the code with it.
Can anyone show me an example of how to use FQL to extract user data? Suppose I have the following code:
String query = "SELECT " +
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
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.
Here is a full example on how to get the friends list and names using the 2.1.1 API:
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
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?
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());
if (sessionKey==null) { System.out.println("session key not found"); servletOutput.println("session expired"); res.sendRedirect(loginPage); //loginPage string defined earlier }else{ user = req.getParameter("fb_sig_user");
servletOutput.println("User is " + user); servletOutput.println("<br>"); facebook = new FacebookJsonRestClient?(appapikey, appsecret,sessionKey); servletOutput.println("Facebook Client created"); servletOutput.println("<br>"); try{ String query = "SELECT name FROM user WHERE uid=" + user; org.json.JSONArray resultArray =(org.json.JSONArray)facebook.fql_query(query);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();
the above provided code was used by me to fetch friends of logged in user.. hope this helps...
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
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
is there any example for desktop application?
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
No You can't without login u can't show picture
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"
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
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
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.
can anyone help me in importing
i am not able to find out from where i can import these
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
Can anyone help me...I can't find out this import
import org.slf4j.Logger; import org.slf4j.LoggerFactory?; import org.slf4j.MDC;
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;
I've a problem with this code:
And my problem is when i call client.friends_get();
The result is: com.google.code.facebookapi.FacebookException?: Incorrect signature
I'm developing on windows.
Any Idea?
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.
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!
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 !
Anybody who could get me a example that use email/passwd to login in facebook
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.
Some notes to the the given example.
1) The two imports:
define only the string constants facebookUserId and facebookUserId.
I substituted them with:
2) Because of the instructions
the web.xml has to contain:
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:
where "test" is the package of your servlets.
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
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) {
How do I resolve this error?
Please help and many thanks! :)
don
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).
Can you please expand on this I am a little confused about what you mean can you post a snippet?
And looking back it looks like this class should implement serializeable
com.google.code.facebookapi.ExtensibleClient?