Play!ing (2.0) with Twitter Bootstrap, WebSockets, Akka and OpenLayers
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(event.data); marker = moveMaker(map, marker, data.longitude, data.latitude); } // if errors on websocket var onalert = function(event) { $(".alert").removeClass("hide"); } 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 MapAnime.java 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>() { @Override public void invoke(JsonNode event) { // nothing to do } }); // When the socket is closed. in.onClose(new Callback0() { @Override public void invoke() { actor.tell(new UnregistrationMessage(id)); } }); } public static void moveTo(float longitude, float latitude) { actor.tell(new MoveMessage(longitude, latitude)); } @Override public void onReceive(Object message) throws Exception { if (message instanceof RegistrationMessage) { // Received a Join message RegistrationMessage registration = (RegistrationMessage) message; Logger.info("Registering " + registration.id + "..."); registrered.put(registration.id, registration.channel); } 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); channel.write(event); } } else if (message instanceof UnregistrationMessage) { // Received a Unregistration message UnregistrationMessage quit = (UnregistrationMessage) message; Logger.info("Unregistering " + quit.id + "..."); registrered.remove(quit.id); } else { unhandled(message); } } public static class RegistrationMessage { public String id; public WebSocket.Out<JsonNode> channel; public RegistrationMessage(String id, WebSocket.Out<JsonNode> channel) { super(); this.id = id; this.channel = channel; } } public static class UnregistrationMessage { public String id; public UnregistrationMessage(String id) { super(); this.id = 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,
- download Play! 2.0
- clone the Git repo
- start “play run” in the project directory
- connect to “http://localhost:9000/map“
- in another terminal, run “play test” to send REST requests and to make the vehicle move
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: http://www.objectify.be/wordpress/?p=341
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.