Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Vaadin 7 Cookbook
Vaadin 7 Cookbook

Vaadin 7 Cookbook: Take the shortcut to developing rich internet applications in pure Java. Vaadin makes it easy and this cookbook makes it easier still with its practical recipes and straightforward approach.

$32.99 $22.99
Book Apr 2013 404 pages 1st Edition
eBook
$32.99 $22.99
Print
$54.99
Subscription
$15.99 Monthly
eBook
$32.99 $22.99
Print
$54.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Apr 24, 2013
Length 404 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781849518802
Category :
Languages :
Table of content icon View table of contents Preview book icon Preview Book

Vaadin 7 Cookbook

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

Left arrow icon Right arrow icon

Key benefits

What you will learn

Develop a Rich Internet Application in pure Java language. Create a Vaadin project in different IDEs and platforms. Explore the new Vaadin 7 features such as Extensions, URI fragments, Converter mechanism, and more. Understand and use different types of layouts. Use build-in atomic components such as button, table, text field, and more. Bind model to components and fetch data from the database lazily. Work with listeners and events and improve your web application by adding server-push add-ons. Integrate Vaadin into the Grails framework.

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Apr 24, 2013
Length 404 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781849518802
Category :
Languages :

Table of Contents

19 Chapters
Vaadin 7 Cookbook Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Authors Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Creating a Project in Vaadin Chevron down icon Chevron up icon
2. Layouts Chevron down icon Chevron up icon
3. UI Components Chevron down icon Chevron up icon
4. Custom Widgets Chevron down icon Chevron up icon
5. Events Chevron down icon Chevron up icon
6. Messages Chevron down icon Chevron up icon
7. Working with Forms Chevron down icon Chevron up icon
8. Spring and Grails Integration Chevron down icon Chevron up icon
9. Data Management Chevron down icon Chevron up icon
10. Architecture and Performance Chevron down icon Chevron up icon
11. Facilitating Development Chevron down icon Chevron up icon
12. Fun Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.