Tutorial: Java based Twitter App on Google App Engine

google_app_engine_javaTwitter a microblogging service is getting more and more popular these  days. A lot of developers are involved to develop applications on its  API.

Two weeks ago I click with a very basic idea and being as a matter of learning I started working on it. I have finished more than 80% of the work. I deployed the application on Google App Engine (I hope you are familiar with it). I used Twitter4J lib a Java wrapper for Twitter API.

If you are also interested in Twitter based app development in Jave, then this tutorial will be helpful for you. Feel free to add comments at the end of the post, I will love to reply.

Things you require for development

Things you need to know before you start

Oauth authentication

You should know Oauth basics and its terminologies. You can little google on it or read this FAQs

Register an App with Twitter

You need to register an application on this URL: http://twitter.com/oauth. Please take care of two things. The call back URL will not be your localhost URL. It should be a valid web address. And while choosing Default Access Type, if your application need to do changes or send tweets then you should choose Read & Write otherwise/if you just want to do readonly operations then leave Read-only checked.

A little bit about Google App Engine

Google App Engine is cloud based hosting environment. You should read on their web or on a post by me.

Steps for any Twitter App

  1. User is on your website
  2. Generate a token
  3. Have a hyperlink and take user to the Twitter from your website for authentication
  4. User will enter its user name and passeword and press allow
    If user’s credentials authentiecated Twitter will call the callback method which you had mentioned. Note that localhost URLs will not work here. You need mentiona a valid web address which will be invoked when user will be authenticated.

Code Section

I will assume that you have developed a helloworld prject in Google App Engine and deployed it on appspot.com domain. Code snippet is available in 2 servlets and 1 jsp page.

LoginServlet.java

Twitter twitter = new Twitter();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
RequestToken requestToken  = twitter.getOAuthRequestToken();

String token = requestToken.getToken();
String tokenSecret = requestToken.getTokenSecret();

HttpSession session = request.getSession();
session.setAttribute("token", token);
session.setAttribute("tokenSecret", tokenSecret);

String authUrl = requestToken.getAuthorizationURL();

request.setAttribute("authUrl", authUrl);
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
rd.forward(request, response);

Consumer key and secrets will be generated when you register an application with Twitter. You need to keep token information into session so that you can use the token when callback URL will be called. authUrl is a link which will take user to the Twitter website for authentication. And if authentication successful it will call your URL mentioned as callback.

login.jsp

<a href='<%=request.getAttribute("authUrl") %>'>Sign in with Twitter</a>

HomeServlet.java (as callback URL)

Twitter twitter = new Twitter();
HttpSession session = request.getSession();

twitter.setOAuthConsumer(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
AccessToken accessToken = twitter.getOAuthAccessToken(
(String) session.getAttribute("token"), (String) session
.getAttribute("tokenSecret"));
twitter.setOAuthAccessToken(accessToken);

User user = twitter.verifyCredentials();

HomeServlet is your callback. Let say you have mentioned URL mapping of this servlet as /Home. So you mention http://.appspot.com/Home in callback field in your app registeration page at twitter. And this HomeServlet will be called. Now you have the user object to play with. See Twitter4J javadocs for more help.

WEB-INF/appengine-web.xml

<sessions-enabled>true</sessions-enabled>

You need to add this tag in you appengine-web.xml file that you are enabling the session.

So this was a tutorial, feel free to ping me on it. If you stuck somewhere. We will both look into it.

I also suggest following links to you people to must visit them. They helps me a lot in the understanding and the development. I will update this tutorial if got more things to discuss.

Helpful Links

Related Posts Plugin for WordPress, Blogger...
  • http://www.incomingit.com/blog spaboy

    Hello,

    Nice article, can you provide full code please? for ppl not used to appengine as me :)

    can you send it to mail?

  • http://www.pakzilla.com Tahir Akram

    Thanks for your comments spaboy!

    Hmm so you need code without GAE. But I think that will work best for any container. Except you dont need to worry about appengine-web.xml. Because session is already enabled. This is the only code that I have for Twitter4J implementation. Believe me the code which I provided will work well in any container :)

    If you have any ambiguity, let me know. I am just here.

  • http://www.incomingit.com/blog spaboy

    Not at all.. im planning to leanr App Engine. so the code for app engine would be ok.

    Thanks in advance

  • http://www.pakzilla.com Tahir Akram

    Ohh I misunderstood you. Ok you want the app code only for GAE. I learned making application in GAE from the following link. Its so easy. Just in few clicks you will have you application running on app engine. http://whyjava.wordpress.com/2009/08/30/creating-struts2-application-on-google-app-engine-gae/

    Just download the app engine plugin from their web. Make a new project and right click deploy on Google. Please just go through the tutorial. If you still find any issue let me know.

  • http://www.pakzilla.com Tahir Akram

    I also recomend you go through this tutorial. A must have to learn GAE. http://www.ibm.com/developerworks/java/library/j-gaej1/

  • chief

    thanx for sharing bro. :)

  • Chief

    thanx for sharing brother!!

  • http://www.pakzilla.com Tahir Akram

    You welcome Chief :)

    If you want to develop some Java based application and want to show others. Google App Engine hosting is the best free place to do it.

    Recommend this thing to other your fellows too who are developing their FYP in Java. Tell them to host online. Let their effort easily online somewhere. Hence it will not die in archives.

  • cetana

    Dear tahir
    Please tell me when call back from twitter to our site is get or post method
    And please clear for me that what kinds of 2 servlet in your exam and those code in what method inside servlet
    Thanks so much

  • http://www.pakzilla.com Tahir Akram

    cetana

    I have read your comments. I get back you shortly.

  • http://www.pakzilla.com Tahir Akram

    Hi cetana;

    When website opens. First hit goes to LoginServlet. This servlet get an OAuth token and put in session to be used further for call back servlet.

    And this servlet also prepares the URL to redirect user to Twitter website for authentication. You will see I added authUrl in request.

    request.setAttribute("authUrl", authUrl);

    When user clicks this link, authenticat from Twitter. And if authentication successful Twitter needs to call our call back url. Which we have given while registering our application.

    HomeServlet is basically our call back url. It will be called when user will be authenticated bu Twitter.

    And about your query that call back URL is get or post, I just look through my code and I have my logic in doGet method. I think we can pass parameters in query string if you want.

    Have your concerns has been cleared? Please let me know.

    We will go again.

  • Dev

    Hi,

    I have same issue with call back. I am not getting your this point, Could you please tell more on that how to implement that? . “if authentication successful Twitter needs to call our call back url. Which we have given while registering our application”.

  • http://www.pakzilla.com Tahir Akram

    Hi Dev

    I am writing a separate blog post on how we can register our app with twitter. To setup call back URL. With screenshots. Just hang on a sec.

  • http://www.pakzilla.com Tahir Akram

    Hello Dev;

    You can visit this post, if you have questions on how to register an app with Twitter and what the call back URL is. http://www.pakzilla.com/2009/11/23/how-to-register-an-app-with-twitter/

    Hope it helps. Let me know if you want to know anything.

  • Dev

    I got it thanks, but I guess I didn’t give callback URL while registering my application. I have one more question twitter has option of oauth_callback parameter i guess. So right now I am trying to provide callback at runtime in url, but its not working. I can do that right?

  • cetana

    Thank so much Akram, Your article is the most clearly and easy for implementation twitter oauth. I did success for twitter and going to do oauth for gmail carlendar and got stuck, wonder if u ever implement oauth for gmail?
    TO Dev: i thing u can modify your application account for twitter even change the url or change it from webapp to desktop app

  • http://www.pakzilla.com Tahir Akram

    Dev;

    I am happy that it helps. I am advancing in OAuth. And I didnt use oauth_callback yet. I will surely share here if I got work on it.

    cetana;

    Your comment has made my day. Well I have next task to use DWR with Twitter4J in Google App Engine. Nops I didnt use oauth for Gmail.

    Do you want use Google account for your authentication in app?

  • http://theAfricanCall.blogspot.com Savio

    Hi Tahir,

    Thank you for your tutorial! it really helped securing oauth authentication to twitter for the 1st time, but how do i make my GAE app have permanent Oauth to twitter, instead of manual intervention everytime? can you please help?

    Regards,
    Savio

  • http://theAfricanCall.blogspot.com Savio

    Hi Tahir,

    From a blog post by Jose in http://jeungun.wordpress.com/2009/09/03/quick-and-dirty-twitter4j-oauth-for-web-apps/#comment-52 i understand that i have to save the access token and the access token secret. but how do i get back the same access token everytime so that i don’t have to make the user manually allow my application access each time?

    i looked at all the methods to get the access token and it does not seem to have anything i’m really looking for. can you please help?

    AccessToken getOAuthAccessToken(RequestToken requestToken)
    Retrieves an access token assosiated with the supplied request token.
    AccessToken getOAuthAccessToken(RequestToken requestToken, java.lang.String pin)
    Retrieves an access token assosiated with the supplied request token and sets userId.
    AccessToken getOAuthAccessToken(java.lang.String token, java.lang.String tokenSecret)
    Retrieves an access token assosiated with the supplied request token and sets userId.
    AccessToken getOAuthAccessToken(java.lang.String token, java.lang.String tokenSecret, java.lang.String oauth_verifier)
    Retrieves an access token assosiated with the supplied request token.
    RequestToken getOAuthRequestToken()
    Retrieves a request token
    RequestToken getOAuthRequestToken(java.lang.String callback_url)

    Thanks!
    Savio

  • http://theAfricanCall.blogspot.com Savio

    Hi Tahir!

    I finally managed to crack it! thanks for your time in figuring this all out!

    I used the following function to set the access token and access token secret and it work well!

    twitter.setOAuthAccessToken(dataStore.getAccessToken() , dataStore.getAccessTokenSecret() );

    Thanks a lot!

    Savio

  • http://www.pakzilla.com Tahir Akram

    Hey Savio;

    I apologize, I cant reply you on time. You clicked me. This is what I have to do for my app. So accesstoken need to store in datastore. If user is returning user?

  • http://theAfricanCall.blogspot.com Savio

    yes tahir… so i store the access token and the access token secret…

    accessToken.getToken();
    accessToken.getTokenSecret();

    along with the username.

    so the next time i need to get info about the user/his feeds then i use the method

    twitter.setOAuthAccessToken and set both the token and the token secret and it does the trick – as i mentioned in my previous comment.

    Thanks for the help!

    Regards,
    Savio

  • Pingback: How to use and retain Twitter4J OAuth access token

  • http://sanjeev-kulkarni.blogspot.com Sanjeev Kulkarni

    Hi, Can you people share a working example of twitter with OAuth implementation? Because I had developed a application using basic authentication and now teitter no more supports this implementation I have to move to OAuth. So please share the one. Thanks.

  • http://www.pakzilla.com Tahir Akram

    Hi Sanjeev;

    You can see the related posts section of this posts. Or you can see Twitter4J tag for more posts about Twitter API.

    My current posts about developing with Twitter API are based on Twitter4J 2.0.x. I am upgrading my OAuth code on version 2.1.2. I will share my OAuth code here. As they have changed some classes and the OAuth way. So code need to be changed.

  • shubham

    Hi friends , Have nay idea to integrate Twitter with Android Application.

  • http://www.pakzilla.com Tahir Akram

    @shubham

    I never tried coding Twitter on Android, but I just googled and come up with this thread. Yusuke Yamamoto explained that Twitter4J works for Android too. You can try Twitter4J on Android. And let us know if it full filled your needs.

  • http://www.pakzilla.com Tahir Akram

    @shubham

    Further its mentioned on Twitter4J (http://twitter4j.org/en/index.html) website that it works on Android.

  • shubham

    Thanx friends for reply , I try all these things , I uesd twitter4j.jar also but i am not getting authentication even; After get authentication I want to jsut twit.
    Pls suggest if u have any idea.

    Thanx

  • http://www.pakzilla.com Tahir Akram

    The easiest way to just tweet from your application is following. Download latest Jar from their website.

    If you dont want to use OAuth.


    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance(twitterID,twitterPassword);
    Status status = twitter.updateStatus(latestStatus);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");

    Hope it will work.

  • wingdings

    aweosme , it worked , but the thing is i dont wanna do all this redirection work , how about just do it with RPC on gwt/gae ?
    i have been trying , but it did so not work , gave me some credential error (though my token and tokenSecret was right and so was both keys)

    so help , PLEASE, email me ,

  • Pingback: oAuth « Identity Management , SOA, Testing, Monitoring

  • Pingback: twitter4j | cg2p

  • http://www.fiufiuuu.com/ FiuFiuuu

    We are students from Federal University we are creatind a social for education, and we’ve used this article. Great post man! We want to share something interesting.

    “The call back URL will not be your localhost URL. It should be a valid web address.”

    I have a tip: We can edit our call back URL not as localhost, for exemplo: http://www.fiufiuuu.com/twitterlogin/callback

    And to have testability we can configure the “hosts” file, in linux or windows, to point to localhost, and we can test and debug localy before to deploy.

    Is this example we’ve put in the hosts file:

    —hosts file —————————
    127.0.0.1 localhost
    localhost:8888 http://www.fiufiuuu.com
    —————————————–

  • http://www.pakzilla.com Tahir Akram

    Hey FiuFiuuu; Thanks for this tip. It will save time and will fast the development. Really helpful.

    Cheers.

  • David

    The following article give you an example using Twitter4J and describe in depth the process to register your application.


    Twitter application using Java

  • http://www.etmmobile.com Vantu

    Hi my friend
    when i run code
    twitter.setOAuthConsumer(Constants.CONSUMER_KEY,
    Constants.CONSUMER_SECRET);
    RequestToken requestToken = twitter.getOAuthRequestToken();

    it show error Acess Token adreay available . please help me

  • http://www.pakzilla.com Tahir Akram

    Hi Vantu

    If you can share more detail… the exception trace in detail.

    It will be helpful to debug the problem.

  • Ghanshyam

    i dont have valid web address to specify as callback URL , so at the time of Registration i kept it blank , now i have problem that how to come back after user valid authorization on my application. tell me a way so i can come back to my application and can execute servlet to get user object.

    Thanks
    Ghanshyam Maliwal

  • Ghanshyam

    Means to ask Is there any way so we don’t specify callback URL at the time of Application Registration instead of this we provide callback URL with request object while user click on link to go to twitter account. so through this callback URL user can come back to my application . For your Knowledge i am creating this Application using Struts Framework

  • http://www.learnonly.com/ Learnonly Heart

    can give full code for non techancal people

  • Femina Ernest

    Im using twitter4j and im trying ur code. but getting error at “Constants” …so 
    for constants what import should i use? 

  • Abc

    Hay dude Twitter() is an interface and u have insensate it 
    it is giving error!!!