Play!ing (2.0) with Twitter Bootstrap, WebSockets, Akka and OpenLayers

The original post can be found on the ekito website.

For one of our client, we need to show a map with vehicles position updated in real-time.
So I began to make a prototype using Play! framework, with its latest released version 2.0, using the Java API. I started from the websocket-chat of the Play! 2.0 samples.

The purpose of the prototype is to show a moving vehicle on a map. The location of the vehicle is sent to the server through a REST call (at the end, it will be sent by an Android app), and the connected users can see the vehicle moving in real-time on their map.

First, let’s look at a small demo !

So, at first, to make the things a bit pretty, I decided to integrate Twitter Bootstrap (v2.0.1) using LessCss. For that, I used the tips from the following article (nothing difficult here).

Then, I integrated OpenLayers, a Javascript framework used for map visualization. I used the Google Maps integration example, and add some KML layers. This is done in the map.scala.html and maptracker.js files, nothing fancy here (it is pure Javascript, and I’m not an expert…).

The interesting part is the one using the WebSockets. On the client side, it is quite standard :

var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var mapSocket = new WS("@routes.Application.mapsocket().webSocketURL(request)");

mapSocket.onmessage = function(event) {
    var data = JSON.parse(;
    marker = moveMaker(map, marker, data.longitude, data.latitude);

// if errors on websocket
var onalert = function(event) {

mapSocket.onerror = onalert;
mapSocket.onclose = onalert;

When the client receive a JSON data from the websocket, it moves the marker on the map. And if an error occurs on the websocket (the server is stopped for instance), a pretty error is displayed thanks to Twitter Bootstrap :

On the server part, the websocket is created by the Application controller, and is handled by the Akka actor; it accesses Akka native libraries to deal with the events from the controller.

public class MapAnime extends UntypedActor {

 static ActorRef actor = Akka.system().actorOf(new Props(MapAnime.class));

 Map<String, WebSocket.Out<JsonNode>> registrered = new HashMap<String, WebSocket.Out<JsonNode>>();

  * @param id
  * @param in
  * @param out
  * @throws Exception
 public static void register(final String id,
   final WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out)
   throws Exception {

  actor.tell(new RegistrationMessage(id, out));

  // For each event received on the socket,
  in.onMessage(new Callback<JsonNode>() {
   public void invoke(JsonNode event) {
    // nothing to do

  // When the socket is closed.
  in.onClose(new Callback0() {
   public void invoke() {
    actor.tell(new UnregistrationMessage(id));

 public static void moveTo(float longitude, float latitude) {

  actor.tell(new MoveMessage(longitude, latitude));


 public void onReceive(Object message) throws Exception {

  if (message instanceof RegistrationMessage) {

   // Received a Join message
   RegistrationMessage registration = (RegistrationMessage) message;"Registering " + + "...");

  } else if (message instanceof MoveMessage) {

   // Received a Move message
   MoveMessage move = (MoveMessage) message;

   for (WebSocket.Out<JsonNode> channel : registrered.values()) {

    ObjectNode event = Json.newObject();
    event.put("longitude", move.longitude);
    event.put("latitude", move.latitude);


  } else if (message instanceof UnregistrationMessage) {

   // Received a Unregistration message
   UnregistrationMessage quit = (UnregistrationMessage) message;"Unregistering " + + "...");

  } else {


 public static class RegistrationMessage {
  public String id;
  public WebSocket.Out<JsonNode> channel;

  public RegistrationMessage(String id, WebSocket.Out<JsonNode> channel) {
   super(); = id; = channel;

 public static class UnregistrationMessage {
  public String id;

  public UnregistrationMessage(String id) {
   super(); = id;

 public static class MoveMessage {

  public float longitude;

  public float latitude;

  public MoveMessage(float longitude, float latitude) {
   this.longitude = longitude;
   this.latitude = latitude;



The “register” and “moveTo” methods are called by the controller, they send messages to the Akka system. These messages are processed by the “onReceive” method. For instance, when it receives a MoveMessage, it creates a JSON object with the longitude and the latitude and it is sent to the clients through the websockets.

I also quickly wrote a test class which parse a text file, and send REST requests with a new location to the server every 100ms.

The project is hosted on Github. It works with Google Chrome v17 and Firefox v11.

To test it,

The problem I need to solve now is that the application is not Stateless, because in the Actor, I store a Map of connected clients. Maybe I’ll need to look at Redis or something, any help would be greatly appreciated.

So in conclusion, I was able to quickly develop a working prototype, and I think I’ll try to use Play! 2.0 in several projects

What’s good:

  • Highly productive
  • Typesafe view templates based on Scala
  • LessCss integration
  • Akka integration
  • Compiled javascript with Google Closure Compiler
  • No need to learn Scala for the moment, hooray !

To be improved:

  • The Scala compile times should be increased, because on my PC, it takes up to 4s to compile a view, and it breaks my flow (I use the “~run” command to gain 1s when switching from my IDE to my web browser)
  • The Scala compiler errors are cryptic
  • I cannot deploy the demo on Heroku because it does not support (yet ?) websockets

Update : A bit later, I discovered an article from @steve_objectify using similar technologies:

Reference: Play!ing (2.0) with Twitter Bootstrap, WebSockets, Akka and OpenLayers from our JCG partner Sebastian Scarano at the Having fun with Play framework! blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply

5 − = four

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books