logo sudovi.com
- X /home/ryan/Groovy, Matisse & Twitter -- Jul 29, 2008 10:20am

Announcing RyTwitter

I was never much of a Twitter user, that is until I had friends that started using we began following each other. Having said that, I'm clearly not a very popular Twitter(er?!?) but its still fun to use. Since I'm really starting to get into the whole Web Service type of thing, I took a look at the Twitter API and after a few command line examples, (right from their documentation) I thought it'd be pretty easy to write a Swing App to update my Twitter status.

I'll say, with the help of Groovy that it wasn't all that bad, but it wasn't as easy as it should have been. Nonetheless, after a little googling and just a couple hours coding, "RyTwitter" was born. Before I get into it though, let me just say that this is not at all intended for any "serious" use at all it does is update your status. It doesn't pull down my friends' statuses or do anything else with any wow factor. Nor does it look polished. I went with the the default NetBeans desktop libraries and didn't bother with skins of any sort, thought I'll probably add something for the heck of it. That being said, lets get to it:

NetBeans' GUI Builder (Matisse) makes it _very_ simple to create a gui and the skeleton code that it creates isn't half bad. I would recommend however that you change your variable names if you intend to be interacting via code with the GUI at all. Having things named jTextField1 and jTextField2, etc could confuse you quite a bit. Since this really isn't a tutorial I won't get into how to use Matisse at this point in time. Suffice it to say that it really is a drag 'n' drop GUI builder akin to *gasp* VB in that you just drag your components to the canvas, click on them to modify their different properties and place them precisely where you want them. Adding event handlers to these components is pretty simple and once you've added a handler, the IDE takes you to the code where you will actually *DO* something with that event.

Once my GUI was created, it was time to wire things up on the backend. Those of you that have been here before know that I'm not big on heavy handed traditional Java and luckily Matisse generated the majority of that heavy handed code with the exception of the event handling code that I added and another core piece that would come to bite me in the butt a bit later.

Previously I had written some Groovy code to make web service calls (POST, GET, PUT, DELETE) so I enabled Groovy in my project and then created a jar file of my web service layer and imported that into my project as well. Since that was so easy, I decided to make as much of my backend in Groovy as I could, including my TwitterUser, TwitterMessage and my service layer objects as well. All Groovy code. This was my first real attempt at getting Groovy and Java to play together. Everything went pretty much as expected with the exception of code completion on my Web Service libraries. Using control space brought up the right libraries, etc, but the method names weren't very clear at that point. For instance, I have a QueryString object that has an add method. Using control space in an effort to bring up that add method resulted in a list of options that looked like: class$groovy$lang$MetaClass -- not very clear. I wound up opening my source for that library in a text editor and used that as my reference.

Once I had all my objects talking to my services and my GUI wired up to that, it was time to test again. (I had been testing all the way...unit testing...*meh* not for this, I was just playing...). I was presented with my GUI, filled out my username, password and message and clicked update. In my NetBeans console, I notied that twitter was returning a 401, Access Denied and the thing would just sit there.

Before I go further, lets talk briefly about the Twitter API: using something like curl you can do this from the command line: curl -u username:password -d status="You message here" http://twitter.com/statuses/update.xml -- what that does is send your username and password combination to twitter, authenticates you and allows you to update your status. Woohoo! Easy right? Not so much.

I thought I was smart and that I just needed to send the username and password combination as params on a POST request to Twitter and I'd get logged in and my message would be updated. Not so fast...even after RTFM I still didn't realize what HTTP Basic Auth was really doing.

Apparently you make your POST request and the server sends back a 401 Not Authorized message. If you were doing this in a browser (and if the service allowed GET requests) you'd then be prompted with a Username/Password dialog box to fill out and then you'd be let in. (*DUH* now I remembered what Basic Auth was...). What Java didn't know was how to respond to that...at least not until I had to tell it.

So basically, my POST request received a challenge response, but didn't know how to handle it. What now? I was confused, and sort of upset that this was TWitter's authorization/authentication solution. *YUK*

It turns out the answer lies in something introduced in Java 1.2 -- java.net.Authenticator. At first, as most Sun documentation, it wasn't exaclty clear to me how to tie this in to my code and the code examples I found on the net were _very_ hard to read. After some thought, and a wild guess or two...I figured it out. Again, before I get into it, lets take a step back:

Authenticator returns a PasswordAuthentication object that actually stores the credentials to be used when met with this typ of challenge response. Your application makes the call, gets challenged and the Authenticator then responds with the credentials and performs the request again. Actually kind of nifty. My only worry was mucking up my Groovy code.

Here was my solution: I have my GUI (RyTwitterView), my UpdateService(TwitterUpdateService), and now something called TwitterAuthenticator. TwitterAuthenticator extends java.net.Authenticator and has a String username and a char[] password. It has only one method which returns a java.net.PasswordAuthentication object. My TwitterUpdateService now has a TwitterAuthenticator property. My GUI sets up the TwitterAuthenticator and passes it to my TwitterUpdateService and sets that as the default Authenticator. Now when I run doUpdate() from my service, when the challenge comes back, the Authenticator uses the credentials returned to authenticate, the request is repeated and my status gets updated. At the time I felt like this was a major PAIN, but in the end...it wasn't so bad. Authenticator feels like a bit of a black box, but it worked.

Having read all that, perhaps some (Groovy)code would help?

class TwitterUpdateService {  // this is Groovy
 TwitterAuthenticator auth
 ...
 ...
 public doUpdate() {
  Authenticator.setDefault(this.auth)
  ...
  post.doRequest()
 }
}

class TwitterAuthenticator { // this is Groovy
 String userName
 char[] password
 PasswordAuthentication getPasswordAuthentication() {
  return(new PasswordAuthentication(userName, password)
 }
}

class RyTwitterView { // this is Java
 ...
 ...
 private voide updateButtonActionPerformed(java.awt.event.ActionEvent evt) {
  ...(getting data from fields on form)
  ...
  TwitterAuthenticator auth = new TwitterAuthenticator();
  auth.setUserName(userName);
  auth.setPassword(password.toCharArray[]);
  ...(some validation)
  TwitterUpdateService updSvc = new TwitterUpdateService();
  updSvc.setAuth(auth);
  ...more stuff
  updSvc.doUpdate();
 }
}



With that, my work was done! My very own Twitter Status client in very short time. In conclusion, the use of Matisse to create the GUI saved a ton of time and the use of Groovy code on the backend made my life alot easier by reducing keystrokes, lines of code and increasing readability. In future projects, I'll be trying to plug Groovy code whenever and wherever it makes sense to do so. It was a learning experience for me to finally get to ties Groovy and Java objects together and watch them work seamlessly. NetBeans has come a very long way and will certainly become my IDE of choice when working with Swing. I'm intersted in seeing how well it works for Grails apps as right now GEdit is still my editor of choice in that arena. Lastly, I am throwing up a screenshot of RyTwitter and the zip file of the app itself. There's no source code in it at the moment, but if enough people want to take a look at it, I can put it up.

Screentshot

RyTwitter.zip

Thanks for stopping by.


~
:wq!


- X Add Comments
All Fields Req'd (I won't display your email)
Do not use "http" or "href" in your comment.
You will be blocked.

Bold: [b]your bold text[/b]
Italics: [i]your italic text[/i]
Underline: [u]your underlined text[/u]
Link: [mylink]http://wherever[/mylink]

Copyright 2008 -- all rights reserved