Consuming Facebook Graph APIs to display Workplace Feed in SAP Portal
Introduction
This post explains how Facebook or Workplace group feed can be integrated and displayed in SAP Enterprise Portal using a Java class. It excludes the UI specific details and is left to the reader to implement it once the required feed data is available. Wherever possible, code snippets have been provided.
Pre-requisites
- To begin with, there must be a Facebook App created that has the Facebook (FB) or the Workplace group configured in it.
- The app should have read permissions to the required fields of the group feed that need to be displayed in SAP Portal.
- A generic access token with long term expiry is required. This token is used for making the FB Graph API calls to fetch the group feed data.
Details
Step 1
As a first step, it is necessary to retrieve the FB group data in raw format. FB’s Graph API provides this in JSON format. In the Graph API explorer, one can construct the required query by choosing the different fields. It is necessary that the FB app grants permissions to read these fields. Typically, the query might look like this as shown in the below code snippet:
String strFB_graph = "https://graph.facebook.com/";
String strAccess_key = "&access_token=<your_app_access_token>";
String strID = "<fb_group_id>";
String strQueryType = "/feed";
String strFields = "?fields=message,id,full_picture,updated_time,from,created_time,likes.limit(0).summary(total_count),comments.limit(0).summary(total_count)&limit=3";
String strURL = strFB_graph + strID + strQueryType + strFields + strAccess_key;
The above query retrieves the recent 3 posts from the group feed with the following fields in JSON format:
- post message
- post ID
- post image in full
- last updated time
- post creator
- created time
- number of likes
- number of comments
Step 2
In the next step, a ‘GET’ HTTP call is made to obtain the JSON data. Below is the self-explanatory code snippet:
//Parse URL into HttpURLConnection in order to open the connection in order to get the JSON data
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//Set the request to GET or POST as per the requirements
conn.setRequestMethod("GET");
//Use the connect method to create the connection bridge
conn.connect();
//Get the response status of the Rest API
int responsecode = conn.getResponseCode();
System.out.println("Response code is: " +responsecode);
//Iterating condition to if response code is not 200 then throw a runtime exception
//else continue the actual process of getting the JSON data
if(responsecode != 200)
throw new RuntimeException("HttpResponseCode: " +responsecode);
else
{
//Scanner functionality will read the JSON data from the stream
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+=sc.nextLine();
}
System.out.println("\nJSON Response in String format");
System.out.println(inline);
//Close the stream when reading the data has been finished
sc.close();
}
Step 3
In this last step, the JSON data is parsed to obtain values for all the fields in the data structure.
//JSONParser reads the data from string object and break each data into key value pairs
JSONParser parse = new JSONParser();
//Type caste the parsed json data in json object
JSONObject jsonobjData = (JSONObject)parse.parse(inline);
//Store the JSON object in JSON array as objects (For level 1 array element i.e Results)
JSONArray jsonarrData = (JSONArray) jobj.get("data");
JSONObject jsonobjFeed;
JSONObject jsonobjFrom;
JSONObject jsonobjLikes;
JSONObject jsonobjLikesCount;
JSONObject jsonobjFromPic;
JSONObject jsonobjFromPicData;
String strArrFromID;
//Get data for Results array
for(int i=0;i<jsonarrData.size();i++)
{
//Store the JSON objects in an array
//Get the index of the JSON object and print the values as per the index
jsonobjFeed = (JSONObject)jsonarrData.get(i);
jsonobjFrom = (JSONObject)jsonobjFeed.get("from");
jsonobjLikes = (JSONObject)jsonobjFeed.get("likes");
jsonobjLikesCount = (JSONObject)jsonobjLikes.get("summary");
System.out.println("Feed item " + i);
System.out.println("\nPost : " +jsonobjFeed.get("message"));
System.out.println("\nAttachment: " + jsonobjFeed.get("full_picture"));
System.out.println("\nTime: " + jsonobjFeed.get("created_time"));
System.out.println("\nLikes Count: " + jsonobjLikesCount.get("total_count"));
// System.out.println("\nComments Count: " + jsonobjCommentsCount.get("total_count"));
System.out.println("\nFrom: " + jsonobjFrom.get("name"));
}
Step 4
As the final step, the HTTP connection created in earlier step is closed.
//Disconnect the HttpURLConnection stream
conn.disconnect();
Conclusion
There can be multiple ways to consume FB’s Graph API and integrate within SAP Portal. This post described one of them. Hope this blog can act as a starting point if there arises a similar requirement for you to implement. Please leave comment below to provide your feedback or if you require more information.
Finally, below is the complete code snippet of a standalone java class file that can be tried out to test one’s own FB graph query.
package com.sample;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class WPFeed {
public static void main(String [] args)
{
//inline will store the JSON data streamed in string format
String inline = "";
String strFB_graph = "https://graph.facebook.com/";
String strAccess_key = "&access_token=<your_app_access_token>";
String strID = "<your_group_id>";
String strQueryType = "/feed";
String strFields = "?fields=message,id,full_picture,updated_time,from,created_time,likes.limit(0).summary(total_count),comments.limit(0).summary(total_count)&limit=3";
String strURL = strFB_graph + strID + strQueryType + strFields + strAccess_key;
System.out.println(strURL);
try
{
URL url = new URL(strURL);
//Parse URL into HttpURLConnection in order to open the connection in order to get the JSON data
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//Set the request to GET or POST as per the requirements
conn.setRequestMethod("GET");
//Use the connect method to create the connection bridge
conn.connect();
//Get the response status of the Rest API
int responsecode = conn.getResponseCode();
System.out.println("Response code is: " +responsecode);
Scanner sc;
//Iterating condition to if response code is not 200 then throw a runtime exception
//else continue the actual process of getting the JSON data
if(responsecode != 200)
throw new RuntimeException("HttpResponseCode: " +responsecode);
else
{
//Scanner functionality will read the JSON data from the stream
sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+=sc.nextLine();
}
// System.out.println("\nJSON Response in String format");
// System.out.println(inline);
//Close the stream when reading the data has been finished
sc.close();
}
//JSONParser reads the data from string object and break each data into key value pairs
JSONParser parse = new JSONParser();
//Type caste the parsed json data in json object
// JSONObject jsonobjData = (JSONObject)parse.parse(inline);
JSONObject jsonobjData = (JSONObject)parse.parse(inline);
//Store the JSON object in JSON array as objects (For level 1 array element i.e Results)
JSONArray jsonarrData = (JSONArray) jsonobjData.get("data");
JSONObject jsonobjFeed;
JSONObject jsonobjFrom;
JSONObject jsonobjLikes;
JSONObject jsonobjLikesCount;
JSONObject jsonobjFromPic;
JSONObject jsonobjFromPicData;
String strArrFromID;
//Get data for Results array
for(int i=0;i<jsonarrData.size();i++)
{
//Store the JSON objects in an array
//Get the index of the JSON object and print the values as per the index
jsonobjFeed = (JSONObject)jsonarrData.get(i);
jsonobjFrom = (JSONObject)jsonobjFeed.get("from");
jsonobjLikes = (JSONObject)jsonobjFeed.get("likes");
jsonobjLikesCount = (JSONObject)jsonobjLikes.get("summary");
System.out.println("Feed item " + i);
System.out.println("\nPost : " +jsonobjFeed.get("message"));
System.out.println("\nAttachment: " + jsonobjFeed.get("full_picture"));
System.out.println("\nTime: " + jsonobjFeed.get("created_time"));
System.out.println("\nLikes Count: " + jsonobjLikesCount.get("total_count"));
// System.out.println("\nComments Count: " + jsonobjCommentsCount.get("total_count"));
System.out.println("\nFrom: " + jsonobjFrom.get("name"));
strArrFromID = jsonobjFrom.get("id").toString();
strFields = "?fields=picture";
strURL = strFB_graph + strArrFromID + strFields + strAccess_key;
url = new URL(strURL);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
responsecode = conn.getResponseCode();
System.out.println("strURL is: " +strURL);
System.out.println("Response code is: " +responsecode);
if(responsecode != 200)
throw new RuntimeException("HttpResponseCode: " +responsecode);
else
{
//Scanner functionality will read the JSON data from the stream
sc = new Scanner(url.openStream());
inline = "";
while(sc.hasNext())
{
inline+=sc.nextLine();
}
System.out.println("\nJSON Response in String format");
System.out.println(inline);
//Close the stream when reading the data has been finished
sc.close();
}
jsonobjFromPic = (JSONObject)parse.parse(inline);
jsonobjFromPicData = (JSONObject)jsonobjFromPic.get("picture");
jsonobjFromPicData = (JSONObject)jsonobjFromPicData.get("data");
if(null!=jsonobjFromPicData.get("url"))
System.out.println("\nFromImageSrc: " + jsonobjFromPicData.get("url"));
}
//Disconnect the HttpURLConnection stream
conn.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I am trying to get the "from" field using an access token created by the administrator of the page, but the graph API does not allow it. It only returns the "from" field when the author is the same one that was used to generate the token. I am using an app with permissions to obtain information from public pages and that is already validated by Facebook.
How did you do it?
Thanks.
Hi Mauricio,
Regret for the late reply to your comment as notifications were off.
For the query mentioned, I was provided with a generic access token at App level.
So, for the FB page, the admin should create FB app for which a general access token can be generated. While I was not involved with this particular action, I know this from Facebook help documentation.
You may want to explore FB graph API help documentation related to access tokens.
Hope this answers your query.
Cheers,
Kapil.