Social « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ Social ’

Posting status update on twitter using Twitter4j

Posted by on September 24th, 2012

Hi,

In the previous post, we saw how to Retweet any user’s tweet from our application. In the same project, i needed to post a new tweet on behalf of the authenticating user from the application using Twitter API.

Posting a new status update is quite easy using Twitter4j library.


For making any twitter API calls we need to have twitter account access_token and access_secret, which we obtains after authorizing/connecting twitter account with the application as mentioned in this blog.


Pre-Requirements:-

       String consumerKey = CONSUMER_KEY // key obtained after registering app.
       String consumerSecret =CONSUMER_SECRET // secret key obtained from the registered app.
       String twitterToken = USER_TWITTER_TOKEN 
       // access_token received by authentication user's twitter account
       String twitterSecret= USER_TWITTER_SECRET 
        // access_secret obtained by authentication user's twitter account 
       String statusUpdate = // message to be posted

Code to create new Twitter Post :-

        TwitterFactory factory = new TwitterFactory()
        Twitter twitter = factory.getInstance()
        twitter.setOAuthConsumer(consumerKey, consumerSecret)
        AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
        twitter.setOAuthAccessToken(accessToken)
        Status status = twitter.updateStatus(statusUpdate)

So, this code will create a new Twitter post on behalf of the authenticating user using API calls.

Hope this helps.


Other Blogs:-

Send Direct Message using Twitter4j
Mark Tweet as Favorite using Twitter4j
Reply to a tweet using Twitter4j
Retweet a tweet using Twitter4j


Cheers..!!!
Vishal Sahu
vishal@intelligrape.com
www.linkedin.com/in/vishalsahu

Posted in Grails

Reply to a user tweet using Twitter4j

Posted by on September 24th, 2012

Hi,

In one of my grails project, i worked on integrating twitter API with the grails application. The requirement is such that we need to display all of the tweets to any user in our application and provide the basic functionality such as reply, retweet, favorite, send direct message etc using the API calls. I used Twitter4j (a java wrapper for twitter API calls), to make API calls.


In the previous blog, we saw how to send ‘Direct Message’ to any twitter user using Twitter4j. In this blog we will see how to replay to any particular tweet using the same library


For making any twitter API calls we need to have twitter account access_token and access_secret, which we obtains after authorizing/connecting twitter account with the application as mentioned in this blog.


Pre-Requirements:-

       String consumerKey = CONSUMER_KEY // key obtained after registering app.
       String consumerSecret =CONSUMER_SECRET // secret key obtained from the registered app.
       String twitterToken = USER_TWITTER_TOKEN 
       // access_token received by authentication user's twitter account
       String twitterSecret= USER_TWITTER_SECRET 
        // access_secret obtained by authentication user's twitter account 
       String replyMessage='Hi, this is just a test message.' 
       Long inReplyToStatusId = // messageId of the tweet to which the user is replying


Code to Reply to Twitter User:-

  
        TwitterFactory factory = new TwitterFactory()
        Twitter twitter = factory.getInstance()
        twitter.setOAuthConsumer(consumerKey, consumerSecret)
        AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
        twitter.setOAuthAccessToken(accessToken)
        StatusUpdate statusUpdate = new StatusUpdate(replyMessage)
        statusUpdate.inReplyToStatusId = inReplyToStatusId
        Status status = twitter.updateStatus(statusUpdate)
    }

So, the above code will send a Reply tweet to the twitter .
This worked for me.
Hope it helps.


Other Blogs:-

Send Direct Message using Twitter4j
Mark Tweet as Favorite using Twitter4j
Retweet a tweet using Twitter4j
Post status update using Twitter4j



Cheers!!!
Vishal Sahu
vishal@intelligrape.com
www.linkedin.com/in/vishalsahu

Posted in Grails

Integrating LinkedIn with grails application

Posted by on March 19th, 2012

In my recent grails project, i needed to integrate LinkedIn with the application using LinkedIn API. I searched a lot about it and find the Java wrapper of linkedIn to use it with my grails application and thought it worth sharing.
LinkedIn uses OAuth2.0 protocol for authorization when our application tries to access the data.



LinkedIn provides 2 ways to access its data

  1. REST API
  2. JavaScript API

I used the REST API to make calls for accessing data.

The steps involved in using LinkedIn API in our grails application are as:-



#1. Register Application :

Register an application on LinkedIn here and get an API key.
This process will generate application and provide API Key & Secret Key for getting access token for API calls.



#2. Get Access Token :

With the help of API key and API secret generated in the above step, we need to get access token for calls. There are various wrapper libraries available to get the access token.


The Java wrapper which i used can be downloaded from here.


Steps involved in getting access token are same for any social media using Oauth 2.0 protocol.
#. A request token is sent to the server to get a URL for the user to give back a verification code.
#. The verification code and the request token are used in another request to get an access token.
Once we have that access token we can then use it to get data from the LinkedIn.



Code to get verification_code is as :


def registerOnLinkedIn = {

  String apiKey = API_KEY obtained from registered LinkedIn Application 
 String apiSecret = API_SECRET obtained from registered LinkedIn Application
 String callbackurl = http://www.example.com/myapp/linkedInCallback 
                              // callback URL to get the access token

  LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance()
                                         .createLinkedInOAuthService(apiKey, apiSecret) 
  LinkedInRequestToken  linkedInRequestToken=  oauthService.getOAuthRequestToken(callbackurl);
  String  authUrl = linkedInRequestToken.getAuthorizationUrl()
  session['REQUEST_TOKEN'] = linkedInRequestToken
  // set linkedRequest token in session, as we will be requiring it to get access token
  redirect(url: authUrl)

 }       

This will redirect user to linkedIn server to grant permissions for this application and provides an verification code to obtain access token

As the user grants permission, the linkedin will redirect it back to the application with verification code, which is used to retrieve access_token.


Code to handle callback, where linkedIn sends verification code.



def linkedInCallBack = {
        LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance()
                                                 .createLinkedInOAuthService(apiKey, apiSecret)
        LinkedInRequestToken requestToken = (LinkedInRequestToken) session['REQUEST_TOKEN']
        List<String> ouathVerifier = params.list("oauth_verifier")
        LinkedInAccessToken linkedInAccessToken = oauthService.getOAuthAccessToken(requestToken, ouathVerifier[0])
        String accessToken = linkedInAccessToken.token 
                                         // required access token for API calls.               
   }



This will generate access token for API calls.



This worked for me.
Hope it helps.

Useful Links:
https://developer.linkedin.com/documents/quick-start-guide
http://code.google.com/p/linkedin-j/


Cheers!!!
Vishal Sahu
vishal@intelligrape.com
http://www.intelligrape.com

Posted in Grails, Groovy

Install Apps on Facebook Fan page using API

Posted by on December 18th, 2011

Hi,
In my current grails project, we are using Facebooks Apps for our application so that any user who wish to use that app, can attach it with his/her Facebook Fan Page manually by visiting the App Profile Page and then adding it to the Fan Page. Then the attached facebook app can fetch data from our project.


But few days ago, Facebook announced that it is Removing App Profile Pages.
Now for adding facebook apps to fan page, we can either Create an Profile page for app or Add the app to Fan page using API.


I implemented the feature to attach any Facebook App to Facebook Fan page using API and thought it worth sharing.


I am assuming that you already have the Facebook Page Access Token with you, if not you can see how to Integrate facebook with web application and get access token here.


Get App Id from Facebook App page:-


To attach any Facebook Fan page, we need to issue an HTTP POST request to the facebook URL.
URL for POST request

URL :  https://graph.facebook.com/${FACEBOOK_PAGE_ID}/tabs

Values we will be requiring :


String FAN_PAGE_ACCESS_TOKEN = fan page access token.
String APP_ID = app id from the registered app.
String FACEBOOK_PAGE_ID = id of the facebook page to which app is to be attached.

Code to issue post request at the given URL:


        StringBuilder sb = new StringBuilder("access_token=");
        sb.append(URLEncoder.encode(FAN_PAGE_ACCESS_TOKEN, "UTF-8"));
        sb.append("&app_id=");
        sb.append(URLEncoder.encode(APP_ID, "UTF-8"));

        URL url = new URL("https://graph.facebook.com/${FACEBOOK_PAGE_ID}/tabs");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        String publishedPostId
        try {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + sb.toString().length());
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
            outputStreamWriter.write(sb.toString());
            outputStreamWriter.flush();
            log.debug("Response code ${connection.responseCode} , Message : ${connection.responseMessage}")
            if (connection.responseCode != 200) {
                log.debug("Unable to attach app to facebook fan page")
            }
        } finally {
            connection?.disconnect()
        }


So, we can attach any Facebook App to the Facebook Fan Page using the above code.


This worked for me.
Hope it helps.


Cheers !!!
Vishal Sahu
vishal@intelligrape.com
http://www.linkedin.com/in/vishalsahu
http://www.intelligrape.com

Posted in Grails, Groovy