Social Media « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ Social Media ’

Reading comments of LinkedIn wall post

Posted by on September 26th, 2012

Hi,


In one of my grails project, i needed to show the comments on any wall post of linkedin through API. I used the Java wrapper to connect any linkedIn account with the grails application which can be seen here. But somehow this library was not working when we need to fetch comments from any wall post and display them in our UI.


I searched a lot about it but couldn’t find anything appropriate, then i decided to use the linkedIn API directly for retrieving the data. To make GET calls , i used the Scribe java library which can be downloaded from here.


To make API calls on linkedIn, we need to have an authenticated account’s access_token and access_secret, which can be obtained by connecting a linkedIn account with the application as mentioned in this post.


Code to fetch comments on LinkedIn Wall post :-

String consumerKey = CONSUMER_KEY // key obtained by linkedIn app
String consumerSecret = CONSUMER_SECRET // secret obtained from linkedIn app
String accessToken = 'assess_token'
String accessSecret = 'access_secret'
String postId = POST_ID // id of the wall post

 OAuthService service = new ServiceBuilder()
                .provider(LinkedInApi.class)
                .apiKey(consumerKey)
                .apiSecret(consumerSecret)
                .debug()
                .build();
 String url = "http://api.linkedin.com/v1/people/~/network/updates/key=${postId}/update-comments?format=json";
 
       OAuthRequest request = new OAuthRequest(Verb.GET, url);
        org.scribe.model.Token accessToken = new org.scribe.model.Token(accessToken,accessSecret)
        service.signRequest(accessToken, request);
        Response response = request.send();
        String jsonResponse = response.getBody()
         def updates = JSON.parse(jsonResponse) // contains comments data in JSON format

          updates.values.each {def commentData ->
                  println "Comment : ${commentData.comment}"
                  println "Creator: ${commentData.person.firstName}"        
            }

This code will fetch the comments from any linkedin wall post. It worked in my case.


Hope it helps.


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

Posted in Grails, Groovy

Get recent twitter followers using Twitter4j

Posted by on September 25th, 2012

Hi,

In the previous blog we saw how to fetch twitter users based on some search criteria using the Twitter4j library, a java wrapper available for Twitter API calls.


In the same grails project, i had the requirement to display the recent twitter followers of authenticated twitter accounts. Twitter4j library provides a way to get the IDs of twitter followers in the ordered way, which can further be used to get the information of the latest followers. It helped me a lot to make quick list of user’s recent followers on twitter.



Twitter API needs 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.


Code to fetch recent twitter followers:-


       TwitterFactory factory = new TwitterFactory()
        Twitter twitter = factory.getInstance()
        twitter.setOAuthConsumer(consumerKey, consumerSecret)
        AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
        twitter.setOAuthAccessToken(accessToken)
        String twitterScreenName = twitter.getScreenName()
        IDs followerIDs = twitter.getFollowersIDs(twitterScreenName, -1)
        List<Integer> followerIdList = followerIDs.IDs
        if (followerIdList?.size() > 0) {
            int numberOfFollowers = Math.min(followerIdList.size(), 20)
            followerIdList = followerIdList.subList(0, numberOfFollowers)
            followerIdList.each {
                twitter4j.User user = twitter.showUser(it)
                  println("Name: ${user.screenName}")
                  println("Location: ${user.location}")
            }
        }


This code will fetch the recent 20 followers from the user’s twitter account.

Hope this helps.


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

Posted in Grails

Search Twitter Users using Twitter4j

Posted by on September 25th, 2012

Hi,

In the previous blog we saw how to fetch tweets based on some search criteria using the Twitter4j, a java wrapper library available for Twitter API calls.


In the same grails project, i had the requirement to search users based of their name or words. Twitter4j library provides a cool way to search users over twitter with its searchUsers() method. It helped me a lot to make quick search of users on twitter.



Twitter User search API needs 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.


Code to search Users:-


           String queryString='Vishal' // some name which you want to search on twitter
           TwitterFactory factory = new TwitterFactory()
           Twitter twitter = factory.getInstance()
           twitter.setOAuthConsumer(consumerKey, consumerSecret)
           AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
           twitter.setOAuthAccessToken(accessToken)
      
           List users = twitter.searchUsers(queryString, 1)
            users.each { user->
                   println("Name: ${user.screenName}")
                   println("Location: ${user.location}")
                  }

This code will fetch the latest 20 users which fits the searched criteria.

Hope this helps.


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

Posted in Grails

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

Parsing tweet for Hashtags, Usernames and URLs in Java

Posted by on September 24th, 2012

Hi,

As i am working on Twitter integration in my current project, i needed to display the searched tweets from twitter API, on my view layer. When we query the Twitter API, it returns tweets text in the form of simple string which contains HashTags, Twitter usernames and links to external resources.


While displaying them on the UI layer, i wanted to have the proper links for every element like:-

#. Hashtags should be linked to search of tweets containing similar tags on twitter.
#. Usernames should link to the profile of that user on twitter.
#. External URLs should be connected to the resource it is pointing to.


I searched a lot and found various ways which are really useful if you want to parse the tweet on the server side and thought it worth sharing.
Below is the method which i used to parse tweet and returns the final html which i can use directly on my UI.


   String parse(String tweetText) {

        // Search for URLs
        if (tweetText && tweetText?.contains('http:')) {
            int indexOfHttp = tweetText.indexOf('http:')
            int endPoint = (tweetText.indexOf(' ', indexOfHttp) != -1) ? tweetText.indexOf(' ', indexOfHttp) : tweetText.length()
            String url = tweetText.substring(indexOfHttp, endPoint)
            String targetUrlHtml=  "<a href='${url}' target='_blank'>${url}</a>"
            tweetText = tweetText.replace(url,targetUrlHtml )
        }

        String patternStr = "(?:\\s|\\A)[##]+([A-Za-z0-9-_]+)"
        Pattern pattern = Pattern.compile(patternStr)
        Matcher matcher = pattern.matcher(tweetText)
        String result = "";

        // Search for Hashtags
        while (matcher.find()) {
            result = matcher.group();
            result = result.replace(" ", "");
            String search = result.replace("#", "");
            String searchHTML="<a href='http://search.twitter.com/search?q=" + search + "'>" + result + "</a>"
            tweetText = tweetText.replace(result,searchHTML);
        }

        // Search for Users
        patternStr = "(?:\\s|\\A)[@]+([A-Za-z0-9-_]+)";
        pattern = Pattern.compile(patternStr);
        matcher = pattern.matcher(tweetText);
        while (matcher.find()) {
            result = matcher.group();
            result = result.replace(" ", "");
            String rawName = result.replace("@", "");
            String userHTML="<a href='http://twitter.com/${rawName}'>" + result + "</a>"
            tweetText = tweetText.replace(result,userHTML);
        }
        return tweetText;
    }

The above code will return the tweet text wrapped in HTML elements to make it more UI friendly.


This worked for me.
Hope it helps.


Useful Links:-

https://dev.twitter.com/docs/tco-url-wrapper
http://stackoverflow.com/questions/8451846/actual-twitter-format-for-hashtags-not-your-regex-not-his-code-the-actual
http://www.simonwhatley.co.uk/parsing-twitter-usernames-hashtags-and-urls-with-javascript


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

Posted in Grails

Follow/Unfollow twitter account using Twitter4j

Posted by on September 24th, 2012

Hi,

In my recent grails project, i worked on integrating twitter API with the grails application. In one of the requirements, we needed to show the tweets from user wall and show the profile of the person/account who posted that tweet. In the profile, the user should be able to Follow or Unfollow that person from his twitter account using our application interface. I used Twitter4j (a java wrapper for twitter API calls), to make API calls and implemented this functionality.


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 twitterName = // twitterName of the twitter account the user want to follow/unfollow


Code to Follow a Twitter Account:-

  
         TwitterFactory factory = new TwitterFactory()
         Twitter twitter = factory.getInstance()
         twitter.setOAuthConsumer(consumerKey, consumerSecret)
         AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
         twitter.setOAuthAccessToken(accessToken)
         twitter4j.User  user = twitter.createFriendship(twitterName)
    }

The above code will help to Follow the twitter account provided in the twitterName.


Code to Unfollow a Twitter Account:-

  
        TwitterFactory factory = new TwitterFactory()
        Twitter twitter = factory.getInstance()
        twitter.setOAuthConsumer(consumerKey, consumerSecret)
        AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
        twitter.setOAuthAccessToken(accessToken)
        twitter4j.User  user = twitter.destroyFriendship(twitterName)
    }

The above code will help to Unfollow the twitter account provided in the twitterName.


This worked for me.
Hope it 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, Groovy

Retweet a 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 mark any tweet as ‘Favorite’ using Twitter4j. In this blog we will see how to Retweet 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 
       Long tweetId = // messageId of the tweet to be retweeted


Code to Retweet a Tweet:-

  
       TwitterFactory factory = new TwitterFactory()
        Twitter twitter = factory.getInstance()
        twitter.setOAuthConsumer(consumerKey, consumerSecret)
        AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
        twitter.setOAuthAccessToken(accessToken)
        twitter.retweetStatus(tweetId)
    }

So, the above code will create a Retweet for that tweet.
This worked for me.
Hope it helps.


Other Blogs:-

Send Direct Message using Twitter4j
Mark Tweet as Favorite using Twitter4j
Reply to a tweet using Twitter4j
Post status update 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

Mark tweet as ‘Favorite’ using Twitter4j

Posted by on September 24th, 2012

Hi,

In one of my grails project, i worked on integrating twitter API with the application. The requirement is such that we need to display all of the tweets to any user and provide the basic functionality such as reply, retweet, favorite etc using the API calls. I used Twitter4j (a java wrapper for twitter API calls), to make API calls. You can refer this blog to see how we can integrate the grails application with Twitter.


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 
       Long tweetId = // id of the tweet


Code to mark tweet as Favorite:-

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

The above code will mark the tweet as ‘Favorite’ for that user.
This worked for me.
Hope it helps.


Other Blogs:-

Send Direct Message using Twitter4j
Reply to a tweet 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