TechAlpine – The Technology world

Steps to integrate Facebook and Twitter with java application?

 

Social Media Integration

Social Media Integration

Overview: Social media revolution is become a significant event in many areas like marketing, networking, analytics and many more. The exposure to social media like facebook, twitter, linked-in has a tremendous impact on business. Social media is like a natural resource for collecting user feedback, comments, suggestions etc. So the integration of social media with applications are also very important. These applications will be able to connect to these medias and get information. In this article I will discuss the integration of facebook and twitter with java application.

Introduction: In the modern era websites have become an integral part of any business, be it big, medium or small. The web presence is an important aspect to reach to  the global audience. Presence of a business on the website is not enough to reach the greater mass audience. To reach out to a larger mass social media plays a significant role as it has a cascading and concurrent effect. Now the social networking and media sites are also interested to integrate and communicate with other websites as they also need to reach the mass common audience. In this similar way websites need the help of social sites to reach target audience. So, in order to complement this, social media sites have exposed their APIs and allows the websites to communicate and integrate with them. Facebook provides convenient APIs (known as Graph API) to integrate with their site and communicate. 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 the developers using the REST web services. As a developer we are free to use APIs of our choice to integrate the features of facebook in our application. Also as a developer we are free to use the technology of our choice. Facebook uses proxy server model as a main integration point. The facebook proxy server follows the following steps:

  • The web application will reside in our web/application server and we need to register the base URL in facebook account.
  • When the application is visited in facebook, it will calls the registered URL on the application server.
  • Now, the application will call necessary facebook APIs to get the relevant information.
  • Our application uses its own database data and facebook data and render it
  • After this facebook returns our application’s output to the user

How to get facebook libraries:

Before we integrate facebook with our java application we need some third party libraries. These third party libraries will help us in 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.

You can check http://code.google.com/p/facebook-java-api/ to get more details about the APIs and Jars. These third party libraries are compatible with Java SE 5 and above.

Download the following JAR files

If you are using Java application server on top of Java SE 5, then you should download the following JAR files:

The above three JARs 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 + “\n”;

StringBuffer searchMessage = new StringBuffer();

ResponseList<Post> results = facebook.getPosts(searchPost);

for (Post post : results) {

System.out.println(post.getMessage());

searchMessage.append(post.getMessage() + “\n”);

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()

+ “\n”);

}

}

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<Post> 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() + “\n”);

}

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”;

}

}

Integrating with Twitter: In order to integrate you 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 we need to follow certain steps as mentioned below:

  • Send a request to twitter asking for a token. This request should carry both 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 like above as well as the previously stored request token and the PIN.
  • Once the token is received, every request going o 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<Status> tweets = qr.getTweets();

for (Status t: tweets){

System.out.println(t.getId() + ” – ” + t.getCreatedAt() + “: ” + t.getText());

out.write(“\n”+t.getId()+”,”);

out.write(“\t”+t.getText()+”,”);

out.write(“\t”+t.getUser()+”,”);

}

}

try{

Thread.sleep(1000*60*15);

}catch(Exception e) {}

}

}

Conclusion: There are many social networking websites available. Out of these facebook and twitter are more commonly used. Java provides libraries to integrate our applications with these websites. So to conclude our discussion, we can understand that social media integration is a new dimension in developer’s world and we should explore it as much as possible.

Leave a Reply

Your email address will not be published. Required fields are marked *


9 − = 2

TechAlpine Books
-----------------------------------------------------------