Tuesday, 25 August 2009

Paying The Bills

A distinct lack of activity on the blogging front lately. This is because I've been (a) moving house and (b) actually enjoying myself at work! ;-)

As Tech Lead on a brand new project, I've been writing a web app using Spring MVC, Freemarker + Hibernate and I thought I would share a few thoughts. I should start by saying that it's been nowhere near as easy as Grails, GSP + GORM, but nonetheless, it's a big improvement on the 'bad old days' of Java web app development.

To be honest, although Spring MVC is both powerful and flexible, I've always found it a little fiddly in the past. However, this time I decided to use annotation-driven controllers and these were way easier to work with than the MultiActionController I've used before. All you need is something like this in your context:
<context:component-scan package="com.royale.sam.web.controller">
And then you can annotate your controller class like this:
@Controller
@RequestMapping(method = RequestMethod.GET)
public class PageController {

...

@RequestMapping(value={"/page.html", "/item.html"})
public ModelAndView pageHandler(HttpServletRequest request, HttpServletResponse response) {
...
}
}
And that's it! Using this technique you can group handler methods in one controller (much like you can in Grails) which makes it easier to reuse domain logic and leads to a well organised application. We found this was particularly useful when implementing handlers for our AJAX functionality.

Freemarker was also pretty good, although - possibly because it's application agnostic - we found that it didn't support a number of features that you take for granted when using JSP. (In fact, I would've used JSP, but requirements dictated that we used a templating language.) For example, we couldn't find an easy + reliable way to get the context path, so we ended up introducing a servlet filter that made this information (and more) available to every page in our app. We also steered clear of using taglibs in our Freemarker templates, preferring to write our own directives.

And Hibernate was Hibernate. Always trickier than you expect to set it up, but once it's done, you generally don't have to worry about it anymore.

Monday, 20 April 2009

Pixel Art

Something I am starting to realise is that pixel art is hard and animated pixel art is even harder. Not just hard, but extremely time consuming too. To give you an idea of how much work goes into these things, take a close look at the forward-facing frames for our protagonist ...

I'm telling you, the guys who did Metal Slug should get some kind of medal.

Pygame Update

I recently realised that I haven't blogged about my Python/Pygame efforts in quite a while, so I figured it was time for an update. The good news is, my lack of blogging is not reflected by a lack of development, so there's quite a few new features - so many, in fact, that it's probably best if I just post a video ...



So here we can see a couple of maps designed with my very own level editor, an animated main character, a scrolling background, the ability to seamlessly walk off one map and onto another, animated features (eg. flames), pickups (eg. coins) and movement correction (ie. note the way the little fella 'slides' off obstacles that are blocking his way).

If anyone's interested, I created this video by running gtk-recordMyDesktop against the Pygame window and converting the resulting .ogg with mencoder:
mencoder out.ogg -oac lavc -ovc lavc -lavcopts abitrate=160 -o rpg-world.avi
I have no idea what most of that means, but the quality has turned out okay!

Wednesday, 8 April 2009

Groovy comes to Google App Engine

It would seem that my reservations about Google App Engine may soon be no more. I haven't had chance to try it yet, but Google App Engine now supports Java!

Better still (for fans of Groovy like myself) work has been going on behind the scenes to ensure that Groovy is also supported - see here and here. In fact, Guillaume Laforge (creator/inventor of Groovy) has already written a Google Maps / Flickr mashup with it.

:-D

Monday, 30 March 2009

Being Groovy

Nothing spectacular here, but it's interesting to see just how nice and simple Groovy can be. I have a page in my app where the user can tick a checkbox for each of their networks to say which networks should receive a status update. The request looks something like this:
newStatus=hello%20world!&network1=on&network2=on&network3=on

Grails supplies this as a map called params, but what I really want is a simple list of network ID's. Here's how I do it:
def networkIds = params.findAll({ key, val ->
key.startsWith("network")
}).collect({ key, val ->
Integer.parseInt(key[7..-1])
})

Basically, I'm chaining two calls together - findAll + collect - that both accept a closure. I'm using findAll to filter out any entries that don't start with 'network' and then collect to convert the resulting map into a list of ints. And not an iterator in sight!

Tuesday, 24 March 2009

Why Grails Is Good

Obviously I can't say that Grails is the best thing since sliced bread and then not present some evidence to support my claim, so here's a specific example.

In my application I have a Network domain class and some other domain classes that extend it - TwitterNetwork, FacebookNetwork, etc. I wanted to handle the CRUD functionality for these classes in a single controller, but keep the forms separate. Having auto-generated the controller + views and then deleted the stuff I didn't want, here's the structure I ended up with:
- grails-app
- domain
- Network.groovy
- FacebookNetwork.groovy
- TwitterNetwork.groovy
- controllers
- NetworkController.groovy
- views
- network
- list.gsp
- facebookNetwork
- create.gsp
- edit.gsp
- twitterNetwork
- create.gsp
- edit.gsp
Out of the box, the default list action just works:
def list = {
if (!params.max) params.max = 10
[ networkInstanceList: Network.list(params) ]
}

As do the delete, save and update actions.

All I have to do now is get the edit and create actions to use the correct view, depending on the network type. To do this I use the class name to determine which view to use. For example, here's my edit action:
def edit = {
def networkInstance = Network.get(params.id)
renderEditForm(networkInstance)
}

def renderEditForm(network) {
def map = [ networkInstance : network ]
def viewPath = getViewPath(network)
render(view:"/${viewPath}/edit", model:map)
}

// derive the view path from the given network instance
def getViewPath(network) {
def networkName = getName(network)
networkName[0].toLowerCase() + networkName[1..-1]
}

The great thing is, I know that will work because by convention Grails will put the views for TwitterNetwork in the twitterNetwork folder and the views for FacebookNetwork in the facebookNetwork folder. It then becomes a simple case of taking the class name and making the first character lower case.

I use the same principle for my create action:
static networks = [ "twitter" : TwitterNetwork,
"facebook" : FacebookNetwork ]

def create = {
def networkInstance = createNetwork(params.type)
networkInstance.properties = params
renderCreateForm(networkInstance, params.type)
}

// create a new network instance of the given type
def createNetwork(networkType) {
if (networkType in networks.keySet()) {
def clazz = networks[networkType]
return clazz.newInstance()
}
}

... etc

And that's it! Full CRUD functionality for a set of polymorphic domain classes in a few lines of code - most of which were auto-generated by the framework. :-)

Wednesday, 11 March 2009

Is Grails The Answer?

I certainly think so. Over the last few years, I've used a variety of Java web frameworks such as Struts, Spring MVC + Tapestry and various combinations of Spring, Hibernate, JPA + EJB. Before all those things came along, I even tried my hand at JSP's, vanilla servlets + JDBC. I got some decent results out of most of those frameworks, but at the same time, it was hard work and productivity wasn't very high on the agenda. However, once things like Rails + Django appeared on the scene, I started to wonder if I should be using Java in the first place? These new frameworks made use of more dynamic languages - Ruby and Python - and promised short development cycles and extremely high productivity.

But, having spent the best part of ten years becoming a Java expert, moving to an entirely new platform seemed like a very big jump - particularly in the case of Ruby/Rails. After all, the JVM is (in my opinion) one of Java's biggest strengths - if only there was an easier way to tap that potential. Enter Groovy + Grails! I'd been following Groovy pretty closely for a while and really liked the look of it, eg. its extensive use of closures. I was also aware of Grails, but the name put me off slightly - it just seemed to be shouting "me too!" a little too loudly for my liking. But following my disappointment with Google App Engine, I decided it was finally time to take the plunge.

I needn't have worried. Quite simply, Groovy + Grails is the best web framework I have ever used in any language. After just one day (which included frequently referring to the documentation) I had full CRUD functionality for a set of polymorphic domain classes. Following that, adding an Authentication Filter was a breeze, creating a Custom Tag Library was incredibly easy and even Ajax Integration (so often where complexity starts to creep in) wasn't too unpleasant. And here's the best part ... all these features build on my existing knowledge of Servlets, Spring, Hibernate, etc, so I'm not learning a whole new technology stack from scratch.

After three days I had an application that was every bit as functional as its Google App Engine equivalent, which took a similar amount of time. I'll admit that I haven't strayed too far from the golden path, but so far, all the signs are extremely encouraging. There's plenty of support out there and the user community is extremely active. I've also read reports of companies using Grails for real-world sites, which is more than some of the latest frameworks can boast. I'll keep you posted ...