In the modern era, web sites have become an integral part of any business—big and small. The presence of a business on the web is not necessarily enough to reach a global mass audience. Social media plays a significant role in reaching a wider audience as it has a cascading and concurrent effect. Social networking and media sites themselves are also interested in integration and communication with other web sites, exposing their APIs and allowing web sites to communicate and integrate with them. Facebook provides convenient APIs (known as Graph API) for this purpose. The Graph API is very powerful and flexible. It exposes all necessary features (known as interfaces) required for integration.
Facebook Application Model
Before going into the actual implementation, let’s understand the Facebook application model. Facebook opens its platform to developers using REST web services. As a developer, you are free to use the APIs of your choice to integrate Facebook features in your application. You are also free to use the technology of your choice. Facebook uses a proxy server model as a main integration point. The Facebook proxy server follows the following steps:
- The web application will reside in your web/application server and you need to register the base URL in a Facebook account.
- When the application is visited in Facebook, it will call the registered URL on the application server.
- The application will call necessary Facebook APIs to get the relevant information.
- Your application uses its own database data and Facebook data and render it
- After this Facebook returns your application’s output to the user
How to Get Facebook Libraries
Before we integrate Facebook with your Java application we need some third party libraries. These third party libraries will help you with integration and communication with Facebook (actually accessing Facebook application installed in their server). Different independent groups of Java and open source developers have made efficient Facebook libraries for integration purpose.
The three JARs above are not required if you are using Java SE 6 or later.
After downloading these JARs, you need to incorporate them in your web or stand alone application. These JARs are made to provide API access to the client application for different purpose.
The following example will show the integration part:
Listing 1: Sample Java code for Facebook integration
package com.home.social;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import net.sf.json.JSONObject;import net.sf.json.JsonConfig;import Facebook4j.Facebook;import Facebook4j.FacebookException;import Facebook4j.FacebookFactory;import Facebook4j.Post;import Facebook4j.ResponseList;import Facebook4j.conf.Configuration;import Facebook4j.conf.ConfigurationBuilder;public class FacebookIntegration { public static void main(String[] args) throws FacebookException { // Create conf builder and set authorization and access keys ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setDebugEnabled(true); configurationBuilder.setOAuthAppId("xxxx"); configurationBuilder.setOAuthAppSecret("xxxxx"); configurationBuilder.setOAuthAccessToken("xxxx"); configurationBuilder .setOAuthPermissions("email, publish_stream, id, name, first_name, last_name, read_stream , generic"); configurationBuilder.setUseSSL(true); configurationBuilder.setJSONStoreEnabled(true); // Create configuration and get Facebook instance Configuration configuration = configurationBuilder.build(); FacebookFactory ff = new FacebookFactory(configuration); Facebook Facebook = ff.getInstance(); try { // Set search string and get results String searchPost = "MACDonaldsIndia"; Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "dd_MM_yyyy_hh_mm"); String fileName = "D:\FacebookConfigFolder\File\" + searchPost + "_" + simpleDateFormat.format(date) + ".txt"; String results = getFacebookPostes(Facebook, searchPost); File file = new File(fileName); if (!file.exists()) { file.createNewFile(); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(results); bw.close(); System.out.println("Completed"); } } catch (IOException e) { e.printStackTrace(); } } // This method is used to get Facebook posts based on the search string set // above public static String getFacebookPostes(Facebook Facebook, String searchPost) throws FacebookException { String searchResult = "Item : " + searchPost + "
"; StringBuffer searchMessage = new StringBuffer(); ResponseList results = Facebook.getPosts(searchPost); for (Post post : results) { System.out.println(post.getMessage()); searchMessage.append(post.getMessage() + "
"); for (int j = 0; j < post.getComments().size(); j++) { searchMessage.append(post.getComments().get(j).getFrom() .getName() + ", "); searchMessage.append(post.getComments().get(j).getMessage() + ", "); searchMessage.append(post.getComments().get(j).getCreatedTime() + ", "); searchMessage.append(post.getComments().get(j).getLikeCount() + "
"); } } String feedString = getFacebookFeed(Facebook, searchPost); searchResult = searchResult + searchMessage.toString(); searchResult = searchResult + feedString; return searchResult; } // This method is used to get Facebook feeds based on the search string set // above public static String getFacebookFeed(Facebook Facebook, String searchPost) throws FacebookException { String searchResult = ""; StringBuffer searchMessage = new StringBuffer(); ResponseList results = Facebook.getFeed(searchPost); for (Post post : results) { System.out.println(post.getMessage()); searchMessage.append(post.getFrom().getName() + ", "); searchMessage.append(post.getMessage() + ", "); searchMessage.append(post.getCreatedTime() + "
"); } searchResult = searchResult + searchMessage.toString(); return searchResult; } // This method is used to create JSON object from data string public static String stringToJson(String data) { JsonConfig cfg = new JsonConfig(); try { JSONObject jsonObject = JSONObject.fromObject(data, cfg); System.out.println("JSON = " + jsonObject.toString()); } catch (Exception e) { e.printStackTrace(); } return "JSON Created"; }}
Integration with Twitter
In order to integrate your application with Twitter, we need to use the library – Twitter4j. This is a well documented library that helps any Java developer to integrate his/her application with Twitter. As a developer you need to follow certain steps:
- Send a request to Twitter asking for a token. This request should carry both a consumer key and a secret key.
- Store the response received from Twitter.
- Once the response is received, the authentication URL is extracted from the response.
- The user then needs to be redirected to the authentication URL, so that he can sign in.
- User signs in and gets a Personal Identification Number or PIN.
- User then enters PIN in the application.
- Once the PIN is entered the application should ask Twitter for a security token, providing consumer parameters as above as well as the previously stored request token and the PIN.
- Once the token is received, every request going to Twitter should have this token along with the PIN
Listing 2: Sample Java code for Twitter integration
package com.home.social;import java.io.BufferedWriter;import java.io.FileWriter;import java.util.List;import Twitter4j.Query;import Twitter4j.QueryResult;import Twitter4j.Status;import Twitter4j.Twitter;import Twitter4j.TwitterFactory;import Twitter4j.conf.ConfigurationBuilder;public class TwitterIntegration { public static void main(String[] args) throws Exception{ // Create configuration builder and set key, token etc ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey("xxx"); cb.setOAuthConsumerSecret("xxxx"); cb.setOAuthAccessToken("xxxxx"); cb.setOAuthAccessTokenSecret("xxxx"); // Create Twitter instance Twitter Twitter = new TwitterFactory(cb.build()).getInstance(); // Create file writer and buffer writer FileWriter fstream = new FileWriter("Twitterstream.txt",true); BufferedWriter out = new BufferedWriter(fstream); // Create Query object and set search string Query query = new Query(""); query.setQuery("#USAirways"); // Get query result QueryResult qr = Twitter.search(query); // Get tweets and write in the file while(qr.hasNext()){ qr.nextQuery(); List tweets = qr.getTweets(); for (Status t: tweets){ System.out.println(t.getId() + " - " + t.getCreatedAt() + ": " + t.getText()); out.write("
"+t.getId()+","); out.write(" "+t.getText()+","); out.write(" "+t.getUser()+","); } } try{ Thread.sleep(1000*60*15); }catch(Exception e) {}}}
Conclusion
There are many social networking web sites available–out of these Facebook and Twitter are the most commonly used. Java provides libraries to easily integrate your applications with these web sites. Social media integration is a new dimension in the developer’s world and you should explore it as much as possible.
About the Author
Kaushik Pal is a technical architect with 15 years of experience in enterprise application and product development. He has expertise in web technologies, architecture/design, java/j2ee, Open source and big data technologies.