Workshop 10
Workshop 10
1. Facebook
Creating a Test Facebook App and Test Users
Before Developing Facebook App, you must have to obtain AppID and Secret value of that App
for using it inside Controller class. For this, follow below steps:
2. Click on WebSite(WWW)
3. Click on Skip and Create App ID
4. Fill out the form, choose Books as Category and Click on Create App ID Button.
5. Click on Add Product from L.H.S menu and then after this and after this click on "Get
Started" button in Facebook Login category.
6. Enable " Embedded Browser OAuth Login" option and fill following infos in " Valid
OAuth redirect URIs" text box and click on "Save Changes".
7. Click on Settings menu and from the Basic Section copy the App ID and App Secret
information
8. Go To Roles Menu for creating and inviting Test Users for using your App.
1. Create a Dynamic Project named Facebook and add Spring Jar files, commons-logging-
1.2.jar and 8 different additional jar files namely(jackson-annotations-2.7.4.jar, jackson-
core-2.7.4.jar, jackson-databind-2.7.4.jar, spring-social-config-1.1.4.RELEASE.jar,
spring-social-core-1.1.4.RELEASE.jar, spring-social-facebook-2.0.3.RELEASE.jar,
spring-social-facebook-web-2.0.3.RELEASE.jar, spring-social-web-1.1.4.RELEASE.jar)
into both java build path and Deployment Assembly of your Project
2. Create a package named ch10.fb.controller inside src folder and Create a Class called
MyController inside it and paste following lines of code inside this file.
package ch10.fb.controller;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.springframework.social.facebook.api.Reference;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.FacebookLink;
import org.springframework.social.facebook.api.FriendList;
import org.springframework.social.facebook.api.PagedList;
import org.springframework.social.facebook.api.PostData;
import org.springframework.social.facebook.api.User;
import org.springframework.social.facebook.api.impl.FacebookTemplate;
import
org.springframework.social.facebook.connect.FacebookConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Operations;
import org.springframework.social.oauth2.OAuth2Parameters;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class MyController {
@RequestMapping(value="/",method=RequestMethod.GET)
public String displayMainPage()
{
return "main";
}
@RequestMapping("/fb/login")
public void login(HttpServletResponse response) throws
IOException
{
FacebookConnectionFactory connectionFactory = new
FacebookConnectionFactory("244607375914989",
"3ce21c26d61adeb2476c899f3cbaefe4");
OAuth2Parameters params = new OAuth2Parameters();
params.setRedirectUri("http://localhost:8080/Facebook/fb/callback");
params.setScope("public_profile,publish_actions");
OAuth2Operations oauthOperations =
connectionFactory.getOAuthOperations();
String authorizeUrl =
oauthOperations.buildAuthorizeUrl(params);
response.sendRedirect(authorizeUrl);
}
@RequestMapping("/fb/callback")
public String callback(@RequestParam("code") String
authorizationCode, HttpServletRequest request)
{
FacebookConnectionFactory connectionFactory = new
FacebookConnectionFactory("244607375914989",
"3ce21c26d61adeb2476c899f3cbaefe4");
OAuth2Operations oauthOperations =
connectionFactory.getOAuthOperations();
AccessGrant accessGrant =
oauthOperations.exchangeForAccess(authorizationCode,
"http://localhost:8080/Facebook/fb/callback", null);
String token = accessGrant.getAccessToken();
request.getSession().setAttribute("facebookToken",token);
return "redirect:/fb";
}
@RequestMapping("/fb")
public String fb(HttpServletRequest request, Model model)
{
String accessToken = (String)
request.getSession().getAttribute("facebookToken");
Facebook facebook = new FacebookTemplate(accessToken);
if(facebook.isAuthorized()) {
//Retrieving Profile of Facebook User
User profile=
facebook.userOperations().getUserProfile();
model.addAttribute("profile", profile);
//////////////////////////////////////////////////////
//Retrieving Friends who have accepted to use the App
List<FriendList>
friendList=facebook.friendOperations().getFriendLists();
System.out.println("List
Sizeeee="+facebook.friendOperations().getFriendProfiles().size());
List<User> friendProfileList = new LinkedList<User>();
for(FriendList friend:friendList)
{
User friendprofile=
facebook.userOperations().getUserProfile(friend.getId());
friendProfileList.add(friendprofile);
model.addAttribute("friendProfileList",
friendProfileList);
////////////////////////////////////////////////////////
///////////////////
//Posting Facebook Status Update
facebook.feedOperations().updateStatus("This was posted
from a Spring web application.");
System.out.println("Status Updated Successfully....");
////////////////////////////////////////////////////////
///////
//url,title,caption,description
//Posting a Link to Facebook
FacebookLink link = new FacebookLink
("http://www.shivapuribaba.com/","Book Released","Swadharma","English
version of swadharma released");
facebook.feedOperations().postLink("This link was posted
from a Spring web application.", link);
//////////////////////////////////////////////////
//Posting Custom Object to Facebook
///////////////////////////////////////
PostData postData = new
PostData(facebook.userOperations().getUserProfile().getId());
postData.message("Book Released");
postData.link("www.shivapuribaba.com","http://www.shivapuribaba.com/
baba_final/Images/hut.JPG", "Book", "Book Released", "ShivaPuri Baba
Swadharma English Version Released");
facebook.feedOperations().post(postData);
return "fb";
}
else {
return "redirect:/fb/login";
}
}
}
</beans>
6. Create a folder named views inside WebContent Directory and create jsp files namely
main.jsp and fb.jsp inside it.
7. main.jsp should contain following codes:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="/Facebook/fb/login"> Click here to Connect to Facebook</a>
<br>
<a href="/Facebook/tw/login"> Click here to Connect to Twitter</a>
</body>
</html>
2. Twitter
Before developing Twitter App, you must have to obtain Consumer Key and Consumer Secret
Value. For this, you must have to follow below steps:
1. Go to https://apps.twitter.com/.
2. Click on Create New App.
3. Fill in the form and create your application. Note that localhost is not a valid domain
name for the Callback URL field, but an IP address works.[ For example: you can enter:
http://127.0.0.1:8080/Facebook/tw/callback] and in WebSite Field you have to enter your
web site information such as "www.mykong.com"
4. On your application page, under Settings, check Allow this application to be used to Sign
in with Twitter.
5. Under Keys and Access Tokens, copy the API key and API secret values. You will use
them in your web application to identify your Twitter application.
You can use the same Facebook project for Twitter Application as well. For this, you have to
follow below steps:
1. Add two additional jar files namely spring-social-twitter-1.1.2.RELEASE.jar and spring-
security-crypto-4.1.0.RELEASE.jar both in a Java Build Path and Deployment Assembly.
2. Create a Controller class namely TwitterController inside src folder and paste the
following lines of code inside it.
package ch10.fb.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.social.connect.Connection;
import org.springframework.social.oauth1.AuthorizedRequestToken;
import org.springframework.social.oauth1.OAuth1Operations;
import org.springframework.social.oauth1.OAuth1Parameters;
import org.springframework.social.oauth1.OAuthToken;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.social.twitter.api.TwitterProfile;
import
org.springframework.social.twitter.connect.TwitterConnectionFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TwitterController {
@RequestMapping("/tw/login")
public void login(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
TwitterConnectionFactory connectionFactory = new
TwitterConnectionFactory("RAwLuwOnJLUbOOYz6aKI5UBVY",
"uTeIDQrIbztvlgudr9UuwNhxRMvVwX0XyuN7guwiKy53JepN27");
OAuth1Operations oauthOperations =
connectionFactory.getOAuthOperations();
OAuthToken requestToken =
oauthOperations.fetchRequestToken("http://127.0.0.1:8080/Facebook/tw/
callback", null);
request.getSession().setAttribute("requestToken",
requestToken);
String authorizeUrl
=oauthOperations.buildAuthenticateUrl(requestToken.getValue( ),
OAuth1Parameters.NONE);
response.sendRedirect(authorizeUrl);
}
@RequestMapping("/tw/callback")
public String callback(String oauth_token, String
oauth_verifier, HttpServletRequest request)
{
try
{
TwitterConnectionFactory connectionFactory = new
TwitterConnectionFactory("RAwLuwOnJLUbOOYz6aKI5UBVY",
"uTeIDQrIbztvlgudr9UuwNhxRMvVwX0XyuN7guwiKy53JepN27");
System.out.println("One");
OAuth1Operations oAuthOperations =
connectionFactory.getOAuthOperations();
OAuthToken requestToken =
(OAuthToken)request.getSession().getAttribute("requestToken");
System.out.println("Two");
// System.out.println("Token="+requestToken.getSecret());
OAuthToken token = oAuthOperations.exchangeForAccessToken(new
AuthorizedRequestToken(requestToken, oauth_verifier), null);
request.getSession().setAttribute("twitterToken", token);
return "redirect:/tw";
}
catch(Exception e)
{
System.out.println("Inside Exception"+e);
// e.printStackTrace();
return "redirect:/tw/login";
}
}
@RequestMapping("/tw")
public String tw(HttpServletRequest request,Model model)
{
OAuthToken token =
(OAuthToken)request.getSession().getAttribute("twitterToken");
if(token == null)
{
return "redirect:/tw/login";
}
TwitterConnectionFactory connectionFactory = new
TwitterConnectionFactory("RAwLuwOnJLUbOOYz6aKI5UBVY",
"uTeIDQrIbztvlgudr9UuwNhxRMvVwX0XyuN7guwiKy53JepN27");
Connection<Twitter> connection =
connectionFactory.createConnection(token);
Twitter twitter = connection.getApi();
if( ! twitter.isAuthorized())
{
return "redirect:/tw/login";
}
//Retrieving user's Twitter Profile
TwitterProfile profile
=twitter.userOperations().getUserProfile();
model.addAttribute("profile", profile);
//Retrieving Tweets of a Twitter User
List<Tweet> tweets =
twitter.timelineOperations().getUserTimeline();
model.addAttribute("tweets", tweets);
//Posting Tweets to Twitter
twitter.timelineOperations().updateStatus("System Generated
Tweet");
//Sending Private Message to Another Twitter User
twitter.directMessageOperations().sendDirectMessage("subodhfreenep",
"Just a Test Tweet");
return "tw";
}
}
3. Create a jsp file named tw.jsp inside views folder and paste following lines of code inside
it:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Connected to Twitter</h1>
name: ${profile.name}<br />
screenName: ${profile.screenName}<br />
url: ${profile.url}<br />
profileImageUrl: ${profile.profileImageUrl}<br />
description: ${profile.description}<br />
location: ${profile.location}<br />
createdDate: ${profile.createdDate}<br />
language: ${profile.language}<br />
statusesCount: ${profile.statusesCount}<br />
followersCount: ${profile.followersCount}<br />
<c:forEach items="${tweets}" var="tweet">
<p>${tweet.text}</p>
</c:forEach>
</body>
</html>
Connecting to Facebook
You have to place following codes in your controller class to connect to Facebook.
@RequestMapping("/fb/login")
public void login(HttpServletResponse response) throws IOException
{
FacebookConnectionFactory connectionFactory = new
FacebookConnectionFactory("244607375914989", "3ce21c26d61adeb2476c899f3cbaefe4");
OAuth2Parameters params = new OAuth2Parameters();
params.setRedirectUri("http://localhost:8080/Facebook/fb/callback");
params.setScope("public_profile,publish_actions");
return "redirect:/fb";
}
@RequestMapping("/fb")
public String fb(HttpServletRequest request, Model model)
{
String accessToken = (String)
request.getSession().getAttribute("facebookToken");
Facebook facebook = new FacebookTemplate(accessToken);
if(facebook.isAuthorized()) {
return "fb";
System.out.println("Successfully Connected to Facebook");
}
else {
return "redirect:/fb/login";
}
}
for(FriendList friend:friendList)
{
User friendprofile=
facebook.userOperations().getUserProfile(friend.getId());
friendProfileList.add(friendprofile);
}
model.addAttribute("friendProfileList", friendProfileList);
To create a twitter App, you have to add following codes in your controller method:
@RequestMapping("/tw/login")
public void login(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
TwitterConnectionFactory connectionFactory = new
TwitterConnectionFactory("RAwLuwOnJLUbOOYz6aKI5UBVY",
"uTeIDQrIbztvlgudr9UuwNhxRMvVwX0XyuN7guwiKy53JepN27");
OAuth1Operations oauthOperations =
connectionFactory.getOAuthOperations();
OAuthToken requestToken =
oauthOperations.fetchRequestToken("http://127.0.0.1:8080/Facebook/tw/callback",
null);
request.getSession().setAttribute("requestToken", requestToken);
String authorizeUrl
=oauthOperations.buildAuthenticateUrl(requestToken.getValue( ),
OAuth1Parameters.NONE);
response.sendRedirect(authorizeUrl);
}
@RequestMapping("/tw/callback")
public String callback(String oauth_token, String oauth_verifier,
HttpServletRequest request)
{
try
{
TwitterConnectionFactory connectionFactory = new
TwitterConnectionFactory("RAwLuwOnJLUbOOYz6aKI5UBVY",
"uTeIDQrIbztvlgudr9UuwNhxRMvVwX0XyuN7guwiKy53JepN27");
System.out.println("One");
OAuth1Operations oAuthOperations =
connectionFactory.getOAuthOperations();
OAuthToken requestToken =
(OAuthToken)request.getSession().getAttribute("requestToken");
System.out.println("Two");
// System.out.println("Token="+requestToken.getSecret());
OAuthToken token = oAuthOperations.exchangeForAccessToken(new
AuthorizedRequestToken(requestToken, oauth_verifier), null);
request.getSession().setAttribute("twitterToken", token);
return "redirect:/tw";
}
catch(Exception e)
{
System.out.println("Inside Exception"+e);
// e.printStackTrace();
return "redirect:/tw/login";
}
}
@RequestMapping("/tw")
public String tw(HttpServletRequest request,Model model)
{
OAuthToken token =
(OAuthToken)request.getSession().getAttribute("twitterToken");
if(token == null)
{
return "redirect:/tw/login";
}
TwitterConnectionFactory connectionFactory = new
TwitterConnectionFactory("RAwLuwOnJLUbOOYz6aKI5UBVY",
"uTeIDQrIbztvlgudr9UuwNhxRMvVwX0XyuN7guwiKy53JepN27");
Connection<Twitter> connection = connectionFactory.createConnection(token);
Twitter twitter = connection.getApi();
if( ! twitter.isAuthorized())
{
return "redirect:/tw/login";
}
return "tw";
}
Posting a tweet
You need to add following codes for Sending Private message to a user.