Bruno Raljić

A Java Developer's Blog

How to send tweets from Java

After finishing mongoDB course, my colleague (Nikola Cakarevic) and I decided to build up a small project that will combine Spring (Spring MVC and Spring Data) and mongoDB. Since the Twitter fits in the whole Big Data story, we decided to base our project on it. Yesterday I found some free time to see how can we easily integrate Twitter. At first, I was thinking about getting tweets as JSON object, since you can get it very easy. I found it as a good approach because JSON is used in mongoDB (expand the source below to see how the tweet is presented as JSON).


{
   "created_at":"Fri Dec 21 10:12:15 +0000 2012",
   "id":282065939585978368,
   "id_str":"282065939585978368",
   "text":"Started working with #Spring #Social #Twitter",
   "source":"web",
   "truncated":false,
   "in_reply_to_status_id":null,
   "in_reply_to_status_id_str":null,
   "in_reply_to_user_id":null,
   "in_reply_to_user_id_str":null,
   "in_reply_to_screen_name":null,
   "user":{
      "id":1015727234,
      "id_str":"1015727234"
   },
   "geo":null,
   "coordinates":null,
   "place":null,
   "contributors":null,
   "retweet_count":0,
   "entities":{
      "hashtags":[
         {
            "text":"Spring",
            "indices":[
               21,
               28
            ]
         },
         {
            "text":"Social",
            "indices":[
               29,
               36
            ]
         },
         {
            "text":"Twitter",
            "indices":[
               37,
               45
            ]
         }
      ],
      "urls":[

      ],
      "user_mentions":[

      ]
   },
   "favorited":false,
   "retweeted":false
}

But, then I found even better solution. My colleague Dragan Vidovic recommended me to use Spring Social – Twitter. When I took a quick look, it surprised me how easy it is to implement. After few steps I’ve managed to send a tweet from a main method. I’ll show you how to do it. This article will be more like a reminder for me, I’m sure there are lot of blogs about this topic.

Dependencies

Start with adding dependencies:

<spring-social.version>1.0.2.RELEASE</spring-social.version>

<dependency>
	<groupId>org.springframework.social</groupId>
	<artifactId>spring-social-core</artifactId>
	<version>${spring-social.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework.social</groupId>
	<artifactId>spring-social-web</artifactId>
	<version>${spring-social.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework.social</groupId>
	<artifactId>spring-social-twitter</artifactId>
	<version>${spring-social.version}</version>
</dependency>

Twitter interface

public interface Twitter {

   boolean isAuthorizedForUser();

   DirectMessageOperations directMessageOperations();

   FriendOperations friendOperations();

   GeoOperations geoOperations();

   ListOperations listOperations();

   SearchOperations searchOperations();

   TimelineOperations timelineOperations();

   UserOperations userOperations();

}

As you can see, there are several groups of operations you can perform. For some you need to be authenticated, you need to have some permissions but for some (e.g. searching) you don’t need anything.

Searching

First thing I tried is to see how can I search the Twitter (search tweets, users etc). Here’s the short example

Tweets

Twitter twitter = new TwitterTemplate();
SearchResults searchResults = twitter.searchOperations().search("brunoraljic");
StringBuilder sb = new StringBuilder();
for (Tweet tweet : searchResults.getTweets()) {
	sb.append("Tweet: \"")
	.append(tweet.getText())
	.append("\" Author: ")
	.append(tweet.getFromUser())
	.append(" Date: ")
	.append(tweet.getCreatedAt())
	.append("\n");
}
System.out.println(sb.toString());

Profiles

Twitter twitter = new TwitterTemplate();
TwitterProfile userProfile = twitter.userOperations().getUserProfile("brunoraljic");
StringBuilder sb = new StringBuilder();
sb.append("User: ")
	.append(userProfile.getScreenName())
	.append("\nName: ")
	.append(userProfile.getName())
	.append("\nBio: ")
	.append(userProfile.getDescription())
	.append("\nLink: ")
	.append(userProfile.getUrl())
	.append("\nFollowers: ")
	.append(userProfile.getFollowersCount());
System.out.println(sb.toString());

Tweeting from public static void main(String[] args)

OK, now let’s try to tweet something. First, you’ll need to register your application. Go to dev.twitter.com/apps and create new application. In order to post new tweets you’ll need the following:

  • Consumer key
  • Consumer secret
  • Access token
  • Access token secret

First two you get when you create an application. Second two you get after generating OAuth tokens. If you want to post new tweets do not forget to select Read and write access level.

Twitter tw = new TwitterTemplate(C_KEY, C_SECRET, A_TOKEN, A_TOKEN_SECRET);
TwitterProfile user = tw.userOperations().getUserProfile();
System.out.println(user.getScreenName());

For searching purposes I used TwitterTemplate no-args constructor. Now I use this constructor, to authenticate myself. You can see now on the line 3, it’s enough to call getScreenName() without any username to get your username. For posting tweets we will use timeline operations.

Twitter tw = new TwitterTemplate(C_KEY, C_SECRET, A_TOKEN, A_TOKEN_SECRET);
String tweet = "Testing #spring #social, if this works, " +
        "I'll use twitter from main() method from now on : )";
if (tweet.length() <= MAX_TWEET_LENGTH) {
	tw.timelineOperations().updateStatus(tweet);
}

And here it is, a brand new tweet:

, , ,

Leave a Reply

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

Show my latest blog post with this comment!