Scaladin chat demo in a Vaadin/Eclipse project

In this post I’m going to show you how to integrate a Scaladin project into an Eclipse-generated Vaadin setup. The demo I’ll be using is a small but impressive one: it uses Vaadin’s Atmosphere-poweredserver-push” and Akka-Actors (disclaimer: I don’t take credit, since I did not write the demo).

I like Scala, Vaadin, and find the idea of Scaladin excellent (to be able to code for Vaadin using idiomatic Scala). There is a SBT plugin for Scaladin, which integrates very well with this build tool. On the other side, the benefits of the Vaadin plugin and IDE integration are lost: like debugging in Eclipse, for example.

What I set up to do was modify the IDE-generated Vaadin project until:

  • Scala was supported
  • Scaladin was supported

As an excercise I “ported” (actually more like “copy-pasting”) the existing “Scaladin Chat demo” to the IDE-generated default setup.

scaladin-chat-eclipse

Here’s what I did…

First, I followed the official instructions on how to get started with a Scala Vaadin project (this includes adding the “Scala nature” to the project!).

However, I did not add the scala-library.jar as instructed there. Instead, I added it as an Ivy dependency to the ivy.xml file:

<!-- Scala Runtime Library -->      
<dependency org="org.scala-lang" name="scala-library" rev="2.10.4"/>

At that point I had a Scala-capable Vaadin project. Then I added Scaladin:

<!-- Scaladin -->
<dependency org="org.vaadin.addons" name="scaladin" rev="3.0.0" />

Since I didn’t know how to bootstrap Scaladin from a Scala class, I left the Java bootstraping class for the moment. Instead, I wrote a Scala class that would provide the main component:

package com.example.vaadindemo

import vaadin.scala.VerticalLayout
import vaadin.scala.Button
import vaadin.scala.Notification

class SomeScalaClass {

  def content: com.vaadin.ui.Component = {
    val scaladinComponent = new VerticalLayout {
      margin = true
      components += Button(caption = "Click Button!", {
        println("Button clicked (Server)")
        Notification.show("Hello via Scaladin!")
      })
    }

    // return the "real" wrapped Vaadin component
    scaladinComponent.p
  }

}

Here you can see that I’m returning a normal Vaadin UI component, not a Scaladin one. Although I am using Scaladin’s “magic” (the nice DSL which wraps over Vaadin) at the end of the day I return the wrapped Vaadin component. Which is the one “consumed” by the Java bootstrapping class:

package com.example.vaadindemo;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.UI;

@SuppressWarnings("serial")
@Theme("vaadindemo")
public class VaadindemoUI extends UI {

    @WebServlet(value = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = VaadindemoUI.class, widgetset = "com.example.vaadindemo.widgetset.VaadindemoWidgetset")
    public static class Servlet extends VaadinServlet {
    }

    @Override
    protected void init(VaadinRequest request) {
    SomeScalaClass scalaInstance = new SomeScalaClass();
        setContent(scalaInstance.content());
    }

}

Note how the Java part consumes the component instantiated on the Scala part. This is a very nice setup to profit from Vaadin’s annotations, which makes using a web.xml file unnecessary. More on that in a moment.

Debugging works as expected, which I tested by placing a breakpoint on Scala’s println().

But of course having Java code lying around didn’t make me happy… I wanted to see if I could integrate the “Scaladin Chat demo” into this project setup. In other words: if I could also bootstrap the Vaadin application from Scala.

First thing I did was to check if I satisfied the dependencies… These are the dependencies listed in the project’s build.sbt:

libraryDependencies ++= Seq(
  "com.vaadin" % "vaadin-server" % "7.1.3",
  "com.vaadin" % "vaadin-themes" % "7.1.3" % "container",
  "com.vaadin" % "vaadin-client-compiled" % "7.1.3" % "container",
  "com.vaadin" % "vaadin-push" % "7.1.3",,
  "vaadin.scala" %% "scaladin" % "3.0-SNAPSHOT",
  "com.typesafe.akka" %% "akka-actor" % "2.2.1",
  "org.eclipse.jetty" % "jetty-webapp" % "8.1.12.v20130726" % "container",
  "org.eclipse.jetty" % "jetty-websocket" % "8.1.12.v20130726" % "container"
)

What’s obviously missing is akka-actor. I assumed that the jetty components were used by the sbt-plugin and not needed in my case (I was using Tomcat). So I added the missing dependency to my Ivy file:

<!-- Akka Actors -->
<dependency org="com.typesafe.akka" name="akka-actor_2.10" rev="2.2.1"/>

After that I copy-pasted the Scala classes / files directly under “src”:

  • com/example/scaladinchat/ScaladinChatUI.scala
  • com/example/scaladinchat/chat.scala

The IDE-generated Vaadin project has only “src”; it does not have “main/scala” or “main/java”. For sake of brevity I will not reproduce the contents of these Scala files, which can be found on the original project.

Now comes a very important point. The Scaladin project makes use of (needs?) web.xml. On the original project this is found under src/main/webapp/WEB-INF. This file, on the IDE-generated project is to be put under WebContent/WEB-INF.

I really don’t know why Scaladin’s version needs the web.xml whereas the official Vaadin code does not seem to. If any reader can enlighten me, I will be very grateful.

Part of what the annotations used to cover in the original Java code is then found on the web.xml file, like:

  • the servlet path
  • the servlet class (auto-discovered)
  • the production mode

Other info covered by the annotations can be passed as initialization parameters to the main Scaladin UI component. I modified the ScaladinChatUI construction to look like this:

class ScaladinChatUI extends UI(
  theme = "vaadindemo",
  widgetset = "com.example.scaladinchat.widgetset.VaadindemoWidgetset")
    with ChatClient { app =>

I had changed the path of the widgetset file. As a last step, I deleted my two previous files VaadindemoUI.java and SomeScalaClass.scala.

Finally, after all these changes, I had very nice Vaadin demo, using server-push (powered by Atmosphere) and Akka-Actors, written exclusively in Scala!

Credits

Many thanks go to Henri Kerola for his contributions! Henri works at Vaadin and created practically everything Scala+Vaadin related: from the chat-demo used as illustration here, to the SBT-plugin, to Scaladin itself. Be sure to check out his github repositories, where you can find other Scaladin demos, integration of Vaadin into Play, Akka-related projects, etc.

Scala Beginners: counting words and lines

A simple command-line tool

At work, I’m teaching one intern and one colleague how to program.

I gave them the following exercise:

Write an utility that takes 3 command-line parameters P1, P2 and P3. P3 is OPTIONAL (see below) P1 is always a file path/name. P2 can take the values:

  • “lines”
  • “words”
  • “find”

Only P2 is “find”, then P3 is relevant/needed, otherwise it is not.

So, the utility does the following:

  • If P2 is “rows” it says how many lines it has
  • If P2 is “words” it says how many words it has (the complete file)
  • If P2 is “find” it prints out the lines where P3 is present

Continue reading

P07 – Flatten a nested list structure

Peter not only offers you one but three solutions in Clojure.

Clojure recursive:

(defn flatten-recur
  "P07 (**) Flatten a nested list structure."
  ([xs] (flatten-recur [] xs))
  ([acc xs]
     (if-not
      (seq? xs) (conj acc xs)
      (if (empty? xs)
        acc
        (-> (flatten-recur acc (first xs))
            (flatten-recur (rest xs)))))))

Clojure de-structured:

(defn flatten-destructured
  "P07 solution I saw on cchandler's github repo"
  [x & tail]
  (concat (if (seq? x)
            (apply flatten-destructured x)
            [x])
          (if (nil? tail)
            nil
            (apply flatten-destructured tail))))

Clojure with reduce:

(defn flatten-reduce
  "P07 solution I saw on rodnaph's github repo "
  [xs]
  (reduce #(if (seq? %2)
             (concat %1 (flatten-reduce %2))
             (concat %1 (list %2)))
          '() xs))

I just came up with one for Scala:

def flatten(list: List[_]): List[_] = {
  def helper(remainder: List[_], result: List[_]): List[_] =
    remainder match {
      case Nil => result
      case (head: List[_]) :: tail => helper(tail, result ++ flatten(head))
      case head :: tail => helper(tail, result :+ head)
    }
  helper(list, Nil)
}

For the first time I am forces to depart from lists of one type of elements and resort to List[_], which would translate to “list of I-don’t-care”. This is of course so because due to the nature of nested lists, one cannot effectively make predictions about the type. It would result in an infinite recursion of declarations: “list of elements of type T OR of (lists of element of type T or of (lists of…”.

It is also unfortunate that the type declaration makes the logic of the function a little bit more difficult to read (though one can get used to it). Of course a type-aliasing could solve the problem like this:

type L = List[_]
def flatten(list: L): L = {
  def helper(remainder: L, result: L): L =
    remainder match {
      case Nil => result
      case (head: L) :: tail => helper(tail, result ++ flatten(head))
      case head :: tail => helper(tail, result :+ head)
    }
  helper(list, Nil)
}

We can see that this solution is, in spirit, not much different than the first Clojure one. It just does not explicitly ask “is this a collection?”, “is it empty?” through functions like in Clojure but leaves those decisions to the Scala pattern-matching mechanism. The benefit of this is the compiler warning if the pattern matching is not exhaustive.

The Scala solution uses, once again, a helper function which does the real recursion and accumulation of results. The recursion ends when there isn’t anything else to process.

The interesting matching is done on the head element of the incoming list (we are always within a list). The head element might itself be a list or not. If it is a list, then it is further flattened and appended to the current results. If it is not, then it’s appended to the results without flattening.

Note the difference between ++ and :+ in (immutable) collections. The former serves to obtain the concatenation of two collections, while the latter serves to obtain the concatenation of one element to an existing collection.

P05 – Reverse a List

Clojure – recursive:

(defn my-reverse [xs]
  "P05 (*) Reverse a list"
  (loop [ret [] xs xs]
    (if (empty? xs)
      ret
      (recur (cons (first xs) ret) (next xs)))))

Clojure – with reduce:

(defn my-reverse-reduce [xs]
  "P05 (*) Reverse a list"
  (reduce #(cons %2 %1) '() xs))

Scala – recursive:

def reverse[T](list: List[T]): List[T] = {
  def helper(remaining: List[T], reversed: List[T]): List[T] =
    remaining match {
      case Nil => reversed
      case first :: rest => helper(rest, first :: reversed)
    }
  helper(list, Nil)
}

Scala – with folding:

def reverseFolding[T](list: List[T]): List[T] =
  list.foldLeft(List.empty[T])((result, element) => element :: result)

P04 – Find the Number of Elements of a List

Clojure recursive:

(defn my-count [xs]
  "P04 (*) Find the number of elements of a list."
  (loop [num 0 xs xs]
    (if (next xs)
      (recur (+ num 1) (next xs))
      (+ num 1))))

Clojure with reduce:

(defn my-count-reduce [xs]
  "P04 (*) Find the number of elements of a list."
  (reduce (fn [c xs] (inc c)) 0 xs))

Scala recursive:

def length[T](list: List[T]): Int =
  list match {
    case Nil => 0
    case x :: rest => 1 + length(rest)
  }

Scala foldLeft:

def length[T](list: List[T]): Int =
  list.foldLeft(0)((count, _) => 1 + count)

This last can probably be improved.

P03 – Find the nᵗʰ Element of a List

This problem is very nice because the Clojure and Scala implementations are practically the same. It allows to appreciate the different syntaxes better.

Below is Peter’s solution to the problem, in Clojure:

(defn kth [n xs]  
  {:doc "P03 (*) Find the Kth element of a list." 
   :pre [(seq? xs)]}
  (if (= 0 n)
    (first xs)
    (recur (- n 1) (next xs)))
  )

Here is my Scala:

def nth[T](n: Int, list: List[T]): T =
  if (n == 0)
    list.head
  else
    nth(n - 1, list.tail)

In this case one can see a small but significant difference where Clojure sticks to functional-programming and Scala favours object-oriented: while in Clojure first and next are functions that operate on collections, in Scala head and tail are methods to be called upon a collection instance.

P02 – Find the Penultimate Element of a List

Peter brings us this solution:

(defn penultimate [xs]
  {:doc  "P02 (*) Find the last but one element of a list."
   :pre [(seq? xs)]}
  (loop [ret (first xs) xs xs]
    (if (next xs)
      (recur (first xs) (next xs))
      ret)))

I can not comment much, since I’m no Clojure developer. In particular I would like to know what recur does? A generic macro to do recursion on a function? Seems interesting…

This is my solution in Scala:

def penultimate[T](list: List[T]): T =
  list match {
    case List(first, last) => first
    case first :: second :: rest => penultimate(second :: rest)
    case _ => error("Can not find penultimate of this list: " + list)
  }

Using pattern matching, it does the following:

  • if it matches a list consisting of only two elements (first and last) return the first one
  • if it matches a list consisting of a least two elements and a rest, do recursion using the second and the rest
  • in any other case the list has an unacceptable for, raise an error

Note the two matching styles for a list. The first one using the de-structuring of the List (unapply behind the scenes) and the second using the “consing” of list-elements.

This implementation either returns the sought element, or it raises an error. It might be a cleaner, more idiomatic Scala implementation to return an Option[T] instead. Let’s explore that possibility:

def penultimate[T](list: List[T]): Option[T] =
  list match {
    case List(first, last) => Some(first)
    case first :: second :: rest => penultimate(second :: rest)
    case _ => None
  }

It can now be used like this:

penultimate(myList) map { element => /* do something with element */ }

Or, if one wants to handle the case where None is found:

penultimate(myList) getOrElse { /* no penultimate found, deal with this */}

Or, to handle both cases:

penultimate(myList) map { element => 
  /* do something with element */ 
} getOrElse { 
  /* no penultimate found, deal with this */
}

P01 – Find the last element of a list

The first problem is to find the last element of a list.

This is Peter’s Clojure version:

(defn my-last [input]
  "P01 (*) Find the last element of a list."
  (if (next input)
    (recur (next input))
    (first input)))

And here is my Scala version:

def last[T](list: List[T]): T =
  list match {
    case List(only) => only
    case first :: rest => last(rest)
    case Nil => error("An empty list has no last element")
  }

Some things to note about the Scala version:

  • It is, of course, type-safe. It won’t accept anything but a list.
  • It is generic: it will work on lists of anything.
  • Because it’s recursive, the return type has to be declared.
  • You get a runtime-error if the list is empty

Because it’s generic and due to Scala’s type inference this will also work:

scala> last(List(1, 2, true, "five", 8))
res0: Any = 8

Scala will just infer to the most immediate matching super-class. In this case: Any.

But there is something disturbing in this implementation, however: raising an error if the list is empty. The Clojure version simply returns nil instead. Both solutions are not quite acceptable to me.

Having to deal with runtime-errors or magic “nulls” is something that as a Scala developer you are inclined to avoid. Fortunately Scala makes it very easy to do so, by switching to Option[T]:

def last[T](list: List[T]): Option[T] =
  list match {
    case List(only) => Some(only)
    case first :: rest => last(rest)
    case Nil => None
  }

Now, the function might return Some[T] or None (it reads like English, doesn’t it?).