Tutorial: Java based Twitter App on Google App Engine

October 3rd, 2009 by Tahir Akram Leave a reply »

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

23 comments

  1. spaboy says:

    Hello,

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

    can you send it to mail?

  2. Tahir Akram says:

    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.

  3. spaboy says:

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

    Thanks in advance

  4. Tahir Akram says:

    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.

  5. Tahir Akram says:

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

  6. chief says:

    thanx for sharing bro. :)

  7. Chief says:

    thanx for sharing brother!!

  8. Tahir Akram says:

    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.

  9. cetana says:

    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

  10. Tahir Akram says:

    cetana

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

  11. Tahir Akram says:

    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.

  12. Dev says:

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

  13. Tahir Akram says:

    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.

  14. Tahir Akram says:

    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.

  15. Dev says:

    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?

  16. cetana says:

    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

  17. Tahir Akram says:

    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?

  18. Savio says:

    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

  19. Savio says:

    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

  20. Savio says:

    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

  21. Tahir Akram says:

    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?

  22. Savio says:

    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

Leave a Reply