www.codinghillbilly.com   kyle.baley.org  Subscribe / Contact
 
 
 
 
LATEST POSTS
Friday, March 05, 2010

Google Web Toolkit has proven an interesting beast to code with. It’s not every web framework that encourages you to use passive view so strongly. That’s thanks partially to gwt-presenter which makes it pretty easy for views to be stupid. In most cases, the presenter even handles wiring up event handlers for the widgets.

Here’s a small excerpt of a view:

public class LiquorStoreListView extends Composite implements LiquorStoreListDisplay {

   Anchor addStore = new Anchor( "add store" );

   public LiquorStoreListView( ) {
      FlowPanel panel = new FlowPanel( );
      panel.add( addStore );

      initWidget( panel );
   }

   public HasClickHandlers getAddStore( ) {
      return addStore;
   }
}

This is missing a bunch of extraneous stuff as is the presenter below:

public class LiquorStoreListPresenter extends WidgetPresenter {

   LiquorStoreListDisplay display;
   EventBus eventBus;

   @Inject
   public LiquorStoreListPresenter( LiquorStoreListDisplay display, EventBus eventBus ) {
      this.display = display;
      this.eventBus = eventBus;
      bind( );
   }

   @Override
   public void onBind( ) {
      display.getAddStore( ).addClickHandler( new ClickHandler( ) {
         public void onClick( ClickEvent event ) {
            Window.alert( "Adding a new store" );
         }
      } );
   }
}

The magic is in the use of interfaces for the widgets. In this case, the Anchor widget implements HasClickHandlers which means the presenter doesn't need to know anything about the widget except that it implements a method, addClickHandler.

This falls apart a little when you have more dynamic user interfaces though. For example, what if each liquor store in our list contains an edit and delete button? Maybe we can expose them as a couple of ArrayList objects, I suppose. But that leads to much madness. And by "madness", I mean the angry kind, which isn't nearly as fun as the crazy kind where you're allowed more latitude at the daily stand-ups.

The reason exposing the edit and delete buttons as an ArrayList to the presenter is icky is because you need to figure out which row was selected. Which leads to some pretty funky implementations, some of which require you to maintain a separate list of click handlers and/or domain objects on the presenter which need to be kept in sync with the view.

Instead, I've started delegating a tiny bit more responsibility to the view. That is, it will wire up the click handlers which in turn, fire off custom events that have more useful data in them.

Here's a sample method in the view:

public void addLiquorStore( LiquorStore store ) {
   int lastRow = storeTable.getRowCount( );
   storeTable.setText( lastRow, 0, store.Name );
   storeTable.setText( lastRow, 1, store.Address );
   Anchor edit = new Anchor( "edit" );
   edit.addClickHandler( new EditStoreClickHandler( store ) );

   private class EditStoreClickHandler implements ClickHandler {

      LiquorStore store;
   
      public EditStoreClickHandler( LiquorStore store ) {
         this.store = store;
      }

      public void onClick( ClickEvent event ) {
         eventBus.fireEvent( new EditStoreEvent( store ) );
      }
   }
}

Then in the presenter:

public void onBind( ) {
   // ...

   eventBus.addHandler( EditStoreEvent.TYPE, new EditStoreEventHandler( ) {
      public void onEditStore( EditStoreEvent event ) {
         LiquorStore store = event.getStore( );
         // Get the store data and display it
      }
   } );
}

May seem like more work but I like the separation a little better. Alternative is to store the store ID in a hidden field and do some DOM manipulation to get it. But I always feel dirty if I have to do that in GWT.

Kyle the Impassive

Friday, February 19, 2010

I didn’t necessarily mean to piggyback off Greg’s two posts on ORMs but c’mon, what’s a hillbilly to do when he perpetuates such negative stereotypes? I mean, before you start knocking it, have any of you *tried* kissing your sister?

He also has some blather in there on RDMSs and ORMs. So I suppose I should hide my indignation behind something technical.

We’re using BigTable for our project by way of Google App Engine. The decision to use it was pretty easy once we landed on GWT as our platform. The integration ‘twixt GWT and App Engine is pretty seamless and hey, App Engine uses Big Table.

I’m glossing over the dozens of times we’ve second-guessed ourselves since making the decision though. The most recent was just yesterday as a matter of fact when my friend expressed a couple of concerns:

  • How do we back it up?
  • How do we do ad hoc reports against it?

Over the course of the conversation, these boiled down to: How can we work with BigTable in a way we’re used to with RDMSs?

The inevitable option came up. Maybe we shouldn’t use BigTable. Maybe MySQL is more suitable if we’re unsure. That means moving off App Engine though and we like what we’ve seen so far with it.

It was a bit of an uncomfortable conversation actually and this was between two very seasoned developers who have never shied away from new tech. I think the reason for the awkwardness though is that we aren’t dealing with someone else’s money. This is a startup so it’s a decision that he and I are going to have to live with.

In the end, being seasoned developers, we recognized that moving to a new development platform will just substitute one set of problems with another. For basic transactions (I hesitate to say OLTP because that will imply I know more about the term than I do), like getting some objects and saving them again, BigTable just plain works. There’s no ORM behind the scenes to map your data structure to the domain model. You create a User and you save it. Any relationships are automatically dealt with by some magic that is buried in the documentation somewhere, I’m sure. It really is like working with an ORM without actually having to deal with the mapping.

As for our two questions above, we have a tentative solution that I still like a day later and it will solve both problems. Let’s take the second one:

How do we do ad hoc reports against it?

See this is where RDMSs shine, I think. So breaking down the question we get: How can we get the benefits of BigTable for transactional stuff and the benefits of RDMSs for reporting and ad hoc querying?

Funny how CQRS starts to make sense when you have the right problem staring you in the face. We’ll have a separate relational database for querying. As requests are sent to BigTable, we’ll also dump them out to another service elsewhere that queues them up to be processed into the relational database.

This also addresses our first question:

How do we back it up?

The nice thing about this approach is that we now have our offline backup though of course, backing up is only half the solution. We also need some way to restore BigTable from our relational database easily. But the idea seems sound enough even if the mechanics may prove otherwise.

Maybe this sounds unduly complicated. It really doesn’t to me. App Engine and BigTable offer a lot of advantages. They solve problems I don’t want to deal with, most notably, scalability. The ones they introduce, backing up and querying, by contrast, are pretty simple. Besides which, I’m scheduled for Udi’s course in a couple of months anyway.

And for the record, I don’t have any sisters. Just three adventurous brothers.

Kyle the Restored

Tuesday, February 16, 2010

Almost three years ago to the day, I concluded a post with this:

I hate security and all software and hardware related to it, including but not limited to: anti-virus, spam, phishing, SSL, permissions, LDAP, NTLM, forms authentication, SecurID tokens, VPNs, swipe cards, PIN numbers, security deposits, car alarms, bike locks, and cell phones for seven-year-olds.I don't like that the major upgrade to Windows XP was a firewall that broke a bunch of apps. And that among IE7's features is not to let me into websites because I'm not smart enough to figure out if they're dangerous. And that Vista's main differentiation from XP is that it's harder to play my music. I will concede, however, that retinal scanners are pretty cool.

Now, three years later and my position has changed slightly in that now I also don’t like OAuth, RSA, salts, Kerberos, MD5, SHA, IPSec, OpenID, HTTP sessions, cookies, cross-site request forgery, fingerprint scanners, parental controls, deadbolts, my mother’s maiden name, my favorite pet, the name of my elementary school, and “forgot my password” links that all but announce my password on Twitter. Again, though, retinal scanners rock.

With that background, today’s topic is authentication with Google Web Toolkit.

In the .NET world, I had my head somewhat wrapped around authentication. Or rather, I knew which code to cut and paste from previous apps to make it work in new ones. But having thrown myself headlong into GWT, I’ve had to actually research the concepts. A little.

With an AJAX application like one built with GWT, there are actually two scenarios that require authentication:

  • Navigating to a page
  • Performing an action on a page

Navigation has traditionally been fairly easy for me to work out. You fiddle with the web.config, add a login page, toss around a FormsAuthenticationTicket or two and call it a day. With GWT, this needs to be done via gwt-presenter. But I’ll leave it at that for now because I haven’t actually got around to doing that part of the authentication yet.

Instead, I’ll focus on the second item: performing an action on a page. In GWT, I’m using gwt-dispatch, a command pattern implementation. It’s nice in that it provides a centralized interface for making RPC calls ‘twixt client and server. Nicer still is the latest version on the trunk which includes support for securing these calls.

As David Peterson points out in this thread, there isn’t much you need to do in order to add security to your command calls. That said, it isn’t altogether obvious to a Java greenhorn how to implement it. So forthwith are my current thoughts in as plain English as I can realistically make it.

The main issue I had when researching all this is that it seemed fairly academic. There is talk of sessions and session IDs and I couldn’t make the leap from that discussion to what I really wanted: to log in to the application. As I lamented on the OpenRasta forum, I can get a username and password from the screen, validate it against a database, and create a random session ID. What happens after that is still a little foggy.

So here is the workflow as I see it now:

  • User enters username and password and clicks submit
  • Login command is created and sent/dispatched to its appropriate handler on the server
  • LoginHandler validates the user, creates a user object, and dumps it into the HTTP Session
  • Server also creates a random session ID and dumps it into an appropriately-named cookie.
  • Server returns login success

Next, the user performs some action that requires authentication:

  • Client creates an appropriate command and sends it to the server
  • The session ID is attached to the command and sent to the server
  • The server checks to see if the action being performed requires authentication.
  • If not, it executes the action
  • If so, it checks to see if a user has been added to the session. It also verifies that the session ID it received matches the one it generated earlier (by also checking the cookies)
  • If the checks fail, throw an InvalidSessionException. Otherwise, execute the action.
  • Back on the client, we use a custom AsyncCallback class that specifically checks for InvalidSessionException. If it catches one, we raise a Logout event which is configured elsewhere to redirect to the login page.

The session ID check seems kind of superfluous on the surface. But from what I gather, it’s necessary to prevent cross-site request forgery attacks. As far as I can tell, it’s not used for any other purpose.

The vast majority of this is taken from various sources and I hope I remember them all. First is the Hupa, a web mail app written in GWT. Much assistance has come from the guy behind this site, which is shaping up to be one of the best tutorials I’ve seen in either Java or .NET. A good chunk of the explanation is from this post and I should note that most of the code in it has been incorporated into gwt-dispatch already.

I had planned to incorporate some code in here but didn’t for a couple of reasons. One, this is kind of wordy and I’d rather do a follow-up that is more code-centric. Two, I haven’t finished the code. For now, the act of typing all this out has served it’s purpose in that it’s helped clarify things in my head. The nice thing is that much of this is already incorporated into gwt-dispatch already. I’m still a little fuzzy on where to implement the parts I need to implement (e.g. where do I check to see if an action can be performed anonymously?) but I have something that works. Which will serve as the basis for future posts.

Kyle the Dispatched

Wednesday, February 10, 2010

I’m in week four of my Google Web Toolkit adventure and things are heating up nicely. I’ve already switched to IntelliJ and back to Eclipse at least once (not really counting the two times I switched in my head while I was laying in bed; let it not be said that being spoiled for choice is always a good thing).

Reason I’m currently sticking with Eclipse: it seems better suited for GWT development. As an editor, IntelliJ rocks for .NET/ReSharper developers. All the shortcuts are familiar and things seem more organized and intuitive. Generally speaking, Eclipse feels like an IDE developed by committee, which it kinda was from what I’ve read. But the GWT and Google AppEngine plug-ins for Eclipse are pretty solid and there’s no confusing terminology around libraries and facets and artifacts and modules like there is with IntelliJ. After all, I’m just a .NET developer.

The gwt-presenter library has been a godsend in the short time I’ve been on the project. Its implementation of MVP is cleaner than my kids’ hides after they’ve had a good whoopin’. Unlike the ASP.NET version of MVP I’ve used over the years, this one has a very decoupled link ‘twixt presenters and views. Communication is managed through dependency injection to wire up view interfaces to their implementations and through an event bus, which comes standard with the gwt-presenter libmockuprary.

Say you have a link in a left sidebar that users click to launch the Settings page in the main content window. With gwt-presenter, the workflow to wire this up is as follows:

  • In the left sidebar’s presenter, attach a click handler to the Settings link exposed as a method on the Display interface, which the view implements. (gwt-presenter appears to use a Passive View approach to MVP.)
  • In the click handler, raise a ShowSettingsWindow event on the event bus.
  • Elsewhere (for example, in the main AppPresenter), we register a handler on the event bus to listen for this event and swap out whatever is being displayed in the content window with the SettingsPresenter.

Here’s where it gets even better. I don’t even need to create a ShowSettingsWindow event. gwt-presenter has history management built-in. This means that in order to navigate to a new “place” in the app, all I need to do is raise a PlaceRequestEvent. Furthermore, I also don’t need to handle the event anywhere. The PlaceRequestEvent includes a parameter indicating the name of the place you want to navigate to. (I believe I’m simplifying but then, I’m a simple person.) As long as that’s mapped to the SettingsPresenter (typically, exposed as a property on the presenter itself), gwt-presenter handles all that for you including adding it to the browser’s history.

So to sum up, out of the box, gwt-presenter gives you:

  • A view and presenter decoupled thanks to dependency injection and a built-in event bus
  • navigation between views
  • browser history management and bookmarking

What makes this all the more amazing to me is something to which I alluded in the previous post: it’s nearly impossible not to use all of this in a GWT application. Yes, gwt-presenter is optional but it’s not optional the way ASP.NET MVC is optional to WebForms developers. The GWT documentation itself encourages the use of it as well as an event bus.

Note that I’m being sparse with implementation details. That’s because there’s no point. The absolute definitive guide for this is already underway over at Andreas Borglin’s pad. As much as I love David Chandler’s articles (and believe me, they’re golden), Andreas’s step-by-step guide to the various pieces, along with detailed source code for each step, is the type of teaching guide I can only aspire to. The purpose for this post is two-fold:

  • Get people over to Andreas’s site to join in the awesomeness
  • To help clarify my own thoughts on how this all works together.

As always, if any of this is helpful or interesting to you, that’s not my fault.

Kyle the Presented

Wednesday, February 03, 2010

The hillbilly be all Java’d up these days. For coming on three weeks, I’ve been the lone developer on a project based on Google Web Toolkit. It’s a web framework (naturally) that allows developers to build applications in Java and compiles it down to JavaScript, CSS, and HTML. Scoff all you want, if it were any other company behind it, I’d probably be right there with you.

We considered quite a few technologies before landing on this one. We went through Ruby, Sharp Architecture, Open Rasta, Moo Tools, and probably several others. I can defend ending up Google Web Toolkit privately if you want but putting the thought process up in a public forum is going to lead to comments that I’m too tired to moderate these days. And yes, I’ve heard of Script #, too.

Coming at this from a .NET developer’s standpoint has been interesting. It’s surprising how much we take for granted in our IDE, for example. I’m still meandering my way through the keyboard shortcuts in Eclipse (after a brief fling with IntelliJ IDEA). One thing I’d really like is a keyboard shortcut for the GWT Compile button, which currently is available only via a toolbar button or a context menu, as far as I can tell. Was happy to find a VIM plugin for it too that works as advertised.

Not sure if this applies to Java in general but within the confines of the Google Web Toolkit, the ecosystem is freakin’ phenomenal. The documentation page alone encourages unit testing and the use of an MVP architecture. Once you start reading about it, you can’t help but stumble on a number of other projects:

  • gwt-presenter: A passive view implementation for GWT
  • gwt-dispatch: A command pattern implementation for GWT
  • Guice: Google’s dependency injection framework
  • Gin: A dependency injection framework for the client part of GWT

The shocking thing from a .NET perspective is that these concepts are just sort of assumed. There’s little debate on whether dependency injection is necessary or whether passive view is overkill. Someone watched a presentation from Google IO last year, whipped up a command pattern project based on it, and lo! the people said it was good. Between support for Hibernate and the App Engine data store, I think people would look at you bug-eyed if you even suggested writing your own data access layer.

The downside to all this as that the tooling seems to be several steps behind what I’m used to in the Microsoft world. It’s still too early to make a fair comparison but even after digging a little deeper into Eclipse, I can’t imagine being quite as productive as I currently am in Visual Studio. Yes, there’s also IntelliJ but our anecdotal evidence suggests that neither Java IDE is seen as a de facto standard. For the moment, I’m sticking with Eclipse simply because all the documentation refers to it and the GWT and App Engine plug-ins for it work out of the box.

Couple of final shout-outs to two blogs that have been invaluable during the learning curve phase. First is Hive Development (currently featuring two posts on how to unit test MVP applications in GWT). Second is TurboManage, whose sample code is more detailed than many apps I’ve written.

Anyway, it’s been an interesting couple of weeks.

Kyle the Decaffeinated

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Copyright © 2010 Kyle Baley. All rights reserved.
 
CATEGORIES
.NET General (18) alt.net (4) altnetconf (9) ASP.NET AJAX (40) ASP.NET MVC (29) Bahamas (1) Bahanet (9) BDD (1) Brownfield (18) Career (9) Castle (1) Code coverage (1) Coding Style (6) Communication (1) Community (18) Conscientious Coding (34) Continuous Integration (11) dasBlog (12) Development (16) DevTeach (4) Domain (2) Environment (4) Estimating (1) Featured (14) Flamingo (10) Games (1) Google App Engine (2) GWT (5) Hardware (6) Java (1) Javascript (7) Linq (2) Livelink (6) Lucene.NET (2) MbUnit (1) Metrics (1) Miscellaneous (24) Mocking (4) NAnt (4) NHibernate (12) NInject (1) Office (3) Office Development (6) Open Rasta (1) Patterns (5) Presenting (13) Professional Development (15) Refactoring (10) ReSharper (11) REST (2) S#arp Architecture (5) Security (3) Software (11) Sundry (18) TDD (19) Tools (21) User Interface (5) Utilities (8) Visual Studio (8) VSTO (1) Web development (12) Windows (3) Working Remotely (16) Workplace (3) Writing (4)
 
LATEST POSTS
 
POPULAR POSTS
 
 
ARCHIVE