package source; import javax.servlet.http.*; import java.io.IOException; import javax.servlet.*; import java.io.PrintWriter; import com.facebook.api.*; public class SocialJavaAPIIntroApp extends HttpServlet { //Application API Key and application secret from creating app in FB String appapikey = new String("00b0049fc7cf0d1e4a4ba2ea3e55b269"); String appsecret = new String("8ad-secret key goes here-"); //Facebook loginPage to this application. Parameter canvas=true shows the result in Facebook canvas String loginPage = "http://www.facebook.com/login.php?api_key="+"00b0049fc7cf0d1e4a4ba2ea3e55b269"+"&v=1.0&canvas=true"; FacebookJsonRestClient facebook; // the facebook client, talks to REST Server PrintWriter servletOutput; // output of servlet. HTML or FBML out public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException{ servletOutput = res.getWriter(); // response is sent to ServletOutput res.setContentType( "text/html" ); servletOutput.println("This is the doGet method"); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { servletOutput = res.getWriter(); // response is sent to ServletOutput res.setContentType( "text/html" ); servletOutput.println("This is the doPost method"); servletOutput.println("
"); String user =null; 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 servletOutput.println(""); // Facebook Redirect to login page } 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("
"); facebook = new FacebookJsonRestClient(appapikey, appsecret,sessionKey); // create Facebook Json Rest Client servletOutput.println("Facebook Client created"); servletOutput.println("
"); // 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); } catch( FacebookException ex ) { servletOutput.println(">Error: Couldn't talk to Facebook> " + ex ); } } //else user is logged in servletOutput.close(); } // end doPost() }