Wednesday, 24 October 2012

Develop cool apps in Facebook

Overview:

Stop using others app on Facebook!!! This is the right time to develop your own app in Facebook, "the largest social networking media" so that others can get service from  your app as till  now you are getting it from other developers.
Facebook give the facility to take the data by user permission so that the developers can use it for their app development.
From Facebook you can access data like your birthday,your email id,you and yours friends education detail,you and yours friends work history ,your and yours friends status and photo updates and so on..(Click hear for Details).
After receiving the data from user, you can use any computer programming language to develop the app viz java. php, cpp,.Net etc.

Here i get only basic permission details, for more browse on Facebook Developer  page.You can get like button you can also get post and feeds automatically.check it out for more....

Supporting Example:

1> Recruitment:
 >>Last time i visited to vmware careers.Actually i was interested for one of the job post. so when i click apply now they redirect me towards Facebook.What they are doing is, they are tracking all the details like your email,name,dob,Education details,Work history from  Facebook account and maintaining in their own data store.If you are looking suitable for that job then  you will get a mail from their automated system.you can do it by using java mail api in-case of java or any other api in other platform.
>>Similarly i experience  the same with ZOHO career and approximately all mnc and mulit port companies are collecting data from Facebook(first one is Linked in) for their hiring process as you know Facebook is the largest social networking media.
2>Utility/security
For example to check whether all  posted link are trusted or not Norton security develop one facebook app.It will scan all link posted by your friends and detect the status etc
3>Shopping(AmeriCommerce Store)
4>Advertising(Facebook advertise )
6>Sex and Romance etc
To know more about category of app that you can develop go to

How to Prepare yourself for developing your own app:

1.You have to strong in one or  more programming language
2.You have to get one Idea on which domain exactly you want to develop your app
3.You have to have knowledge of parsing and preparing the json .

Put your First Step:

1. Register your self in Facebook Developer page with your existing credential.

2.Verify your account by using your mobile number(100% confidential)

3.click on create app(Here)

4.As soon you click on create app one pop-up will come, which will ask  App name that you wanted to     develop and App namespace which is optional one

5.Important!!!Decide on which server you will host your application, if you don't have plan then check the web Hosting box.
with this hosting server you can deploy only php, Ruby, Python, Node.js etc.If you are planning to develop your app in any other language like java,.Net,cpp etc then choose your own hosting server viz Cloud computing environment.In my case i use Google cloud.
6.Note down the app id,App secrete which you will use it on your app development


Getting start with my application:

In order to complete the blog i display user details from basic permissions only infect you can use more by following the above guide line.

Basically i did it by using java(spring, jsp, GAE, json, oauth protocol).
i use spring-mvc and for injection dependency you can use ioc.
in my app total 4 files are there;-
   1.BasicFacebookApp.java(I implimanted my business logic hear using Spring-mvc)
   2.UserDetails.java(it is one of the data transfer object you can say a pojo)
   3.userdetails.jsp(for displaying the details)
   4.welcome.jsp(user will get it in first hit)


Explanation and Details:

Here i just present few line of code snippet from my application but not the total application,So try to customize it according to you r requirement.
By using this example code you can fetch your details like mail,dob, first name, last name etc

step-1:redirect to Facebook using following URL
url=https://www.facebook.com/dialog/oauth/?" +
"client_id=copy your app id&" +
"redirect_uri=copy your redirect uri&" +
"response_type=code&" +
"state=litu101&"+
"scope=mention details permission separated with ,

Stpe-2:Get the code send by facebook as a query string
Step-3:By using the code send the url to get access_token
String url_For_AccesToken= "https://graph.facebook.com/oauth/access_token?client_id=COPY THE APP ID&" +
            "redirect_uri=http://facebookoauthforbasicinformati.appspot.com/gettingCode&" +
            "client_secret=COPY THE APP SECRATE&" +
            "code="+code;
Step-4: Exchange  the access_Token  to access Graph-api which will return the required details in the form of  json. For this you have to prepare one URL and send it to Facebook server with access_token
To prepare the URL refer to Graph API Explorer
Step-5: Parse the json using json parser 

BasicFacebookApp.java
======================================
package com.acti.controller;

import ...;

@Controller
public class BasicFacebookApp {
//this is hte welcome file
@RequestMapping(value="/", method=RequestMethod.GET)
public String homeController(){
return "welcome";
}
//Step-1
//this is the rediracted uri if user will allow then it will access data otherwise not
@RequestMapping(value="/sendfb",method=RequestMethod.GET)
public void rediredttoFacebook(HttpServletRequest request,HttpServletResponse response) throws IOException{
HttpSession session=request.getSession(true);
String redirest_Facebool="https://www.facebook.com/dialog/oauth/?" +
"client_id=copy your app id&" +
"redirect_uri=copy your redirect uri&" +
"response_type=code&" +
"state=litu101&"+
"scope=mention details permission separated with ,";
response.sendRedirect(redirest_Facebool);
}
//callback functionality
@RequestMapping(value="/gettingCode",method=RequestMethod.GET)
public String postProcessingfb(HttpServletRequest request){
HttpSession session=request.getSession(false);
if(session!=null){
UserDetails user=new UserDetails();
//step-2
String fb_code=request.getParameter("code");
String accessToken="";
System.out.println("code::"+fb_code);
//http://facebookoauthforbasicinformati.appspot.com
//http://localhost:8888/gettingCode
try {
//step-3
        String inputLine;
        String url_For_AccesToken= "https://graph.facebook.com/oauth/access_token?client_id=COPY THE APP ID&" +
            "redirect_uri=http://facebookoauthforbasicinformati.appspot.com/gettingCode&" +
            "client_secret=COPY THE APP SECRATE&" +
            "code="+fb_code;
            URL url=new URL(url_For_AccesToken);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            BufferedReader bufferReader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuffer stringBuffer=new StringBuffer();
            while ((inputLine=bufferReader.readLine())!=null)
            stringBuffer=stringBuffer.append(inputLine+"\n");
            bufferReader.close();
            accessToken=stringBuffer.toString();
        }catch (Exception token_Exception) {
// TODO: handle exception
        //your reeor handling code
}
        System.out.println("acces token::"+accessToken);
//step-4
        String graph = "";
        try{
        String graph_Inputline;
        String graph_requestURL="https://graph.facebook.com/me?fields=id,name,link,gender,first_name,last_name,username,locale&"+accessToken;
        URL graph_URL=new URL(graph_requestURL);
        URLConnection graph_urlConnection=graph_URL.openConnection();
        BufferedReader graph_bufferReader=new BufferedReader(new InputStreamReader(graph_urlConnection.getInputStream()));
            //StringBuffer graph_stringBuffer=new StringBuffer();
        String graph_stringBuffer = "";
            while ((graph_Inputline = graph_bufferReader.readLine()) != null)
                //graph_stringBuffer.append(graph_Inputline + "\n");
            graph+=graph_Inputline;
            graph_bufferReader.close();
            //graph=graph_bufferReader.toString();
        }catch (Exception graph_Exception) {
// TODO: handle exception
        your erroe handling code
}
        System.out.println("json::"+graph);
//step-5:
        //prese the json
        try{
        JSONObject json=new JSONObject(graph);
        user.setId(json.getString("id"));
       
        user.setName(json.getString("name"));
       
        user.setLink(json.getString("link"));
       
        user.setGender(json.getString("gender"));
       
        user.setFirst_name(json.getString("first_name"));
       
        user.setLast_name(json.getString("last_name"));
       
        user.setUsername(json.getString("username"));
       
        user.setLocale(json.getString("locale"));
       
        session.setAttribute("user",user);
        return "userdetails";
       
        }catch (Exception e) {
// TODO: handle exception
        //your own error handling code
}
}
return null;
}
}

======================================

.UserDetails.java
===========================
package com.acti.dto;

import java.io.Serializable;

@SuppressWarnings("serial")
public class UserDetails implements Serializable{
private String id;
private String name;
private String first_name;
private String last_name;
private String link;
private String username;
private String gender;
private String locale;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
}

===========================

userdetails.jsp
==========================
<%@ page language="java" import="com.adaptavant.dto.UserDetails;" session="true" 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>
<jsp:useBean id="user" class="com.adaptavant.dto.UserDetails" scope="session"/>
 <table border="0"  cellpadding="0" cellspacing="0" 
height="40%" width="40%">
          <tr>
             <td><FONT SIZE="4" COLOR="#333399">We fetch the Following Information from FaceBook</FONT><BR></td>
          </tr>
          <tr>
             <td><B>Name:</B></td>
             <td> <%=user.getName() %></td>
          </tr>
          <tr>
             <td><B>FirstName</B></td>
             <td> <%=user.getFirst_name()%></td>
          </tr>
          <tr>
             <td><B>LastName</B></td>
             <td> <%=user.getLast_name() %></td>
          </tr>
          <tr>
             <td><B>Id</B></td>
             <td><%=user.getId()%></td>
          </tr>
           <tr>
             <td><B>Location</B></td>
             <td> <%=user.getLocale()%></td>
          </tr>
           
           
           <tr>
             <td><B>Click To view</B></td>
             <td><a href="<%=user.getLink()%>">Click</a></td>
          </tr>
           <tr>
             <td><B>Gender</B></td>
             <td><%=user.getGender()%></td>
          </tr>
          
</table>
</body>
</html>
==========================

Welcome.jsp
==============================
<%@ 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>
<style type="text/css">
div#body1{
position:absolute;
top:400px;
left:600px;
}

</style>
</head>
<body>
<div id="header1">
<font " size="4" style="top: 351px;left: 452px;position: absolute; color:rgb(16, 65, 168);">Click Below Image to Fetch details from Facebook account</font>
<div id="body1">
<a href="/sendfb"><img src="http://commondatastorage.googleapis.com/conversionsupportimages/cswebsiteimages/facebook.gif"></a>
</div>
</div>
</body>
</html>
=============================


Finally i would like to thank you for your patience.if you like this then don't forgot  to post comment,complement or suggestion which will inspire me for further posting.



















Skype Me™!

Wednesday, 17 October 2012

Twitter oauth guideline with Example

About:

By  using this blog you can access data from twitter Server on OAuth standard. Twitter will give all data of a particular user except  password. So that you can use it in your product development.you can do this by using Facebook and Google too.Hopefully i will post all that stuff later on.

Recently i have finished one application related to Twitter oauth where i face many problem while developing  because i didn't find one good documentation from internet.
So if you are one of them then relay this blog will be very useful to you

To Develop this several third party apis are there but basically i use Twitter-4j api.
Follow the below guideline for Getting start.

Pre-Requirements:

1.Any live hosting server in testing or developing mood.(because call back url will not work for localhost)
2.A twitter account
3.Twitter4J API: you need twitter4j-core-[verson].jar to your built path
4.You can refer api Doc

Getting Start/Register one App with Twitter:

1.Create a new application on twitter development environment
2.Click on create new application.
                         

3. Fill-up the details as shown in below screen shot

                                 
    Name:your app name any thing(in my case getRef)
    Description:what is the motto of your app(you can get......)
   Website:your publicly available web site where you are planing to deploy your app.
   callback URL:  Give one hosting environment address because in local host it will not work
   click on create your twitter application

4.Click on create a new application:
  it will give you the following details listed below
      Consumer key
Consumer secret
Request token URL
Authorize URL
Access token URL
Callback URL

5. it's important in callback URL don't give you localhost
    it will not work
    twitter has already remover that option
    so use any live hosting environment and for students use any free cloud server
    for deploy your app by loin for personal use
    eg:-Google app engine,amazon cloud server

    later you will use all the information above while developing your application so note it down.


Example:

Here i use spring-mvc and Google app engine for Deploying this application.In face you can use ioc for injection dependency.

1.i use one Controller to handle all this stuff(GetDataFromTwitter.java) infect you can use servlet also
2.One jsp page to redirect to my app(Welcome.jsp)/optional one
3.Another jsp to ask conformation before redirecting to twitter server(login.jsp)
4.Another one for Displaying the user details. Infect you can  use the user  details/information for further business processing.But in order to complete this blog i display the user information(success.jsp).


Welcome.jsp:(Just for the worm welcome any way this is optional one)

=========================================
<%@ 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>
<style type="text/css">
div#body1{
position:absolute;
top:400px;
left:600px;
}

</style>
</head>
<body>
<div id="header1">
<font color="#0EA5B9" size="4" style="top: 351px;left: 491px;position: absolute;">Click Below Image to Fetch details from Twitter</font>
<div id="body1">
<a href="/requesttwitter"><img src="../image/logo.png"></a>
</div>
</div>
</body>
</body>
</html>
===========================================

GetDataFromTwitter.java:(all business Details)

========================================================
package com.acti.controller;
imports........................;

@Controller
@RequestMapping(value="/")
public class GetDataFromTwitter {

   // This is the consumer key for this application
    private String consumer_key =copy it from your refistred app;

    // This is the consumer secret for this application
    private String consumer_secret = copy it from your registred app;

//Step-1(just for welcome file list)
    @RequestMapping(value="/",method=RequestMethod.GET)
    public String welcome(HttpServletRequest request,HttpServletResponse response) throws     TwitterException{
    return "welcome";
    }
 /Step-2(/from welcome.jsp it will come hear)
@RequestMapping(value="/requesttwitter",method=RequestMethod.GET)
    public String getDetails(HttpServletRequest request,HttpServletResponse response) throws TwitterException{
   
    Twitter twitter = new TwitterFactory().getInstance();
twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumer_key, consumer_secret);
    //AccessToken requestToken=twitter.getOAuthAccessToken();
    RequestToken requestToken= twitter.getOAuthRequestToken();
    String token = requestToken.getToken();
    String tokenSecret = requestToken.getTokenSecret();
    HttpSession session = request.getSession();
    session.setAttribute("token", token);
    session.setAttribute("tokenSecret", tokenSecret);
    session.setAttribute("requesttoken", requestToken);
    System.out.println("Token "+token);
    System.out.println("TokenSecrate "+tokenSecret);
    String authUrl = requestToken.getAuthorizationURL();
    request.setAttribute("authUrl", authUrl);
    System.out.println("url"+authUrl);
    return "login";
   
    }
//Step-3(call back url in my case XXXX.appsport.com/getdata what you have registred curing creation of app)
@RequestMapping(value="/getdata",method=RequestMethod.GET)
public String afterAuthentication(HttpServletRequest request,HttpServletResponse response) throws IOException{
                //create one UserDetails pojo with setter and getter method
UserDetails user_Details=new UserDetails();
PrintWriter out=response.getWriter();
HttpSession session = request.getSession(false);
if(session!=null){
try{
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumer_key,consumer_secret);
AccessToken accessToken = twitter.getOAuthAccessToken((RequestToken) session.getAttribute("requesttoken"));
twitter.setOAuthAccessToken(accessToken);
//User is a object which contain all the user information details
User user=twitter.verifyCredentials();
user_Details.setUser_Name(user.getName());
System.out.println("seventh");
user_Details.setFrineds_count(user.getListedCount());
user_Details.setUser_Location(user.getLocation());
user_Details.setGet_id(user.getId());
user_Details.setGetLanguage(user.getLang());
user_Details.setUser_url(user.getURL().getPath());
user_Details.setProfile_image(user.getProfileImageURL().getPath());
user_Details.setGettime_Zone(user.getTimeZone());
session.setAttribute("user", user_Details);
}catch (TwitterException twitterException) {
// TODO: handle exception
//your error handling mechanism
}
}
return "sucess";
}
}
=========================================================

login.jsp:( for getting conformation)

=======================================

<%@ 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>

<style type="text/css">
a{
text-decoration : none;
}
a:link {
color: green;
font-weight: bold;
}
a:visited {
color:green;
font-weight: bold;
}
a:hover{
color: red;
font-size: 20px
}
div.common{
font-weight: bold;
position: relative;
left: 500px;
top: 382px;
}
}
/* a:visited{
color:yellow;
} */
</style>

</head>
<body>
<div class="common">
<font color="red" size="4">We need your permission</font><br><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 <a href='<%=request.getAttribute("authUrl") %>'>Click to conform</a>
</div>
</body>
</html>

======================================

success.jsp (to see user details)

==================================

<%@ page language="java" import="com.acti.dto.UserDetails;" 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>
<jsp:useBean id="user" class="com.acti.dto.UserDetails" scope="session"/>
 <table border="0"  cellpadding="0" cellspacing="0" 
height="40%" width="40%">
          <tr>
             <td><FONT SIZE="4" COLOR="#333399">We fetch the Following Information from Twitter</FONT><BR></td>
          </tr>
             <td><B>Name:</B></td>
             <td> <%= user.getUser_Name() %></td>
          </tr>
          <tr>
             <td><B>Id</B></td>
             <td> <%= user.getGet_id() %></td>
          </tr>
           <tr>
             <td><B>Location</B></td>
             <td> <%= user.getUser_Location()%></td>
          </tr>
           <tr>
             <td><B>Language</B></td>
             <td> <%= user.getGetLanguage() %></td>
          </tr>
           <tr>
             <td><B>TimeZone</B></td>
             <td> <%= user.getGettime_Zone()%></td>
          </tr>
           <tr>
             <td><B>Number of Friend</B></td>
             <td> <%= user.getFrineds_count() %></td>
          </tr>
           <tr>
             <td><B>View Profile</B></td>
             <td> <a href="<%= user.getUser_url()%>">click</a></td>
          </tr>
          
</table>
</body>
</html>
===================================



Ok if you fill that this post is really helping you then please don't forgot  to post comment,compliment or suggestion because it will give me more inspiration and energy for further posting.
Finally i will say thank you for your patience











Skype Me™!