preload
Jun 30

Some Vaadin at last.

Download Vaadin from here and unpack it. You only really need the minimal one jar download, but with documentation this well written it’d be a shame not to grab it all.

They have platform specific downloads because some pieces of the underlying GWT toolset use SWT. As far as I can tell, there’s no runtime platform specificity and I’m not going to be touching the GWT tools in this series, so don’t worry about it.

From the download copy the vaadin-6.0.0.jar file ( hidden inside the WebContent directory if you downloaded the full installation ) into your spike/lib directory.

SBT adds any jars it finds in the lib directory to the classpath. Old-school styling baby!

And now some code.

The first “why don’t you follow along at home” example from the Book of Vaadin is on page 24.

You need to configure the Vaadin servlet in the web.xml file. Sorry, back to the XML grindstone.

Insert this into the web-app element:

<display-name>myproject</display-name>
<context-param>
	<description>Vaadin production mode</description>
	<param-name>productionMode</param-name>
	<param-value>false</param-value>
</context-param>
<servlet>
	<servlet-name>Spike Application</servlet-name>
	<servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class>
	<init-param>
		<description>Vaadin application class to start</description>
		<param-name>application</param-name>
		<param-value>spike.SpikeApplication</param-value>
	</init-param>
</servlet>
<servlet-mapping>
	<servlet-name>Spike Application</servlet-name>
	<url-pattern>/*</url-pattern>
</servlet-mapping>

The web.xml will now route all requests through the Spike Application servlet that’s will look for the spike.Application class. I’ve changed the class and package name from the example to match the project and to keep package hierarchies short-ish.

The original Java code on the first example looks like this:

package com.example.myproject;

import com.vaadin.Application;
import com.vaadin.ui.*;

public class MyprojectApplication extends Application
{
    @Override public void init() {
        final Window mainWindow = new Window("Myproject Application");
        Label label = new Label("Hello Vaadin user");
        mainWindow.addComponent(label);
        mainWindow.addComponent(
            new Button("What is the time?",
                new Button.ClickListener() {
                    public void buttonClick(ClickEvent event) {
                        mainWindow.showNotification("The time is " + new Date());
                    }
                }));
        setMainWindow(mainWindow);
   }
}

Not too bad. Particularly when you consider what it generates - a full page of HTML with a button with a server-side call back that displays the server time on screen in an area that fades out after a few seconds.

Not too bad, but I think Scala can do better. Stage 1 - Transliteration.

Create the application class:

~/code/spike : mkdir src/main/scala/spike
~/code/spike : touch src/main/scala/spike/Application.scala

Then edit the class so that it looks like so:

package spike 

import com.vaadin.Application
import com.vaadin.ui._
import java.util.Date 

class SpikeApplication extends Application {
    override def init(): Unit = {
        val mainWindow = new Window("Spike Application")
        val label = new Label("Hello Spike Application User!")
        mainWindow.addComponent(label)
        mainWindow.addComponent(
        new Button("What is the time?",
            new Button.ClickListener() {
                def buttonClick(event: Button#ClickEvent) {
                    mainWindow.showNotification("The time is " + new Date())
            }}))
	    setMainWindow(mainWindow)
   }
}

Start Jetty:

~/code/spike : sbt >jetty-run

Then navigate to http://localhost:8080

Exciting - not so much. Still, the Scala here is pretty much identical to the Java code. It is nice to know that you can take a piece of Vaadin code and translate it without too much trouble. But if the Scala isn’t any better - then Java would be a ’safer’ choice.

Let’s see if we can pimp this code.

Hmm, I don’t like the inner class listener. In Java this is the best choice, in Scala we have more choices. Closures/Blocks/BlockClosures/Anonymous Functions/Lambdas/Anonymous Delegates/whatever you want to call them. to the rescue. We can create a button that takes a closure and never have to write one of those ugly little inner classes again.

Another thing that bothers me is that call to setMainWindow. Inheritance like this makes testing and TDD harder because I’m tied into the way the Application class works. I don’t like that. That’s not a game I’m going to play. I’ve an idea of how to extract us from that hole using abstract traits. But that can wait until I try writing tests.

After removing the inner class, slight blemishes in the rest of the code became more obvious so I’ve done a spot of in-lining and removed a few extraneous braces. I often find that once you can’t see the little pimples until you’ve removed the massive warts. Anyway, the code now looks like this:

package spike 

import com.vaadin.Application
import com.vaadin.ui._
import java.util.Date 

class SButtonClickListener(action: Button#ClickEvent => Unit) extends Button.ClickListener {
    def buttonClick(event: Button#ClickEvent): Unit = {
        action(event)
    }
}

class SButton(text: String, action: Button#ClickEvent => Unit) extends Button(text, new SButtonClickListener(action))

class SpikeApplication extends Application {
    override def init: Unit = {
        val mainWindow = new Window("Spike Application")
        mainWindow.addComponent(new Label("Hello Spike Application User!"))
        mainWindow.addComponent(
            new SButton("What is the time?", _ => mainWindow.showNotification("The time is " + new Date)))
	   setMainWindow(mainWindow)
   }
}

But, but, but, that’s longer I hear you cry. Yes it is. But the first two classes can be pulled out and stored away somewhere and you’re free of inner class event handlers for every button hence-forth.

The important part is the init method, isn’t that much cleaner than before? You create a window, add a couple of components and pass it on.

For my money, this is a win.

Swap this code into place, execute a:

>jetty-restart

and take a look to make sure it hasn’t changed.

Next time - continuous build and deploy and on to the next example.

Jun 30

So, where to start? At the beginning I suppose. I’ve decided to take the Book of Vaadin and, as I’m reading it, I’ll convert each of the examples from Java to Scala. Stage one will be transliteration, stage two will be ‘pimping’ and Scala-fying the code.

My Scala chops are still developing, and my Vaadin chops are non-existant, so if anyone wants to point out stoopid-noob-mistakes or ways to improve my pimping skills please feel free. Either drop me a line here or twitter me @roblally and I’ll try to rectify my mistakes.

As I talk through the process I’ve followed, I’m not going to mention IDE integration. I use the most excellent IntelliJ IDEA and the mostly excellent Scala plugin for it. Configuring the IDE is really outside the scope of this post, you’ll have to figure that out for yourself. Anyway, time to get going.

Stage One : SBT

SBT (Simple Built Tool) is a minimalist (well, it is minimalist now, and more features are arriving all the time) build tool for Scala. It isn’t the answer for every problem, but if things pan out the way I hope they will, it should be good for this little project.

Start off by downloading the SBT launcher : the installation instructions are simple enough.

Stage Zero : Java (preferably Java 6)

Yeah, I know, zero comes before one, but since I’m only going to say “Java - you should have some”, it doesn’t really matter where I put it.

Stage Two : Create a project

Create a directory to hold the project. I’ve used ~/code/spike - using spike in the XP sense rather than the Buffy villain fan-boy sense.

~/code/spike (3504) : sbt
Project does not exist, create new project? (y/N/s) : y
Name: spike
Organization []:
Version [1.0]:
Scala version [2.7.5]:
sbt version [0.5]:
...lots of output...
>

When I ran SBT in the empty directory it told me that there was no project found (anyone who’s surprised should stop reading now.. nothing to see here, move along) and helpfully offered to create it.

I entered the name of the project ’spike’ and hit return to accept the defaults for everything else.

SBT will now download everything I need to get my project going, including the correct version of Scala and SBT itself. Yes, all you downloaded was the SBT launcher, the full version is tied to the specific version of Scala you’re using so it helpfully has a neat layer of indirection.

You’ll notice that SBT has left you with an endearing little ‘>’ prompt. SBT can execute a command, or it can enter an ‘interactive’ mode where it will execute a command and then stay running, waiting to fulfil your next desire. Like a very limited genie, only capable of granting pretty crappy wishes. The scala compiler can take a few seconds to get warmed up, so this isn’t a bad idea. You can also tell it to execute commands whenever it detected file changes - very nice for those TDD aficionados, on every file save you can have all your tests run so you never have to manually poke the run button. When using two monitors I like to have a console with SBT running in file watcher mode running my tests on one monitor with my IDE on the other.

OK, OK, very nice auto test runner… neat but hardly revolutionary. Well, another neat but not revolutionary feature is the ability to run a hosted Jetty instance and restart that whenever files change. I’m hoping that will be a real win when we get to the point of actually having something on the screen.

We don’t want SBT running just now, though so:

> exit
[info]
[info] Total session time: 781 s
~/code/spike :

The default SBT project isn’t a web app, and doesn’t really know anything about them. Let’s fix that.

~/code/spike : mkdir src/main/webapp/
~/code/spike : mkdir src/main/webapp/WEB-INF
~/code/spike : touch src/main/webapp/WEB-INF/web.xml

Open the web.xml file in your favourite editor and pop in:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
</web-app>

My word, I’d forgotten what a pain in the ass it is to try to put sample XML into a blog posting. For that reason, if for no other, I’ll try to keep the XML to a minimum. I think we’ll have to define a single servlet, after that we can stay away from angle-bracket land for a good while.. maybe forever.

SBT is configured using Scala. Adhering to the convention over configuration mantra it has pretty sensible defaults. But since this is a web app, the defaults won’t cut it. We need to create a project configuration class.

~/code/spike : mkdir project/build
~/code/spike : touch project/build/SpikeProject.scala

And pop open SpikeProject.scala file in the editor/IDE of your choice. (We’re almost there.. honest).

import sbt._

class SpikeProject(info: ProjectInfo) extends DefaultWebProject(info)
{
  val jetty = "org.mortbay.jetty" % "jetty" % "6.1.18" % "test->default"
}

And our configuration is done. GENTLEMEN, START YOUR ENGINES! Or, developers of any gender, please start your web-server.

Run the following command once.

~/code/spike : sbt update

You need to do this every time you change your configuration. SBT will download your dependencies, but only when you ask it to. With everything in place

~/code/spike : sbt
> jetty-run

And there you have it! A web application that does nothing at al on http://localhost:8080!!!

Please note that I started sbt in interactive mode and then started Jetty. If you just run sbt jetty-run then jetty starts and promptly stops. Not as useful as you might imagine.

I know, I know, a second part has gone by without any Vaadin and hardly any Scala. Next time, I promise.

Jun 30

Over time I’ve been becoming increasingly enamoured of Scala. Like many technologies that I come to love, the first two or three times I try them I come away unsatisfied. I don’t know what it is, but some technologies keep me coming back until they click. Scala’s been like that. The first time I was put off by the apparent complexity of the syntax, the second time I was put off when I was stymied by the lack of a useable reflection mechanism. This time round… I’m happy and I feel at home.

So, I’ve been looking round at web frameworks in the Scala world, and there wasn’t a lot that pleased me. I can see why some people would like Lift - if it was 1998 and we hadn’t figured out that the only thing worse than having code in your markup, is having markup in your code. Maybe this is another one of those things I’ll come back to and have a click moment on. But, for now Lift goes in the “bad idea that works only because of the brain power behind it” pile.

So I started looking round for something that lined up better with my personal sensibilities. I’ve often been attracted to Echo, and it looked like it might be what I was looking for - a component framework that would let me write only in Java - or in this case Scala. Development of Echo 2 seems to be mostly at an end and Echo 3 is closing in on a production release.

I want to develop now, the “keeping up with Jones’” part of me doesn’t want to use Echo 2 and the “oh, god, the pain” part of me doesn’t want to use a beta release of a framework in an untested configuration.

Poking around the Echo home page, I came across this post mentioning Vaadin. From a development perspective Vaadin looked very similar to Echo - application centric, everything is written in Java, component based. And they’ve just released a new version (6.0) with some outstanding documentation including the very nifty Book of Vaadin.

I’m a sucker for a well documented open source project, so I’m trying it with Scala rather than Java, and I’ll document my experiments here.

Joonas Lehtinen, who I believe has a connection to Vaadin asked me to report to the Scala or Vaadin mailing lists - once I’ve got a couple of these posts up I’ll drop a link into the Vaadin forums.

PS I’m not picking a fight with the Lift people, I respect them and I wish them every success. I’ve bought the Lift Book and David Pollack’s excellent Scala book, so I’m doing what I can to support the community. Even though I think they’re off in the weeds. Dammit, I didn’t mean to type that out loud.

Jun 20

I’ve just finished listening to The Art of Teaching Entrepreneurship and Innovation by Tina Seelig, a podcast from Stanford’s excellent Technology Ventures Program.

One of the key points I took from the podcast came from a story where Tina had given a group of students $5 and challenged them to create as much value as possible in a set period. Those who did best were those who realised that the $5 was a constraint, not an asset and worked around it. Those who limited themselves to the question, “what can I do with $5?” didn’t do as well as the people who asked themselves “how can I generate value”.

My favourite response was the group of students who, instead of using their $5, sold the presentation slot, where they were supposed to present their results to the university, to a local company who came in and did an advertising pitch. This group realised that the assets they had transcended the obvious raw materials in front of them.

To make the point clearer, in future years Tina substituted the $5 for post-it notes or rubber bands. Whilst the results of people trying to generate value with only a handful of rubber bands was more amusing, I personally think the lesson about looking beyond the obvious was more important. But, Tina Seelig is obviously a smart lady, I’ll trust her vision.

Jun 18

Électricité de France - Alex McGuire hat-tip to Barry Carr for pointing it out.