Developing Java web applications using Vaadin

Benoit Chartron, 123RF.com

Ice Cold

The web application framework (WAP) Vaadin is a useful tool for developing high performance Java applications for the Raspberry Pi.

It can be frustrating after working for weeks on a Raspberry project to have it be rejected by potential users because "there is no place to click" or the project cannot be controlled via a smartphone. Many users do not want to deal with the command line. This means it is important to develop a user friendly web interface for projects. The WAP Vaadin [1] offers an elegant solution This protocol is based on the Google Web toolkit and uses Java as its programming language.

There are a number of reasons to use Vaadin as a protocol for developing applications. Many other protocols are available, and presumably some of these are more lightweight. However, Vaadin holds a decisive advantage because it can be used to develop browser applications without the need for generating even a single line of HTML or JavaScript code from scratch. The application is written like a standard Java applet. The layouts and GUI components are reminiscent of AWT or Swing elements. Vaadin uses these to generate a browser application and thus avoids all the nerve-wracking problems which often accompany the creation of web applications. Experienced web app developers will no doubt agree that some of tsaid problems can take a long time to solve.

The Vaadin project homepage offers a demo area [2] with a preview of how the individual GUI components function (Figure 1), detailed descriptions of the components and source code for the example provided. There is also a free, online book for beginners on how to use Vaadin [3], which can be downloaded after completing a simple registration form. However, while it may be interesting to read about the many benefits of using Vaadin, it is much more fun to try it out on a "live" object.

Figure 1: This I s the demo area on the Vaadin home page. There is a code example and a description for each component.

Preparations

As a first step, you should build a Raspberry Pi server. There is a Light version of Raspbian [4] on the Raspberry Pi home page which can be used for this. This version contains only the bare necessities. As such, you will find neither an X server nor extensive Office programs. In other words it is ideal for a Raspberry Pi based application server. As usual, you should download the image from the Raspberry Pi homepage, decompress it and then write it to an SD card. You can use dd, Win32 Disk Imager if you are running Windows, or any other suitable tool for this task (Listing 1).

Listing 1

raspbian_lite_latest

$ wget https://downloads.raspberrypi.org/raspbian_lite_latest
$ unzip raspbian_lite_latest
$ sudo dd if=2015-11-21-raspbian-jessie-lite.img of=/dev/<ßßI>sdd<ßßI> bs=1M
$ sync

For the dd command you should specify the output device of your system using the command line argument of. When in doubt, use the command lsblk. The date for the image may be more recent than the one given in the example.

After transferring the image, you should insert the SD card into a 2nd or 3rd generation Raspberry Pi and connect the Pi to a power supply. Theoretically, Vaadin should also work with a first generation Raspberry Pi. However, in the interest of full disclosure, it should be noted that running Java on a Raspberry Pi 1 is not really fun. Even with the Raspberry Pi 2, some of the installation steps take quite a bit of time. Luckily the programs run fairly fast once installed.

In order to access the Raspberry Pi at a later date via SSH, activate the corresponding daemon via the configuration tool raspi-config. This step also provides an opportunity for expanding the file system to match it to the full capacity of the SD card. Expansion is important because the project build takes a lot of memory. Next, users of a Linux PC should connect to the mini computer via the command ssh pi@IP-address. Windows users usually rely on PuTTy [5] to connect.

Vaadin poses few challenges to the Java Development Kit (JDK). You don't necessarily need to download and manually install the latest JDK from the Oracle homepage. Instead, install the version of Oracle Java that comes with the Raspbian repository. In order to start the first example of Vaadin, you will also need the build tool Maven which is likewise found in the Raspbian repository. (See info box "Maven"). Update the Raspbian system while doing this. This should be done before installing new software in any case. (Listing 2).

Listing 2

Installing maven

$ sudo apt-get update
$ sudo apt-get dist-upgrade
$ sudo apt-get install oracle-java7-jdk maven

Maven

Maven provides a standardized method for building Java projects. If you pay attention to the pre-defined conventions, you can use this build management tool to create and administer your projects effortlessly. The conventions primarily apply to issues related to project design, such as directory trees and naming conventions.

The central element of Maven is the Project Object Model file, pom.xml. This is where the user specifies any dependencies the project has on other software components. These components then indicate in turn which dependencies exist for other projects. As a consequence, a project tree is formed when Maven first loads. It saves all of these components in its local repository to insure that subsequent build processes run more quickly.

The last parameter indicates that Maven should create a WAR archive. This type of archive contains all libraries, classes and resources needed for the project in the form of a compressed web application. The WAR archive can be rolled out and executed in any Servlet container. Some examples of familiar servlet containers which are also web servers include Apache Tomcat and Jetty. (See info box: "Jetty").

Listing 3

mvn archetype:generate

$ mvn archetype:generate \
  -DarchetypeGroupId=com.vaadin \
  -DarchetypeArtifactId=vaadin-archetype-application \
  -DarchetypeVersion=7.5.10 \
  -DgroupId=local \
  -DartifactId=myproject \
  -Dversion=1.0 \
  -Dpackaging=war
@KE

Jetty

Jetty functions as a servlet container and web server, similarly to Apache Tomcat. In comparison to its Apache counterpart, Jetty requires fewer resources, but it is also less flexible to use. The advantage to this tool lies instead in the ease with which it can be integrated into other projects. For example, the Google Web toolkit has used Jetty as a webserver since Version 1.6.

Executing the initial Maven commands takes some time since the program loads quite a few individual components from the Internet. During the installation Maven asks you whether the project parameters are correct. You should answer with [Y]. Next, switch into the project directory and proceed with the first Vaadin project build. The build will take a particularly long time to complete so take a coffee break to alleviate your boredom. You will need less patience for future builds, as Maven will do incremental rebuilds of those parts which have been modified.

Maven will deposit the finished project and everything that belongs to it in the myproject directory. At that point however, the project is still not executable. You still need to create the archive. This is done using Lines 1 and 2 from Listing 4. In order to start this example application, enter the command from line 3. This command starts a Jetty web server on the Raspberry Pi and makes the application available at http://IP-address:8080/myproject.

Listing 4

jetty

$ cd myproject
$ mvn package
$ mvn jetty:run

The example application (Figure 2) merely provides an introduction to programming with Vaadin. For instance, if you look inside the accompanying source code, you will not find any HTML. Instead, the source code resembles an AWT application.

Figure 2: The first example of a Vaadin application.

Listing 5

MyUIServlet

@Theme("mytheme")
@Widgetset("your.company.MyAppWidgetset")
public class MyUI extends UI {
  @Override
  protected void init(VaadinRequest vaadinRequest) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);
    Button button = new Button("Click Me");
    button.addClickListener(new Button.ClickListener() {
      @Override
      public void buttonClick(ClickEvent event) {
        layout.addComponent(new Label("Thank you for clicking"));
      }
    });
    layout.addComponent(button);
  }
  @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
  @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
  public static class MyUIServlet extends VaadinServlet {
  }
}

Expanding the code

Now you have a fully functioning Vaadin environment. To take your first steps on your own, modify the source code of the demo app and build the project again. This is done by opening a second SSH connection to the Raspberry Pi. Jetty is still running in the first SSH session which you previously started with the mvn jetty:run command.

In this second SSH session, you can do things like open the user interface file which is located in ~/myproject/src/main/java/local. Use a text editor such as Nano or Vi for this. Once the file is opened, you can modify the contents. You might start with changing the name of the button (Listing 6) after which remember to save the file again.

Listing 6

"Light On" Button

[...]
Button button = new Button("Light on");
[...]

Next, rebuild the project with the mvn package command. This command has to be executed in the folder which contains the file pom.xml. Afterwards, you will see in the first SSH window, that Jetty automatically notices the change to the application and rolls it out again.

Now adapt the program so that it talks to the GPIO interface on the Raspberry Pi. The easiest way to do this with Java is to use the Pi4j library. (See info box "Pi4j"). To add the library to your project, all you need to do is enter the library as a dependency in the pom.xml file (Listing 7) and rebuild the project. Afterwards the library will be immediately available for use. The complete pom.xml file for this example is found on the DVD accompanying this issue of Raspberry Pi Geek.

Listing 7

pom.xml (part)

[...]
<dependency>
  <groupId>com.pi4j</groupId>
  <artifactId>pi4j-core</artifactId>
  <version>1.0</version>
</dependency>
[...]

Pi4j

The Pi4j library [10] is derived from the WiringPi tools [9] and is used for accessing the GPIO interface of the Raspberry Pi with Java. If you don't want to work with a tool like Maven, you can manually install the Pi4j library. This is done using the command:

$ curl -s get.pi4j.com | sudo bash

Once installed, the small pi4j tool helps compile and start Java programs.

Now comes the question what to do with this demo application. In order to keep the programming to a minimum, we will try to switch an LED on and off using two buttons on a website. First you will need to tie the positive lead of the LED (usually the longer one), via a series resistance of 220 Ohm to 1 kOhm with Pin 13 of the GPIO. You should tie the negative lead of the diode (usually the shorter of the two), directly to one of the grounding pins.

Now add a second button to the user interface file and label this one "light off". For the programming logic, you should add the contents of Listing 8. Since you are now accessing Raspberry Pi hardware, Jetty needs the correct permissions. Therefore you need to start the service as root via sudo mvn jetty:run. Figure 3 shows how the page looks in the browser after it has been slightly reworked.

Listing 8

"Light Off" Button

package local;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPin;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.Raspberry PiPin;
@Theme("mytheme")
@Widgetset("local.MyAppWidgetset")
public class MyUI extends UI {
  static GpioPinDigitalOutput led=null;
  @Override
  protected void init(VaadinRequest vaadinRequest) {
    final GpioController gpio = GpioFactory.getInstance();
    led = gpio.provisionDigitalOutputPin(Raspberry PiPin.GPIO_13,"LED", PinState.LOW);
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);
    Button buttonOn = new Button("Light on");
    buttonOn.addClickListener(new Button.ClickListener() {
      @Override
      public void buttonClick(ClickEvent event) {
        MyUI.led.high();
      }
    });
    Button buttonOff = new Button("Light off");
    buttonOff.addClickListener(new Button.ClickListener() {
      @Override
      public void buttonClick(ClickEvent event) {
        MyUI.led.low();
      }
    });
    layout.addComponent(buttonOn);
    layout.addComponent(buttonOff);
  }
  @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
  @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
  public static class MyUIServlet extends VaadinServlet {
  }
}
Figure 3: A simple example using two buttons that switch an LED on and off.

Now take a closer look at the demo program (also found on the accompanying DVD) in the RPG/vaadin/ directory. After the typical Java import prelude, the application selects the theme and the widget set via annotations (@...). This is how all of the visuals for the program are specified. Right at the end of the process, you will find two annotations that control the behavior of the servlet. These are the only indications that a web application is involved.

The remaining source code could easily have come from a Java FX application; the code generates two buttons which are connected to a 'listener'. There are anonymous classes inside the listener, each of which carries out specified actions as soon as the user presses one of the buttons. There should be no need for further explanation of the remaining few commands for controlling the GPIO.

Buy this article as PDF

Express-Checkout as PDF

Pages: 6

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content