CS6320:  SW Engineering of Web Based Systems

 

Example of Java Servlet Web App Facebook App does Authentication followed by Simple Graph API query  and HAS LINK FOR INVITEon user
 
This uses previous Java based Authentication code -- read there for details of Authentication


RESULTS
first UI

RESULTS OF CLICKING ON INVITE LINK --- will send request to users selected  AND THEN GO BACK TO 1st Interface

invite link goes to multi-friend selector

Servlet class -- invoked by Facebook mapped currently to

       http://puzzle.sci.csueastbay.edu:8080/grewe_FacebookSimpleApp/grewe_FacebookSimpleApp2/
package grewe.FacebookAuthentication;
 import java.io.IOException;
 import javax.servlet.ServletException;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.*;
 import java.net.URL;
 import java.net.URLConnection;
 import java.net.URLEncoder;
import javax.servlet.RequestDispatcher;
/** * Servlet implementation class FacebookSimpleApp */ @WebServlet(name="FacebookSimpleApp" ,urlPatterns={"/grewe_FacebookSimpleApp2/","/FacebookSimpleApp"}) public class FacebookSimpleApp extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FacebookSimpleApp() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // NOTE: REQUEST (INVITE) CALL CALLBACK is doGet ---the request to send Invite (REQUEST) below in doPost // will do a GET call back to the deployed webapp real address http://puzzle* so we have to redirect it to the apps.facebook // which will call the doPost method of this servlet passing again signed_request paramter // The callback to doGet does not include this information and the callback to http://puzzle* takes you // outside the facebook wrapper so must forward it to the https://apps.facebook.com/apid/ url. // You can check the results of whether or not the social call was successful here -- see Social data api to see what returned to callback response.sendRedirect("https://apps.facebook.com/296187843796738/"); }
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // AUTHENTICATION CODE try{ String signedRequest = (String) request.getParameter("signed_request"); //if authenticated this will be parameter sent to you from Facebook //create instance of FacebookSignedRequest based on signedRequest parameter retrieved above // note even if not authenticated you still get a signedRequest but, the oauth parameter will not be set FacebookSignedRequest facebookSignedRequest = FacebookAuthService.getFacebookSignedRequest(signedRequest); PrintWriter writer = response.getWriter(); //if the signedRequest was null, no authentication then the called to getOauth_token() will be null // redirect to authentication URL if (facebookSignedRequest.getOauth_token() == null) { response.setContentType("text/html"); writer.print("<script> top.location.href='" + FacebookAuthService.getAuthURL() + "'</script>"); writer.close(); } else { //we are authenticated at this point and going to forward the accessToken to your business logic Servlet/JSP request.setAttribute("accessToken", facebookSignedRequest.getOauth_token());


//Application CODE --- THIS IS WHERE YOUR APPLICATION CODE GOES response.setContentType("text/html"); writer.println("<body bgcolor=\"#ccccff\">"); //CODE DISPLAYS USER ID writer.print("Welcome user ME -- " + facebookSignedRequest.getUser_id() + "<br>"); //CODE FOR LINK TO INVITE -- style the link as you want and fit it in your interface as you want //going to create link that uses Facebook request dialog box to ask users to invite their friends to the app //which will pop-up a Facebook request dialog box asking for which friends...will return here String mess = "Come%20use%20" + FacebookAuthService.getAppName() + "%20with%20me!"; //Note- the callbacks from this apprequests url is the http://puzzle* the actual webapp location // if you put https://apps.facebook.com/appid/ you get error message saying that this url not owned by app // this http://puzzl* we are supplying will call back to THIS servelet and is a GET request (calls doGet) String s; s = "http://www.facebook.com/dialog/apprequests?app_id=" + FacebookAuthService.getAPIId() + "&message="+ mess +"&redirect_uri=" + FacebookAuthService.getCanvasURI(); writer.println("folloing links to " + s + "<br><br>"); writer.println("<a target=\"_top\" href=\"" + s +"\">" + "Invite Your Friends --</a> <br>"); writer.println("<br><hr>"); // This next link will only allow friends that do not have app installed yet s = "http://www.facebook.com/dialog/apprequests?app_id=" + FacebookAuthService.getAPIId() + "&message=" + mess + "&filters=['app_non_users']&redirect_uri=" + FacebookAuthService.getCanvasURI(); writer.println("folloing links to " + s + "<br><br>"); writer.println("<a target=\"_top\" href=\"" + s +"\">" + "Invite Your Friends --not having app installed </a> <br>"); writer.println("<br><hr>"); //CODE TO GET SOCIAL DATA -- you will need to parse the results of reading in the lines or like in Authentication use Jackson //makes a request to the graph URL and displays output and get the JSON back --you need to parse it s= "https://graph.facebook.com/me?access_token=" + facebookSignedRequest.getOauth_token(); writer.println(s); writer.println("<br><br>Graph on me output = " + "<br>"); InputStream fileSource = new URL(s).openStream(); URL u = new URL(s); URLConnection uc = u.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( uc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) writer.println(inputLine); in.close(); writer.println("END Graph output " + "<br><br>"); //POSSIBLE alternative is to forward on the request to another servlet/JSP for completion // be careful about where you place these jsps/servlets --see facebook restrictions about forwarding /* RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/figure_out_path"); //you will change the path to map to business logic Servlet/JSP s = requestDispatcher.toString(); writer.println(s + " <br><br>"); s = getServletContext().toString(); writer.println(s + " <br>"); s = requestDispatcher.FORWARD_REQUEST_URI; writer.println("forward uri " + s + " <br>"); s = requestDispatcher.FORWARD_SERVLET_PATH; writer.println("forward servlet path is " + s + "<br>"); requestDispatcher.forward(request, response); */ } }catch(Exception e){} }
}
 
FacebookAuthService.java (class from authentication)   change things in green
 
package grewe.FacebookAuthentication;
import  org.apache.commons.lang3.StringUtils;
         import org.apache.commons.codec.binary.Base64;
         import com.fasterxml.jackson.databind.ObjectMapper;
       
public class FacebookAuthService {
         private static final String apiKey = "29618XXXXXX" //you will change this
         private static final String appSecret = "875faXXXXX8";  //you will change this
         private static final String appId = "296XXXXXXXXX8";  //you will change this
         private static final String redirect_uri = "http://puzzle.sci.csueastbay.edu:8080/grewe_FacebookSimpleApp/grewe_FacebookSimpleApp2/";  //you will change this
        
         private static final String apps_uri = "https://apps.facebook.com/296187843796738/";  //you will change this
         private static final String canvas_uri = "http://puzzle.sci.csueastbay.edu:8080/grewe_FacebookSimpleApp/grewe_FacebookSimpleApp2/";  //you will change this
         private static final String appName = "Buzz";
         private static final String[] perms = new String[] {"publish_stream", "email"};
         // private static final String[] perms = new String[] { "email"};
       
         public static String getAPIKey() {
         return apiKey;
         }
         public static String getSecret() {
         return appSecret;
         }
   
         public static String getAPIId() {
         return appId;
         }
   
         public static String getRedirectURI() {
         return redirect_uri;
         }
   
         public static String getAppsURI() {
         return apps_uri;
         }
   
         public static String getCanvasURI() {
         return canvas_uri;
         }
         public static String getAppName() {
         return appName;
         }
         public static String getLoginRedirectURL() {
         return "https://graph.facebook.com/oauth/authorize?client_id=" + appId
         + "&display=page&redirect_uri=" + redirect_uri + "&scope=" + StringUtils.join(perms,',');
         }
         public static String getAuthURL(String authCode) {
         return "https://graph.facebook.com/oauth/access_token?client_id="
         + appId + "&redirect_uri=" + redirect_uri + "&client_secret="
         + appSecret + "&code=" + authCode;
         }
         public static String getAuthURL() {
         return "https://www.facebook.com/dialog/oauth?client_id="
         + appId + "&redirect_uri=" + redirect_uri + "&scope="
         + StringUtils.join(perms,',');
   
         }
       
         //this is the method that creates instance of FacebookSignedRequest using returned Facebook signed_request info
         public static FacebookSignedRequest getFacebookSignedRequest(String signedRequest) throws Exception{
 //parst the json string returned from Authentication and grab the oauth token
         String payLoad = signedRequest.split("[.]", 2)[1];
         payLoad = payLoad.replace("-", "+").replace("_", "/").trim();
 String jsonString = new String(Base64.decodeBase64(payLoad));
 //this maps the returned response from that has the jsonString as the signed_request returned from Facebook
         //to an instance of the FacebookSignedRequest class.
         // uses 3rd party package called Jackson to do mapping of JSON string to an object.
         return new ObjectMapper().readValue(jsonString, FacebookSignedRequest.class);
         }
  }

 

 

 



FacebookAuthentication.java (again class from previous Authentication example used here)

package grewe.FacebookAuthentication;
             
public class FacebookSignedRequest {
               private String algorithm;
               private Long expires;
               private Long issued_at;
               private String oauth_token;
               private Long user_id;
               private FacebookSignedRequestUser user;
 public String getAlgorithm() {
               return algorithm;
               }
 public void setAlgorithm(String algorithm) {
               this.algorithm = algorithm;
               }
 public Long getExpires() {
               return expires;
               }
 public void setExpires(Long expires) {
               this.expires = expires;
               }
 public Long getIssued_at() {
               return issued_at;
               }
 public void setIssued_at(Long issued_at) {
               this.issued_at = issued_at;
               }
 public String getOauth_token() {
               return oauth_token;
               }
 public void setOauth_token(String oauth_token) {
               this.oauth_token = oauth_token;
               }
 public Long getUser_id() {
               return user_id;
               }
 public void setUser_id(Long user_id) {
               this.user_id = user_id;
               }
 public FacebookSignedRequestUser getUser() {
               return user;
               }
 public void setUser(FacebookSignedRequestUser user) {
               this.user = user;
               }
 //inner class used to represent user information
               public static class FacebookSignedRequestUser {
               private String country;
               private String locale;
               private FacebookSignedRequestUserAge age;
 public String getCountry() {
               return country;
               }
 public void setCountry(String country) {
               this.country = country;
               }
 public String getLocale() {
               return locale;
               }
 public void setLocale(String locale) {
               this.locale = locale;
               }
 public FacebookSignedRequestUserAge getAge() {
               return age;
               }
 public void setAge(FacebookSignedRequestUserAge age) {
               this.age = age;
               }
             
 
               public static class FacebookSignedRequestUserAge{
               private int min;
               private int max;
             
 public int getMin() {
               return min;
               }
             
 public void setMin(int min) {
               this.min = min;
               }
             
 public int getMax() {
               return max;
               }
             
 public void setMax(int max) {
               this.max = max;
               }
               }
               }
               }
 
© Lynne Grewe