Monday, December 12, 2011

JKstat at Play!

The Play framework seems to be quite popular around Cambridge.

For those not familiar with it, it's a java application framework built for REST. And, like Ruby on Rails, it emphasizes convention over configuration.

Rather than creating yet another boring blogging example I decided to use JKstat as an example, and see how involved building a RESTful JKstat server was using the Play framework.

Creating a project is easy:

play new jkstat

The one thing I'm not keen on is the way it manages dependencies for you to get you jar files. You can either mess about with yaml files, or drop the jar file into the lib directory of the project. Full details of the complex way are in the play directory of the JKstat source.

The next step is to decide how to route requests. The JKstat client only has a few requests, in a fairly fixed form. So I can write the routes file explicitly by hand:

# JKstat queries get sent to JKplay
GET /jkstat/getkcid    JKplay.getkcid
GET /jkstat/list    JKplay.list
GET /jkstat/get/{module}/{instance}/{name} JKplay.get

All this means is that if a client requests /jkstat/list, then the list() method in the JKplay class gets called.

Slightly more complex, something of the form /jkstat/get/module/instance/name will invoke a call to get(module, instance, name).

Putting this in a routes file in the application's conf directory is all that's needed to set up the routing. The other thing you need to do is write the JKplay class and put the java source in the application's app/controllers directory. The class just contains public static void methods with the correct signatures. For example:

    public static void list() {
 KstatSet kss = new KstatSet(jkstat);
 renderJSON(kss.toJSON());
    }

JKstat knows how to generate JSON output, and the renderJSON()call tells Play that this is JSON data (which just means it won't do anything with it, like format a template, which is the normal mode of operation).

And that's basically it. All I then had to do was run the project (with LD_LIBRARY_PATH set to find my jni library) and it was all set. The JKstat client was able to communicate with it just fine.

No comments: