Home > Uncategorized > Writing Comet based application using Scala and the Atmosphere Framework

Writing Comet based application using Scala and the Atmosphere Framework

Writing Atmosphere‘s Comet based applications is simple. Imagine using Scala instead of Java…it becomes really simple! No need to learn Lift anymore 🙂


Not being an expert with Scala at all, I’ve decided to re-wrote the Chat based application I’ve recently used when adding cluster support to Atmosphere. This is really my first ever Scala application so don’t jump looking at the code! Instead, tweet me a better implementation. I will not go into the details of how to write an Atmosphere application, so if this is the first time you learn about Atmosphere, start here.

For the chat, I’ve needed to implement two methods: one that will be invoked when suspending a response (Comet’s HTTP streaming technique), and one for sending chat messages to those suspended response (to the other chat member). To do that in Scala, I did:

  1 package org.atmosphere.samples.scala.chat
  3 import javax.ws.rs.{GET, POST, Path, Produces, WebApplicationException, Consumes}
  4 import javax.ws.rs.core.MultivaluedMap
  5 import org.atmosphere.core.annotation.{Broadcast, BroadcastFilter, Suspend}
  6 import org.atmosphere.util.XSSHtmlFilter
  8 @Path("/chat")
  9 class Chat {
 11     @Suspend
 12     @GET
 13     @Produces(Array("text/html"))
 14     def suspend() = "<!-- Comet is a programming technique that enables web " +
 15                 "servers to send data to the client without having any need " +
 16                 "for the client to request it. -->\n"
 18     @Broadcast
 19     @Consumes(Array("application/x-www-form-urlencoded"))
 20     @POST
 21     @Produces(Array("text/html"))
 22     @BroadcastFilter(Array(classOf[XSSHtmlFilter],classOf[JsonpFilter]))
 23     def publishMessage(form: MultivaluedMap[String, String]) = {
 24         val action = form.getFirst("action")
 25         val name = form.getFirst("name")
 27         val result: String = if ("login".equals(action)) "System Message" + "__" + name + " has joined."
 28              else if ("post".equals(action)) name + "__" + form.getFirst("message")
 29              else throw new WebApplicationException(422)
 31         result
 32     }
 33 }

To suspend the response, I’ve annotated the suspend() method (line 11) with @Suspend. The returned value of the suspend() method will be written and then the response will be suspended, waiting for server event, e.g messages from other chatter. Now when someone publish a message, method publishMessage() will be invoked. Since the method is annotated with @Broadcast (line 18), the method’s returned value will be broadcaster to all suspended response, e.g. all suspended connections will get a chance to write the message. But since I don’t want users to publish script or any kind of attack, I’ve also added the @BroadcastFilter annotation, which will make sure to filter malicious characters. Since my javascript client expect JSONp response, I’ve decided to write a BroadcastFilter in Scala that transform the message:

  1 package org.atmosphere.samples.scala.chat
  3 import org.atmosphere.cpr.BroadcastFilter
  5 class JsonpFilter extends BroadcastFilter[String] {
  7     val BEGIN_SCRIPT_TAG = "<script type='text/javascript'>\n"
  8     val END_SCRIPT_TAG = "</script>\n"
 10     def filter(m : String) = {
 11         var name = m
 12         var message = ""
 14         if (m.indexOf("__") > 0) {
 15             name = m.substring(0, m.indexOf("__"))
 16             message = m.substring(m.indexOf("__") + 2)
 17         }
 19         val result: String = (BEGIN_SCRIPT_TAG + "window.parent.app.update({ name: \""
 20                 + name + "\", message: \""
 21                 + message + "\" });\n"
 22                 + END_SCRIPT_TAG)
 23     }
 24 }

Then I just pass the name of that class to the @BroadcastFilter annotation:


What amaze me here is one filter is written in Java, the other one in Scala!. That’s it. With those two classes, the Atmosphere REST Chat demo works. To complicate the application, I’ve decided to deploy it into a cluster. This is simple to achieve by annotating the publishMesaage with:


Now my Scala application is Comet-Cluster enabled! That was fun!

For any questions or to download the above sample, go to our main site and use our Nabble forum (no subscription needed) or follow us on Twitter and tweet your questions there!

var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.&#8221; : “http://www.&#8221;);
document.write(unescape(“%3Cscript src='” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));

var pageTracker = _gat._getTracker(“UA-3111670-3”);


Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: