Facebook Connect implementation using OAuth in java

facbook connect using appId



package com.apalya.action;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.codehaus.jettison.json.JSONObject;

import com.apalya.util.ApalyaProperties;
import com.visural.common.IOUtil;
import com.visural.common.StringUtil;

/**
 * 
 * @author Ravi
 * 
 */
public class Facebook extends BaseAction {

 /**
  * Register your web application here https://developers.facebook.com/apps
  * to get below credential.
  */
 private static final String api_key = 1608443106749145;
 private static final String secret = c21bf0af0d9479e8582e46ed36fe114av;
 private static final String client_id = 1608443106749145;

 /**
  * set this to your servlet URL for the authentication servlet/filter
  */
 private static final String redirect_uri = "http://your_application_url/redirect_action_to_call_method";

 /**
  * set this to the list of extended permissions you want
  */
 private static final String[] perms = new String[] { "publish_stream",
   "email" };

 public static String getLoginRedirectURL() {

  return "https://graph.facebook.com/oauth/authorize?client_id="
    + client_id + "&display=page&redirect_uri=" + redirect_uri
    + "&scope=" + StringUtil.delimitObjectsToString(",", perms);
 }

 public static String getAuthURL(String authCode) {
  return "https://graph.facebook.com/oauth/access_token?client_id="
    + client_id + "&redirect_uri=" + redirect_uri
    + "&client_secret=" + secret + "&code=" + authCode;
 }

 /**
  * Redirect url method which handle the facebook request.
  * 
  * @return success when the user successfully authenticated by facebook
  */
 public String getFbauth() {
  String code = getServletRequest().getParameter("code");
  if (StringUtil.isNotBlankStr(code)) {
   try {
    String authURL = Facebook.getAuthURL(getServletRequest()
      .getParameter("code"));
    URL url = new URL(authURL);
    String result = readURL(url);
    String accessToken = null;
    Integer expires = null;
    String[] pairs = result.split("&");
    for (String pair : pairs) {
     String[] kv = pair.split("=");
     if (kv.length != 2) {
      // log.error("Unexpected auth response");
     }
     if (kv[0].equals("access_token")) {
      accessToken = kv[1];
     }
     if (kv[0].equals("expires")) {
      expires = Integer.valueOf(kv[1]);
     }
    }
    if (accessToken != null && expires != null) {
     try {
      authFacebookLogin(accessToken, expires);
     } catch (Exception e) {
      // log.error("Auth Facebook Login failed",e);
      return "success";
     }
    } else {
     // log.error("Access token and expires not found");
    }
   } catch (IOException e) {
    // log.error("Access token and expires not found",e);
    return "success";
   }
  }
  return "success";

 }

 /**
  * After successfully login facebook return the json response object with
  * loggedin user details.
  * 
  * @param accessToken
  * @param expires
  */
 public void authFacebookLogin(String accessToken, int expires) {
  String userName = null;
  try {
   JSONObject resp = new JSONObject(
     IOUtil.urlToString(new URL(
       "https://graph.facebook.com/me?access_token="
         + accessToken)));
   // get user details and save in data base as per your requirement.
  } catch (Throwable ex) {
   // handle the exception
  } finally {
   getServletRequest().getSession().setAttribute("userName", userName);
   getServletRequest().getSession().setAttribute("fbAccessToken",accessToken);
  }
 }

 private String readURL(URL url) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  InputStream is = url.openStream();
  int r;
  while ((r = is.read()) != -1) {
   baos.write(r);
  }
  return new String(baos.toByteArray());
 }

 public static String getAPIKey() {
  return api_key;
 }

 public static String getSecret() {
  return secret;
 }
}

One thought on “Facebook Connect implementation using OAuth in java

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.