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

You May Also Like

44 Comments

  1. 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.

  2. 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.

  3. 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.

  4. 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

  5. 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.

  6. 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”.

  7. 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?

  8. 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

  9. 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?

  10. 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

  11. 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

  12. 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

  13. 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?

  14. 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

  15. 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.

  16. 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.

  17. @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.

  18. 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

  19. 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.

  20. 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 ,

  21. Pingback: twitter4j | cg2p
  22. 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
    —————————————–

  23. 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

  24. 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

  25. 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

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

  27. hi, I implemented this code and I am getting the callback correctly.

    From my callback URL I am getting this error , Please help me.

    401:Authentication credentials (https://dev.twitter.com/docs/auth) were missing or incorrect. Ensure that you have set valid conumer key/secret, access token/secret, and the system clock in in sync.
    The screen name / password combination seems to be invalid.

    I had already set the correct consumer key with Application type as Read, Write and Access direct messages in twitter settings.

Leave a Reply to Dev Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.