Home Programming Vaadin 7 Cookbook

Vaadin 7 Cookbook

books-svg-icon Book
eBook $32.99 $22.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $32.99 $22.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Creating a Project in Vaadin
About this book
Publication date:
April 2013
Publisher
Packt
Pages
404
ISBN
9781849518802

 

Chapter 1. Creating a Project in Vaadin

In this chapter, we will cover:

  • Creating a project in Eclipse IDE

  • Generating a Vaadin project in Maven archetype

  • Building a Vaadin application with Gradle

  • Using Vaadin with Scala

  • Running Vaadin on Grails

 

Introduction


Before we start coding, we need a project. Vaadin projects can be created in many ways using several tools and languages.

In this chapter, we will show how to make projects that support three languages: Java, Groovy, and Scala.

First, we will make a simple Java project in Eclipse. Then, we will continue in a more sophisticated way and make a Vaadin application by using Maven and Gradle. Maven is a tool providing a better build process and it uses XML for the description of project, definition of dependencies, plugins, and so on. While Gradle is the next generation of build tools. Gradle combines both Maven and Ant, taking the best from both tools. Maybe the most exciting thing about Gradle is that it is uses Groovy instead of XML.

After we know how to make the project from Maven archetype, we will make the same project in IntelliJ IDEA.

Scala is a programming language that integrates features of object-oriented and functional languages. The server-side part of Vaadin runs on JVM and therefore we can write Vaadin applications in Scala language.

Grails is a web application framework that takes advantage of the Groovy language. Grails follows the convention over configuration principle. When we make a new Grails project, we automatically get a persistent model, service, controller and view layers, environments, and localization. We will have a look at how to create a new Grails project and how to use Vaadin instead of a Grails view layer.

 

Creating a project in Eclipse IDE


In this recipe, we are going to create a new Vaadin project in the Eclipse IDE.

Getting ready

Download and install the latest version from the Eclipse download page (specifically Eclipse IDE for Java EE Developers), http://www.eclipse.org/downloads.

There is an Eclipse extension for Vaadin, which helps us with the creation of Vaadin projects, widget set compilation, and so on. The instructions on how to install the extension are at http://vaadin.com/eclipse.

How to do it...

Carry out the following steps in order to create a new project in Eclipse IDE:

  1. Open the New Project window and search for vaadin.

  2. There should be a few Vaadin wizards listed. Choose Vaadin 7 Project and click on the Next button.

  3. Fill in the name of the project. Select Apache Tomcat v7.0 as Target runtime and click on the Finish button.

  4. Eclipse makes a Hello world application for us. All the application code has been placed in the HellovaadinUI class. Now we can run the project. Right-click on the name of the project, go to Run As, and then click on Run on Server. Choose Apache Tomcat v7.0 to run our application and confirm the dialog window.

  5. The application appears in the Eclipse's Internal Web Browser or we can open the started application in our favorite browser: http://localhost:8080/HelloVaadin.

How it works...

Let's have a look at what has been generated by Eclipse.

The following table explains the content of the important directories:

Directory / Project Item

Description

Deployment Descriptor

Is not a real directory but it offers a user-friendly way to edit the web.xml file.

Java Resources/src

Contains the entire project's Java source code.

WebContent

Contains deployment descriptor file web.xml. We can also place here static resources such as images, CSS, or JavaScript files.

In this folder we can make a VAADIN directory for the new themes.

build

Is used to store compiled classes.

Note

web.xml must contain the definition of the UI class, servlet, and URL mapping. It must be located inside the WEB-INF folder.

There's more...

Now we can try to change the code inside the HellovaadinUI class, so the application prints out the name of the system user.

String user = System.getProperty("user.name");
Label label = new Label("Hello Vaadin user: " + user);
layout.addComponent(label);

Tip

Notice we can see the changes in code without restarting the application server. The project is recompiled after we save a file and changes are visible in the browser right away.

We need to add the ?restartApplication parameter into the URL when running a Vaadin application with the @PreserveOnRefresh annotation on our UI class.

 

Generating a Vaadin project in Maven archetype


Maven makes the build process really easy. Let's see how easy it is to make a new Vaadin project using Maven. We will use the latest version, Maven 3, which can be downloaded from http://maven.apache.org/download.html.

We are going to use the command line in this recipe. We will make the project in the command prompt and then we can import the Maven project into whatever IDE that supports Maven (Eclipse, IntelliJ IDEA, and so on).

Using Maven archetypes is quite handy and a quick way to create a new project. Let's try to make a new Vaadin project using the vaadin-archetype-application archetype.

For those who are new to Maven, please learn the basics from the following web page:

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

How to do it...

Carry out the following steps in order to create a new project in Maven:

  1. Open the command prompt and check whether Maven is installed properly. The version of Maven should be displayed. If not, then search the Web for how to install Maven 3 on your operating system.

    $ mvn --version
    Apache Maven 3.0.4
    Maven home: /usr/share/maven
    
  2. Decide where to put your project and run the following command. It will create a new folder called vaadin-in-maven-arch with a sample Vaadin project using the Maven file structure.

    mvn archetype:generate \
     -DarchetypeGroupId=com.vaadin \
     -DarchetypeArtifactId=vaadin-archetype-application \
     -DarchetypeVersion=LATEST \
     -Dpackaging=war \
     -DgroupId=app \
     -DartifactId=vaadin-in-maven-arch \
     -Dversion=1.0 
    
  3. Maven asks for confirmation of whether to create the project. Type y into the console. Maven will show its BUILD SUCCESS message after the project is created.

    Confirm properties configuration:
    groupId: app
    artifactId: vaadin-in-maven-arch
    version: 1.0
    package: app
     Y: : y
    
  4. Run the package Maven target in order to pack the application as a WAR file and compile the widget set. Run the following command in the root of the project.

    mvn package
    
  5. We are done and we can run our new web application. Go to the root of the project where pom.xml file is located and run the following command.

    mvn jetty:start
    

    The application will be running on http://localhost:8080.

Tip

We are using Jetty, which is open source and a commercially usable web server. Jetty is great for development because it starts really fast.

How it works...

We have made a new Vaadin application from the Maven archetype and all the content needed for running the application was generated fr us.

Let's have a look at the folder structure in the project.

Directory / Project Item

Description

pom.xml

Is a Maven configuration file. POM stands for Project Object Model.

src/main/java

Contains the entire project's Java source code.

src/main/webapp/WEB-INF

Contains web.xml, the deployment descriptor.

src/main/webapp/VAADIN

Contains a compiled widget set and can contain new Vaadin themes.

target

Used to place the output from compilation.

Maven archetype could be described as a project template. We can create our own archetypes by running the following command inside the Maven project:

mvn archetype:generate

There's more...

We can configure auto-redeploys in Jetty. The scanning interval can be set to, for example, 2 seconds. After we recompile the code, Jetty redeploys the application so we don't have to stop and start the application server after each change in the code. The following change needs to be made in the pom.xml file:

<scanIntervalSeconds>2</scanIntervalSeconds>

More about the Jetty plugin can be found on the following link:

http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin

 

Building a Vaadin application with Gradle


Gradle is the next generation of builds tools. It helps with building, publishing, deploying, and actually any other task which should be automated.

Gradle build scripts are written in Groovy, which makes this build tool really straightforward and easy to use. In this recipe, we are going to use the Groovy language.

We will use the Gradle plugin for Vaadin, which makes the development of Vaadin applications in Groovy really luxurious.

Getting ready

Let's install Gradle before we start from http://gradle.org/installation.

Create a new directory where we will place the new project:

mkdir vaadin-in-gradle

How to do it...

Carry out the following steps in order to create a new project in Gradle:

  1. Create a file build.gradle in the project root. It is going to be just one line that is necessary for running the project.

    apply from: 'http://plugins.jasoft.fi/vaadin.plugin'
    
  2. Run the createVaadinProject target and fill in the name of the application and package. Alternatively, just press the Enter key twice and let the plugin create the default application inside the default package.

    gradle createVaadinProject
    
  3. Run target vaadinRun, which starts up the embedded Jetty web server, and the application will be deployed.

    gradle vaadinRun
    

    The URL of the web server is printed out in the console as follows:

    :themes
    :compileJava
    :processResources UP-TO-DATE
    :classes
    :widgetset
    :vaadinRun
    Application running on http://0.0.0.0:8080 (debugger on 8000)
    > Building > :vaadinRun
    

How it works...

Gradle is following the convention over configuration paradigm and that is why Gradle build scripts are so minimalistic. For example, the default source folder for Groovy files is src/main/groovy and we can change it by the following code that we place inside the build script build.gradle.

sourceSets {
  main {
    groovy {
      srcDirs = ['src/groovy']
    }
  }
}

The next valuable thing about Gradle is good documentation:

http://www.gradle.org/docs/current/userguide/userguide_single.html

Let's have a bit more detailed look at what the Gradle plugin for Vaadin did for us.

When we run the createVaadinProject target, the plugin creates two files. MyApplication.groovy inside com.example.myapplication package and web.xml in src/main/webapp/WEB-INF folder.

Directory / Project Item

Description

build.gradle

Gradle build script.

src/main/groovy

Contains Groovy source code.

src/main/webapp/

Contains WEB-INF/web.xml, the deployment descriptor.

The plugin also defines the vaadinRun target that starts up the Jetty web server and deploys the application.

There's more...

There are other targets such as createVaadinTheme, devmode, widgetset, and more in the Vaadin plugin. All these, and more information about the plugin configuration, can be found on the GitHub page:

https://github.com/johndevs/gradle-vaadin-plugin

 

Using Vaadin with Scala


Scala is a multi-paradigm language integrating object-oriented and functional programming. Read more about Scala on http://www.scala-lang.org.

Getting ready

Scala installation is quite easy. Just go to http://www.scala-lang.org/downloads, download Scala, and set up system variables as follow:

  • Linux/Mac

    SCALA_HOME=/Users/John/Installations/scala
    export SCALA_HOME
    export PATH=$PATH:$SCALA_HOME/bin
    
  • Windows

    %SCALA_HOME% = c:\Scala
    %PATH% = %PATH%;%SCALA_HOME%\bin
    

We have to maintain our project anyhow and we are going to utilize Gradle.

Tip

There is also another way to manage Scala projects. It is called Typesafe and more info is on http://typesafe.com.

How to do it...

Carry out the following steps in order to create a new Scala project:

  1. Make the project structure so we have folders where we can put our project files.

    mkdir -p vaadin-in-scala/src/main/{scala/app,webapp/WEB-INF}
    
  2. Make build.gradle in the project root. It is going to be just a few lines that are necessary for running the project.

    apply plugin: 'war'
    apply plugin: 'jetty'
    apply plugin: 'scala'
        
    repositories {
      mavenCentral()
    }
        
    dependencies {
      scalaTools 'org.scala-lang:scala-compiler:2.10.0'
      scalaTools 'org.scala-lang:scala-library:2.10.0'
      compile 'org.scala-lang:scala-library:2.10.0'
      compile group:'com.vaadin', name:'vaadin-server', version:'7.0.4'
      compile group:'com.vaadin', name:'vaadin-client', version:'7.0.4'
      compile group:'com.vaadin', name:'vaadin-client-compiled', version:'7.0.4'
      compile group:'com.vaadin', name:'vaadin-themes', version:'7.0.4'
      compile group:'com.vaadin', name:'vaadin-client-compiler', version:'7.0.4'
    }
    
  3. Create a new Scala class MyVaadinUI that we place into the MyVaadinUI.scala file in the folder src/main/scala/app.

    package app
    
    import com.vaadin.ui._
    import com.vaadin.server.VaadinRequest
    
    class MyVaadinUI extends UI {
      def init(request: VaadinRequest) = {
        val layout = new VerticalLayout()
        layout.setMargin(true)
        setContent(layout)
        layout.addComponent(new Label("Hello Vaadin user."))
        }
    }
  4. Add the web.xml file to the src/main/webapp/WEB-INF folder.

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>Vaadin Web Application</display-name>
      <context-param>
        <description>Vaadin production mode</description>
        <param-name>productionMode</param-name>
        <param-value>false</param-value>
      </context-param>
      <servlet>
        <servlet-name>Vaadin Application Servlet</servlet-name>
        <servlet-class>com.vaadin.server.VaadinServlet</servlet-class>
        <init-param>
          <description>Vaadin UI to display</description>
          <param-name>UI</param-name>
          <param-value>app.MyVaadinUI</param-value>
        </init-param>
      </servlet>
      <servlet-mapping>
        <servlet-name>Vaadin Application Servlet</servlet-name>
        <url-pattern>/*</url-pattern>
      </servlet-mapping>
    </web-app>
  5. We are done and we can run the application.

    gradle jettyRun
    

    The following output should be displayed:

    :compileJava UP-TO-DATE
    :compileScala UP-TO-DATE
    :processResources UP-TO-DATE
    :classes UP-TO-DATE
    > Building > :jettyRun > Running at http://localhost:8080/vaadin-in-scala
    

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

How it works...

We have made a Gradle project in which we have applied the scala plugin. The Scala plugin inside the Gradle build script ensures that all the .scala files inside the src/main/scala source folder will be compiled. Scala files are compiled to .class files that are then deployed on the Jetty webserver.

The deployment descriptor (web.xml file) defines one servlet. When users access the URL with the /* pattern, which is mapped to the Vaadin servlet, MyVaadinUI is shown in the browser.

The important thing we need to check is the init-param element of the Vaadin servlet. It needs to point exactly to the UI class, which represents our application. The path to the UI class must be the full name of the class together with the package, for example, app.MyVaadinUI.

See also

 

Running Vaadin on Grails


Grails is a web application framework, which uses the Groovy language, following the coding by convention paradigm. All the information about Grails can be found at the following link:

http://grails.org

The Grails plugin called vaadin integrates Vaadin into the Grails project. Therefore, we can use Vaadin as a replacement for the Grails view layer. Instead of writing HTML, CSS, and JavaScript, we make Vaadin view in Groovy. More information about the Vaadin integration is available at the following web page:

http://vaadinongrails.com

We are going to make a simple Vaadin application that will be running on Grails and written in Groovy.

Getting ready

Install the Eclipse Groovy/Grails Tool Suite (GGTS). download link is available at the Grails pages at http://grails.org/products/ggts.

Tip

If you are running on Windows, then install GGTS to a folder that does not contain white spaces (for example, C:\EclipseSTS).

How to do it...

Carry out the following steps in order to create a new Grails project with Vaadin:

  1. Open File | New | Grails Project.

  2. Fill in the name of the project and finish the New Grails Project wizard.

  3. Click on the Grails icon, which opens the console that we use for running the Grails command. In this step, we just want to make sure the project is created properly. Run the run-app command.

  4. The Grails application is opened up in the browser window using http://localhost:8080/vaadin-in-grails. It still uses .gsp files, which we replace with Vaadin in the next step.

  5. Install the Vaadin plugin. Open up the Grails console and run the following command:

     install-plugin vaadin
    
  6. Mark the grails-app/vaadin folder as the source folder.

  7. Run the application again and open http://localhost:8080/vaadin-in-grails in the browser. Vaadin has replaced the Grails view.

How it works...

We have made a Grails project where we have replaced the Grails view layer with a Vaadin framework. The integration between Grails and Vaadin is done by the Grails plugin that is connecting these two frameworks. As you have experienced, the Vaadin plugin is available via the Grails plugin system (http://grails.org/plugin/vaadin).

Let's have a close look at what the Vaadin plugin has generated for us.

The MyUI.groovy file has been generated inside the grails-app/vaadin source folder. MyUI represents the Vaadin user interface, which is shown to the user in the browser window.

package app

import com.vaadin.ui.UI
import com.vaadin.ui.VerticalLayout
import com.vaadin.server.VaadinRequest
import com.vaadin.ui.Label
import com.vaadin.grails.Grails

class MyUI extends UI {

  @Override
  protected void init(VaadinRequest vaadinRequest) {
    VerticalLayout layout = new VerticalLayout()
    String homeLabel = Grails.i18n("default.home.label")
    Label label = new Label(homeLabel)
    layout.addComponent(label)
    setContent(layout)
  }
}

We should store all the Vaadin code we create inside the grails-app/vaadin source folder.

The Vaadin plugin needs to have information about the location of the MyUI class in order to add that information to the web.xml deployment descriptor. Therefore, a new file VaadinConfig.groovy has been generated inside the grail-app/conf folder.

vaadin {
  mapping = [ "/*": "app.MyUI" ]
  productionMode = false
}

environments {
  production {
    vaadin {
      productionMode = true
    }
  }
}

In VaadinConfig.groovy, we can change the path to the UI class. We can also add more UI classes.

vaadin {
  mapping = [ "/*": "app.MyUI", "/ui/*": "app.YourUI" ]

The last thing which has been done during the plugin installation is the removal of the URL mapping inside the UrlMappings.groovy file.

Tip

If we make changes in the code, then the code is recompiled and we don't have to restart the server (just refresh the web page).

Changes on class level (for example, a change of parent class) are not recompiled and we have to restart the application.

See also

Latest Reviews (1 reviews total)
Très bon livre de "trucs et astuces" Vaadin 7. Les problématiques qui y sont abordées sont celles que nous avons tous ou presque tous.
Vaadin 7 Cookbook
Unlock this book and the full library FREE for 7 days
Start now