You're viewing all posts tagged with playframework

#playframework, #scala, #siena, #gae fun

In my last post, I mentioned that I created a simple (very simple!) Google App Engine hosted Play! webapp, written using Scala.  The webapp simply tracks people who visit my blog.  More accurately, it tracks people who view a little PNG that one of the methods renders.  If someone GETs the image, I capture the visitor’s IP address and the time.  This won’t be replacing anyone’s use of Google Analytics anytime soon, I can assure you.

But for the edification of those who may want to play with Play! and Scala, this is what I did:

  • using Play! 1.1, create a new module: play new —with=scala
  • also add siena and gae to your application.conf
  • define the paths in your controller.  I just have two, the root path lists the recent visitors, and “/track” which renders the image and captures the visitor’s information.
controllers.scala:

def index {
val visits = Visit.recent
render(visits)
}

def track {
val trackedIP = new Visit
trackedIP.remoteAddress = request.remoteAddress
trackedIP.referer = request.headers.getOrElse("referer", None)
// store it in The Cloud(tm)
trackedIP.insert()
// this is the image they see
val file = Play.getFile("/public/images/favicon.png")
renderBinary(file)
}

Note the “getOrElse” call above. This is one of the nice features of Scala. This is there because request.headers is a Map and the referer key isn’t guaranteed to be there. In Java, we would do this:

Http.Header refererHeader = request.headers.get("referer");
String referer = "";
if (refererHeader != null) {
referer = refererHeader.toString();
}
trackedIP.referer = referer;

That’s quite a mouthful, and the Scala version is much more readable.

  • now, define the model.  Because we are deploying to Google App Engine, we will use the Siena module as Siena works much more naturally with that type of datastore than Hibernate.  I’ve never been able to get JPA with Hibernate to work on Google App Engine anyway.

The Visit class extends siena.Model and declares the properties that we will store on the database. The Visit object is a singleton; if we were writing a Java object, the static/class methods we put on the Visit.class are what we are putting in the Visit object here.  In our case, we simply create a method “recent” which returns up to 20 of the most recent visitors. The @Index on the date field is necessary so Siena can order by date, which we will do in reverse order (because we want the most RECENT visitors.)

models.scala:

import play._
import play.data.validation._
import siena._
import java.util.Date

class Visit extends Model {
@Id var id:Long = _
var remoteAddress : String = _
var referer: String = _
@Index(Array("date_index")) var date : Date = new Date
}

object Visit {
def recent:java.util.List[Visit] = Model.all(classOf[Visit]).order("-date").fetch(20)
}

Your views are done in the same manner that you would do them in a Java-based Play! application: via Groovy templates.  Of course, you can always replace the template engine with Scalate or whatever else you prefer, via Play! plugins.

One handy trick I learned was the use of the JavaConversions helper class, introduced in Scala 2.8, which adds some implicit conversions between Java and Scala collections classes. This way, if you want to process the result of our call to Visit.recent using Scala style closures, you could do this:

import scala.collection.JavaConversions._

Visit.recent.foreach(v => println(v.remoteAddress))

This isn’t the most useful application, but it does provide a nice starting point for toying with the language.

play!ing with scala

I decided to try my hand at learning Scala.  It’s supposedly the “next big JVM language” and the “Java killer” if you believe the hype machine.  Personally, I don’t think that’s true.  I think the next big JVM language that replaces Java will be a future Java.  If there’s one thing Oracle knows how to do well, it’s making money, and that can’t be bad for the future of Java.

That being said, it appears like it will be a few more years before we can get any meaningful improvements to the Java language, such as language support for properties, better type inference, and closures.  So for personal projects I find my eyes wandering away from the Java realm towards more recent developments like Scala or Fantom.  A part of me actually likes the Fantom language better, because of the pragmatic, boring by design, philosophy behind the language.  But Scala seems to be more mature, so — for the moment — I’ve decided to take a stab at learning it instead.

I’ve been using a self-contained Play! environment that the makers of the Play! framework released.  This runs a web environment on your local machine that makes it very easy experiment with the language: just edit a source file and hit refresh and to see the results.

I’ve also found that the Play! framework is an ideal way to play around with the language, and it made it dead simple to get a webapp up on Google App Engine written in the language.  I’ll talk about that webapp a little more in my next post.

new play! module — paginate

One of the things I miss from JSF programming is the ability to use easily pluggable controls.  Play! isn’t really a component oriented framework, so it doesn’t provide that ability out of the box.  But because it’s so extensible it’s easy enough to fill in this gap.

I just uploaded a new module for the Play! framework to github.  It’s called Play—Paginate and does exactly what it sounds like it does: it gives you the ability to easily create paginating tables with minimal impact on your code.

Simply render the paginator from your controller.  You can instruct it to load the values from the database, or wrap a List you already loaded.

    public static void index() {
        Paginator entities = new ModelPaginator(TestModel.class,
"field=?", "whatever").setPageSize(4);
        render(entities);
    }

Simply render the paginator in your view by adding this stylesheet:

<link rel="stylesheet" type="text/css" media="screen" 
href="@{'/public/stylesheets/play-pagination.css'}">

And use the tags #{paginate.list}, which is a drop-in replacement for #{list}, and #{paginate.controls}, to display the pagination controls:

#{paginate.list items:entities, as:'ref'/}
#{paginate.controls items:entities /}

Then you’ll get something like this:

Play--Paginate control

Easy peasy.

dev derby 2010

This weekend, on September 11, 2010, I took part in the Dev Derby 2010.  This was a contest where teams were split up by programming language, and challenged to create as usable and fully functional a program as possible in only six hours.  Sadly, some teams, such as Justin Ko’s Team Ruby, were shorthanded.  However, the PHP and C# teams put up a good fight.

The challenge was to design a software system that could be used to match non-profit organizations with volunteer groups that offer services that match their needs.  There were a number of criteria that we had to meet, such as implementing some external API (most people chose some form of Single Sign On) and implementing all of the required features for the application.

I’m happy to announce that my team, Team Java, won the challenge.  More so, our system was the only one that worked end to end. 

Some might wonder how we did it: well, I started out doing what I do with everything else - I first identified the best tools for the job. And sometimes those tools aren’t the ones we normally use.

At work, as an enterprise Java developer on Wall Street, I normally use a particular stack of frameworks: Spring, JSF, Hibernate.  I think they are the right tools for that job.  The usual development cycle involves coding - compiling - deploying the updated code - restarting the server/process/container - relogging in and whatever else to get back to wherever you were - and then, finally, retesting.  (Of course, we employ automated test suites as well.)

For the contest, we were building a webapp, and competing against languages like Ruby, Python, and PHP that do not have the compile and deploy stages: it’s simply code - hit refresh and test.  Over the long term, for a large project, that’s not a huge advantage, but in a contest that lasts only six hours, that would have killed us.

So our secret weapon was the Play! framework.  This is a very easy to use to framework.  How easy was it? Well, none of the other six team members had even heard of Play! before the contest.  I sent out a document only a week before the challenge describing how to use it and only two people really read it.  The rest learned as we coded. 

Play! is a very agile framework that is completely stateless and recompiles changes to your codebase transparently - so it erases the advantage that dynamic languages have by not needing a compilation step.  In the meantime, we still benefit from the advantages of static typing that Java gives us, protecting us from a large number of time-wasting bugs.  Certainly, there are certain types of problem domains that are easier or only possible in dynamic languages (that’s why there are no pure static typed languages: they all offer some way to subvert the type system such as reflection or casting), but for a webapp those problems aren’t applicable.

We were allowed to use libraries that would help us in meeting the coding challenge.  Play! has a lot of plugins available for it: we used Search to implement full text search in our filters, and Scaffold to rapidly generate prototype screens.

While not a Play! plugin, we also used the java-facebook-api which was incredibly easy to use when adding Facebook Connect access to the system.

I’m very pleased with how well our use of the Play! framework turned out (even if I’m not entirely pleased with how our CODE turned out: hey, in only six hours, you have to make a few allowances… :) ).  It was a fun challenge, and I hope to try again next year.  Hopefully the Ruby team will have better luck assembling their team so I can show all the cool kids how you should truly achieve web scale webapps.  At least the Zend-spinning PHP geeks got the message.  (Luckily for C#, Microsoft was on hand with paid counselors to help them cope with the loss with promises of improvements in Visual Studio 2011 that would make them more competitive… well, not really, but they should have been!)

Playing with Play!

I’ve been playing around with the Play! framework for some time.  It’s a really great framework for the Java language that makes web programming fun again.  Well, fun for those of us who didn’t jump on the Ruby bandwagon several years ago.  They’ve already been having fun.  But now we can too, and not have to give up the things we love about Java like static typing and enterpriseyness and NullPointerExceptions.  Well, maybe not the last one…

I think Play! shows how most of the problems that people have with the Java language are mostly self-imposed and cultural.  Don’t like the code-compile-deploy test cycle?  Who doesn’t?  With Play! that isn’t a problem anymore.  Play! uses a custom classloader which compiles the classes on the fly, meaning we get the same rapid coding that Ruby on Rails and PHP developers are accustomed to: edit your source file, hit save, hit refresh on the browser, and go.

So I’ve had some fun with Play! for a while and decided to give back to the Play! community.  Today, I’ve released a module for use by the Play! community called scaffold.  It basically works like the Ruby on Rails scaffolding generators, creating some simple controllers and CRUD views based on your models.  Unlike the CRUD module that comes with Play!, this is done via static generation instead of dynamic, runtime introspection.  So, once you’ve customized your views and controllers, you can remove the module and continue without any further dependency.

Hopefully someone finds it useful.