Vaadin Programming Cookbook PDF
Vaadin Programming Cookbook PDF
Contents
Preface
Vaadin is an open source web framework for rich Internet applications. In contrast to JavaScript libraries and browser-plugin
based solutions, it features a server-side architecture, which means that the majority of the logic runs on the servers. Ajax
technology is used at the browser-side to ensure a rich and interactive user experience. On the client-side Vaadin is built on top
of and can be extended with Google Web Toolkit.
Vaadin uses Java as the programming language for creating web content. The framework incorporates event-driven programming
and widgets, which enables a programming model that is closer to GUI software development than traditional web development
with HTML and JavaScript. (Source: https://en.wikipedia.org/wiki/Vaadin)
In this ebook, we provide a compilation of Vaadin programming examples that will help you kick-start your own projects.
We cover a wide range of topics, from Architecture and Best Practices, to Data Binding and Custom Components. With our
straightforward tutorials, you will be able to get your own projects up and running in minimum time.
Vaadin Programming Cookbook ix
Jesus is a self taught programmer who began programming back in 1991 using an IBM A10 mainframe with Pascal an Assembler
IBM 360/70 emulator and Turbo C on a X86 PC. Since that he has been working for the banking industry with emerging
technologies like Fox Pro, Visual Fox Pro, Visual Basic, Visual Cpp, Borland Cpp.
Lately he has moved out to the Airline industry, leading designing and programming in-house web applications with Flex,
Actionscript, PHP, Python and Rails and in the last 7 years he has focused all his work in Java, working on Linux servers using
GlassFish, TomCat, Apache and MySql.
Vaadin Programming Cookbook 1 / 134
Chapter 1
The design is the most important part of a program, because a bad design produces bad software. A solid rock design increases
the chance of getting good results, of course you still need good programmers but its easier to correct clumsy code with a good
design. Anyway how do you define code quality or clumsy code? If the code works and no bugs arise in the final product, could it
be improved?. Is the language we are using the best to solve my problem?. Am i using the right platform to deploy my software?.
All these questions are the nightmare of software architects. The design produces the architecture of the software and the amount
of parts my system has. The architecture refers to the high level structures of a software system, its a discipline. Each structure
has software elements. The architecture of a software system is similar to the architecture in buildings. Where the design is the
blueprint of the building, the architecture is the technique used to build and each part of the building is a piece of software. In
the architecture of the software its recommended for a lot of architects to have a rigid division of concerns like Model-View-
Presenter, Model-View-Controller, etc. But in the end if you are the architect of the system, all of these choices are up to you,
just build your software in the best way you can and live with the consequences. In my own experience in pro of the peace of
mind is better to use some kind of separation of concerns in the software architecture.
Java JDK 8
Latest Eclipse Mars
Vaadin 7.6.5
Tomcat Server 8
1.2 Introduction
Vaadin Framework 7 is a server side web framework that uses Ajax to keep the UI synchronized with the server. Usually on each
user interaction, Vaadin makes one or more Ajax calls against the server to "keep the server informed" whats going on with the
UI. You can change this behavior but its better to keep the server side nature of Vaadin. This design was done to secure your
data, so its better to keep it that way. Vaadin consists of three separate layers. In this tutorial we are going to see with a simple
application how the Vaadin architecture works and where is every part of the architecture when you are coding.
1.3 Prerequisites
JDK installed
Eclipse Mars installed and working
Vaadin Programming Cookbook 2 / 134
Client widgets
Web Server layer
Persistence layer
Vaadin Programming Cookbook 4 / 134
The client widgets are the user interface elements that are shown in the browser. These widgets are a combination of HTML and
JavaScript, the native execution environment for browsers. Vaadin makes extensive use of GWT - Google Widget Toolkit, while
GWT is an open source set of tools that allows web developers to create complex JavaScript applications in Java. With Vaadin
you can also create your widgets using HTML, JavaScript and CSS directly. The client widgets compose the user interface in
a regular Vaadin application and usually each widget has a server counterpart that keeps the user interaction always server side,
preventing data loss.
This layer is a Java servlet or a portlet that is in charge of intercept the requests of the widgets and send a response to update the
UI. Moreover, it can make asynchronous calls to the widgets like server push calls to update the UI without user interaction.
Java Servlet A Java servlet is a Java program that runs within a Web server. Servlets usually use the Request-response message
exchange pattern defined by the HyperText Transfer Protocol. Servlets are also capable of make asynchronous server push on
any time required.
Portlets Portlets are pluggable user interface software components. A portlet UI is just like a regular Vaadin application, and is
used like pieces of a web page with complete and concise functionality. Like a weather gadget that has a well known function,
porlets are commonly used in enterprise portals like Liferay.
The persistence layer is in charge of the data in the application. This layer usually has an interface with a database or an in-
memory datasets or a library to store data in the file-system or whatever persistence method you have. If your application needs
Vaadin Programming Cookbook 5 / 134
to store data this is the place where you put the code to manage all you need to save the data.
1.5.2.1 Persistence
We are going to simulate persistence with an ArrayList, this is for the purpose of this tutorial. But you can plug here a database
or write files on disk or connect to the cloud and save your data there.
Persistence
private ArrayList myArrayList;
public VaadinArchPersistence(){
myArrayList = new ArrayList();
}
We have here a private ArrayList called myArrayList to store our data, in this case a string.
A constructor public VaadinArchPersistence() to initialize our ArrayList, this only lasts until you refresh the page.
On every page refresh all data is lost. A persistence container should save the data in a more durable media.
public void addItem(String item) is a method to add an item to our collection. This method also checks that the
item is not empty. This is the place to validate your data, when you send the data to a external medium that data must be validated
before. Also here you need to check the security to avoid database exploits, because a malicious user could found vulnerabilities
in your application if you didnt put a filter between layers.
public String getItems() is a method to get all our items into a big string to show all items.
With that we can simulate a persistence fully working layer.
When you start a Vaadin application opening a web page the VaadinServlet calls the Init method. In the Init method
we create the components. These components are server side with a client side counterpart. This example has a textbox to input
text from the client to the persistence layer, a button to send the text in the textbox to the server, a button to retrieve all items
added from the server and a label to show the items.
The layout
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
The Label to show the items stored, we need to create mylabelstyle on the client CSS.
Add Item
Button bAddItem = new Button("Add Item");
bAddItem.setWidth("200px");
bAddItem.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
vap.addItem(tf.getValue());
tf.clear();
}
});
Vaadin Programming Cookbook 7 / 134
The Abstract component shares the state with the abstract component connector in order to keep the state synchronized between
the client and the server part of the component/widget. GWT creates the client widget with the closure compiler. The widget
calls the Abstract component connector. The abstract component connector then updates the state and make Ajax calls to the
Abstract component that is server side.
The client uses the GWT compiler to convert the Java code into JavaScript and the JavaScript is also compiled with the Google
closure compiler to optimize it. Now lets compile the widgetset. Click on the Vaadin toolbar menu and compile the widgetset:
In this folder you have the compiled widget-sets into JavaScript, you have a version for each browser supported and you also
have "gz" compressed versions to send it instead when is supported. Vaadin take in charge of all these details for you. So you
only need to know how to write the Java code and forget about these details until you need to write your own components.
VaadinarchitectureUI.java
package com.example.vaadinarchitecture;
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.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
Vaadin Programming Cookbook 10 / 134
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@SuppressWarnings("serial")
@Theme("vaadinarchitecture")
public class VaadinarchitectureUI extends UI {
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
VaadinArchPersistence vap = new VaadinArchPersistence();
layout.addComponent(tf);
layout.addComponent(bAddItem);
layout.addComponent(bShowItems);
layout.addComponent(lItems);
}
VaadinArchPersistence.java
package com.example.vaadinarchitecture;
import java.util.ArrayList;
import java.util.Iterator;
public VaadinArchPersistence(){
myArrayList = new ArrayList();
}
vaadinarchitecture.scss
@import "../valo/valo.scss";
@mixin vaadinarchitecture {
@include valo;
.v-label-mylabelstyle {
color: white;
text-align: left;
background-color: black;
border-color: white;
font-weight: bold;
}
}
Right click on the project folder and choose Run as Run on server choose Tomcat 8 server and hit finish.
1.8 Results
As you run the application you get a text box with two buttons
Vaadin Programming Cookbook 12 / 134
Press the CONTROL+SHIFT+i key combination in the browser window to get to the console. Locate the Network tab and press
the buttons of the application. As you can see, every time you press a button the client tier makes an Ajax call to the server.
Chapter 2
An application is a computer program created to perform a group of useful tasks for an end user. Application could be a vast
topic to cover, just because a simple "Hello World" program is an application. Most applications do much more than only print a
hello message on the user interface.
The "Hello world" application is useful as an initial program when you are learning a new programming language to illustrate
the basic syntax for constructing a working program and get it to run on a computer. The first "Hello World" application was
created by Brian Kernigham in a internal memorandum of Bell Laboratories "Programming in C a tutorial".
Java JDK 8
Latest Eclipse Mars
Vaadin 7.6.6
Tomcat Server 8
2.2 Introduction
In this example we are going to create a sample Vaadin application to show common widgets interacting with each other. We
generate a character sheet for an RPG game using random values. If the values appeal to us, we could save them for later use.
This application could be useful to you if you play tabletop RPG games but further than that, is an application to illustrate some
common Vaadin widgets working together.
2.3 Prerequisites
JDK installed
Eclipse Mars installed and working
Vaadin plug-in installed
Class variables
private Table attr;
private Table savedAttr;
private Item str;
private Item con;
private Item nte;
Vaadin Programming Cookbook 16 / 134
We declared two tables and five items to manage our data, also a random instance to generate random numbers.
Layouts
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
We create the layouts, a main vertical layout, a horizontal layout for the first row of the main layout and a vertical layout to place
the buttons of the application.
CellStyleGenerator
CellStyleGenerator myCellColors = new CellStyleGenerator() {
@Override
public String getStyle(Table source, Object itemId, Object propertyId) {
if(propertyId!=null){
Item item = source.getItem(itemId);
if(item.getItemProperty(propertyId).getValue().getClass()==Integer. -
class){
Integer cellValue = (Integer)item.getItemProperty( -
propertyId).getValue();
if(cellValue > 15 && cellValue 17){
return "green";
}
if(cellValue < 8){
return "red";
}
}
}
return null;
}
};
This CellStyleGenerator changes the color of individual cells based on its value. First we check that the cell is no empty
with if(propertyId!=null). Then we get the Item in the cell with Item item =source.getItem(itemId);.
We then Check the value of the Item and verify that is an integer with if(item.getItemProperty(propertyId).
getValue().getClass()==Integer.class).
If the value is an Integer, we cast it to a local variable with Integer cellValue =(Integer)item.getItemProper
ty(propertyId).getValue(); and based on the value of the variable we set the colors of the cells in the table.
Attributes Table
attr = new Table("Attributes");
attr.addContainerProperty("Attribute", String.class, null);
attr.addContainerProperty("Value", Integer.class, 0);
Vaadin Programming Cookbook 17 / 134
attr.setPageLength(attr.size());
attr.setSelectable(false);
attr.setImmediate(true);
attr.setFooterVisible(false);
attr.setCellStyleGenerator(myCellColors);
This table is going to have the generated values, one string column with the name of the attribute and an integer column holding
the value of that attribute. We create the table with attr =new Table("Attributes");. attr is a class field. attr.
addContainerProperty("Attribute", String.class, null); defines the first value data type as string.
attr.addContainerProperty("Value", Integer.class, 0); defines the second column data type as integer.
With attr.setPageLength(attr.size()); we constrain the size of the table on the screen to the size of the data
contained on it.
attr.setSelectable(false);, the user cannot select the rows on the table.attr.setImmediate(true); set im-
mediate tells the application to send any changes on the table to the server, when they occur. Hide the footer of the table attr.
setFooterVisible(false);.
And tell the table to use our custom cell style generator attr.setCellStyleGenerator(myCellColors);.
Helper initialization
rnd = new Random();
createCharacterTable();
rnd =new Random(); initializes the random number generator. createCharacterTable();, calls a custom method
to fill the table with the initial values. This is explained later on this article.
Table of saved attributes
savedAttr = new Table("Saved Rolls");
savedAttr.setSizeFull();
savedAttr.addContainerProperty("Name", String.class, "");
savedAttr.addContainerProperty("Strength", Integer.class, 0);
savedAttr.addContainerProperty("Constitution", Integer.class, 0);
savedAttr.addContainerProperty("Intelligence", Integer.class, 0);
savedAttr.addContainerProperty("Agility", Integer.class, 0);
savedAttr.addContainerProperty("Wisdom", Integer.class, 0);
savedAttr.setCellStyleGenerator(myCellColors);
This table is going to have the saved data of our application.savedAttr =new Table("Saved Rolls"); creates the
table.savedAttr.setSizeFull(); sets the size of the table to fit all the space available.
Button reroll
Button reroll = new Button("Reroll");
reroll.setWidth("200px");
reroll.setIcon(FontAwesome.DIAMOND);
reroll.addStyleName("friendly");
reroll.addClickListener(new ClickListener() {
@SuppressWarnings("unchecked")
@Override
public void buttonClick(ClickEvent event) {
str.getItemProperty("Value").setValue(getReroll());
con.getItemProperty("Value").setValue(getReroll());
nte.getItemProperty("Value").setValue(getReroll());
agi.getItemProperty("Value").setValue(getReroll());
wis.getItemProperty("Value").setValue(getReroll());
}
});
With this button we randomize all attributes with new values. Button reroll =new Button("Reroll"); creates the
button. reroll.setWidth("200px"); sets the width of the button to "200px". reroll.setIcon(FontAwesome.
DIAMOND); assigns an icon to the button using fontawesome that is shipped with Vaadin out of the box.
reroll.addStyleName("friendly"); adds the Vaadin friendly style to the button, this style is predefined in Vaadin.
reroll.addClickListener(new ClickListener() adds the listener to the button, inside the listener we call str.
getItemProperty("Value").setValue(getReroll()); to get a new strength value using getReroll() method
that is explained later.
The same procedure is done with all attributes in the table to get new random values.
Name TextField
TextField name = new TextField("Character Name");
name.setRequired(true);
name.setWidth("200px");
With TextField name =new TextField("Character Name"); we create the text field to input the name of the
character. name.setRequired(true); sets the field required. name.setWidth("200px"); sets the width of the field
the same as the buttons.
Button save
Button save = new Button("Save");
save.addStyleName("primary");
save.setIcon(FontAwesome.SAVE);
save.setWidth("200px");
save.addClickListener(new ClickListener()
Create a new button with Button save =new Button("Save");. save.addStyleName("primary"); assigns
style primary to the button. save.setIcon(FontAwesome.SAVE); sets an icon for font awesome.
save.setWidth("200px"); sets the width to the button to 200 pixels. save.addClickListener(new ClickLis
tener() adds a click listener to the button.
Save click listener
public void buttonClick(ClickEvent event) {
int istr = (int) str.getItemProperty("Value").getValue();
int icon = (int) con.getItemProperty("Value").getValue();
int inte = (int) nte.getItemProperty("Value").getValue();
int iagi = (int) agi.getItemProperty("Value").getValue();
int iwis = (int) wis.getItemProperty("Value").getValue();
Vaadin Programming Cookbook 19 / 134
if((istr != 0) && (icon != 0) && (inte != 0) && (iagi != 0) && (iwis != 0)){
if(name.isEmpty()){
Notification.show("The name is required");
}else{
String cName = name.getValue();
if(findDuplicates(cName)){
Notification.show("Name is duplicated");
}else{
Object savedAttrId = savedAttr.addItem();
Item nSavAttr = savedAttr.getItem(savedAttrId);
nSavAttr.getItemProperty("Name").setValue(cName);
nSavAttr.getItemProperty("Strenght").setValue(istr);
nSavAttr.getItemProperty("Constitution").setValue(icon);
nSavAttr.getItemProperty("Intelligence").setValue(inte);
nSavAttr.getItemProperty("Agility").setValue(iagi);
nSavAttr.getItemProperty("Wisdom").setValue(iwis);
name.setValue("");
Notification.show("Character saved!");
}
}
}else{
Notification.show("You must generate a character first");
}
When the save button is clicked the click listener is called by the framework. int istr =(int) str.getItemProper
ty("Value").getValue(); gets the value of strength and cast it to an integer. int icon =(int) con.getItemP
roperty("Value").getValue(); gets the value of constitution and cast it to an integer. int icon =(int) nte.
getItemProperty("Value").getValue(); gets the value of intelligence and cast it to an integer.
int inte =(int) agi.getItemProperty("Value").getValue(); gets the value of agility and cast it to an
integer. int iwis =(int) wis.getItemProperty("Value").getValue(); gets the value of wisdom and cast
it to an integer. if((istr !=0) && (icon !=0) && (inte !=0) && (iagi !=0) && (iwis !=0)) checks
the values has been generated.
Otherwise a notification is send to the user. name.isEmpty() checks the name is no empty. If the name is empty a notification
is triggered.String cName =name.getValue() gets the name into a string variable. findDuplicates(cName)
check if the name is already used.
When all conditions are meet then we proceed to save the character into the saved rolls table. Object savedAttrId =
savedAttr.addItem(); creates a new object from the saved attributes table. Item nSavAttr =savedAttr.getIt
em(savedAttrId); gets the item from the container.
nSavAttr.getItemProperty("Name").setValue(cName); sets the value of the name into the saved attribute con-
tainer, also we set all other properties from the container with the values we already have.
nSavAttr.getItemProperty("Strenght").setValue(istr); sets the strength. nSavAttr.getItemPrope
rty("Constitution").setValue(icon); sets the constitution.
nSavAttr.getItemProperty("Intelligence").setValue(inte); sets the intelligence. nSavAttr.getIte
mProperty("Agility").setValue(iagi); sets the agility. nSavAttr.getItemProperty("Wisdom").set
Value(iwis);.
Now we set the name text field to an empty string and send a notification to the user indicating that the character has been saved.
Add the widgets to the layouts
butLay.addComponent(butLabel);
butLay.addComponent(reroll);
butLay.addComponent(save);
butLay.addComponent(name);
topHorLay.addComponent(attr);
Vaadin Programming Cookbook 20 / 134
topHorLay.addComponent(butLay);
layout.addComponent(topHorLay);
layout.addComponent(savedAttr);
We add the buttons to the vertical butLay layout and then we add the attr table and the butLay to the horizontal topHor
Lay layout. Finally we add the topHorLay layout and the savedAttr table to the main layout.
createCharacterTable method
private void createCharacterTable()
{
Object strItemId = attr.addItem();
str = attr.getItem(strItemId);
str.getItemProperty("Attribute").setValue("STR");
str.getItemProperty("Value").setValue(0);
This method populate the attr table with two columns attribute and value and each row is an attribute used.
getReroll method
private int getReroll(){
return rnd.nextInt(19)+1;
}
This method generates random integers to get the values of the attributes.
findDuplicates method
private boolean findDuplicates(String newName){
for(Iterator i = savedAttr.getItemIds().iterator(); i.hasNext();){
if(newName.toLowerCase().equals(curName.toLowerCase())){
return true;
}
}
Vaadin Programming Cookbook 21 / 134
return false;
}
This method returns true if a name already exist in the saved attributes table.
VaadinappexampleUI.java
package com.example.vaadinappexample;
import javax.servlet.annotation.WebServlet;
import java.util.Iterator;
import java.util.Random;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Item;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.CellStyleGenerator;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
@SuppressWarnings("serial")
@Theme("vaadinappexample")
public class VaadinappexampleUI extends UI {
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
topHorLay.setSpacing(true);
@Override
public String getStyle(Table source, Object itemId, Object -
propertyId) {
if(propertyId!=null){
Item item = source.getItem(itemId);
if(item.getItemProperty(propertyId).getValue(). -
getClass()==Integer.class){
Integer cellValue = (Integer)item. -
getItemProperty(propertyId).getValue();
if(cellValue > 15 && cellValue 17){
return "green";
}
if(cellValue < 8){
return "red";
}
}
}
return null;
}
};
@SuppressWarnings("unchecked")
@Override
public void buttonClick(ClickEvent event) {
Vaadin Programming Cookbook 23 / 134
str.getItemProperty("Value").setValue(getReroll());
con.getItemProperty("Value").setValue(getReroll());
nte.getItemProperty("Value").setValue(getReroll());
agi.getItemProperty("Value").setValue(getReroll());
wis.getItemProperty("Value").setValue(getReroll());
}
});
@SuppressWarnings("unchecked")
@Override
public void buttonClick(ClickEvent event) {
int istr = (int) str.getItemProperty("Value").getValue();
int icon = (int) con.getItemProperty("Value").getValue();
int inte = (int) nte.getItemProperty("Value").getValue();
int iagi = (int) agi.getItemProperty("Value").getValue();
int iwis = (int) wis.getItemProperty("Value").getValue();
}
});
butLay.addComponent(butLabel);
butLay.addComponent(reroll);
butLay.addComponent(save);
butLay.addComponent(name);
topHorLay.addComponent(attr);
topHorLay.addComponent(butLay);
layout.addComponent(topHorLay);
layout.addComponent(savedAttr);
}
@SuppressWarnings("unchecked")
private void createCharacterTable()
{
Object strItemId = attr.addItem();
str = attr.getItem(strItemId);
str.getItemProperty("Attribute").setValue("STR");
str.getItemProperty("Value").setValue(0);
if(newName.toLowerCase().equals(curName.toLowerCase())){
return true;
}
Vaadin Programming Cookbook 25 / 134
}
return false;
}
}
vaadinappexample.scss
@import "../valo/valo.scss";
@mixin vaadinappexample {
@include valo;
.v-table-cell-content-green {
background: #33BB00;
color: #FFFFFF;
}
.v-table-cell-content-orange {
background: #FCB724;
color: #FFFFFF;
}
.v-table-cell-content-red {
background: #FF0000;
color: #FFFFFF;
}
Right click on the project folder and choose Run as Run on server choose Tomcat 8 server and hit finish.
Vaadin Programming Cookbook 26 / 134
2.8 Results
Chapter 3
Best practices are procedures that are accepted or prescribed as being correct or most effective.
Java JDK 8
Latest Eclipse Mars
Vaadin 7.6.8
Tomcat Server 8
3.2 Introduction
In this example we are going to illustrate best practices used to make Vaadin applications. We are going to make a Vaadin
example to illustrate these practices.
3.3 Prerequisites
JDK installed
Eclipse Mars installed and working
The design is the blueprint of our program. It is better to invest some time making a good design and when the design is ready,
start coding the application. In our case we have an application that has a menu and three views, each button on the menu changes
the view. We have a welcome view that displays a welcome label. An input view to input some fields, and a view to show all the
data.
Vaadin Programming Cookbook 30 / 134
3.5.2 Annotations
It is recommended to use annotations to define our servlet, because Vaadin uses annotations by default for convenience. Conve-
nience over configuration is a design pattern used to avoid huge configuration files and promotes flexibility.
Annotations
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = VaadinbestpracticesUI. -
class, widgetset = "com.example.vaadinbestpractices.widgetset. -
VaadinbestpracticesWidgetset")
3.5.3 Navigator
Use a navigator to change the views in the application. The navigator was created for this task. We use the navigator in our init
application method.
In our init method, first we create the layout and the content panel to use with the navigator.
Layout & content
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Panel contentPanel = new Panel("Main Panel");
contentPanel.setSizeUndefined();
We create the navigator and attach the views used in our application. In this case we have 3 views: welcome, input and data.
Navigators views
new Navigator(this, contentPanel);
getNavigator().addView(InputPage.NAME, InputPage.class);
getNavigator().addView(WelcomePage.NAME, WelcomePage.class);
getNavigator().addView(DataPage.NAME, DataPage.class);
new Navigator(this, contentPanel); Creates the navigator using the panel as a placeholder. getNavigator().
addView(InputPage.NAME, InputPage.class); Adds the input view to the navigator.
getNavigator().addView(WelcomePage.NAME, WelcomePage.class); Adds the welcome view to the navi-
gator. getNavigator().addView(DataPage.NAME, DataPage.class); Adds the data view to the navigator.
We are going to navigate our application using a menu. Each time we click on a menu button the navigator changes the view. For
each menu button we have a listener to change the view.
Menubar listeners
MenuBar.Command welcome = new Command() {
@Override
public void menuSelected(MenuItem selectedItem) {
getNavigator().navigateTo(WelcomePage.NAME);
}
};
@Override
public void menuSelected(MenuItem selectedItem) {
getNavigator().navigateTo(InputPage.NAME);
}
};
@Override
public void menuSelected(MenuItem selectedItem) {
getNavigator().navigateTo(DataPage.NAME);
}
};
MenuBar.Command welcome =new Command() Creates a new menu command welcome. getNavigator().navi
gateTo(WelcomePage.NAME); Navigates to the welcome page.
MenuBar.Command input =new Command() Creates a new menu command input. getNavigator().navigate
To(InputPage.NAME); Navigates to the input view.
MenuBar.Command data =new Command() Creates a new menu command data. getNavigator().navigateTo
(DataPage.NAME); Navigates to the data view.
3.5.3.4 Menu
We create the menu and attach the buttons to it. When a button is attached to the menu we use the menu command listener
created before.
Main menu
Vaadin Programming Cookbook 32 / 134
MenuBar mainMenu =new MenuBar(); Creates a new menu bar. mainMenu.addItem("Welcome", FontAwes
ome.ARROW_CIRCLE_LEFT, welcome); Add the welcome button to the menu.
mainMenu.addItem("Input", FontAwesome.WEIXIN, input); Add the input button to the menu. mainMenu.
addItem("Data", FontAwesome.LIST, data); Add the data button to the menu.
We redirect the navigator to the page we want to show when the application is started.
Navigator initial page
layout.addComponent(mainMenu);
layout.addComponent(contentPanel);
getNavigator().navigateTo(WelcomePage.NAME);
The welcome page is used as the initial page for the navigator.
Welcome page
public class WelcomePage extends VerticalLayout implements View {
public WelcomePage() {
setMargin(true);
setSpacing(true);
Label welcome = new Label("Welcome");
welcome.addStyleName("h1");
addComponent(welcome);
}
public class WelcomePage extends VerticalLayout implements View The welcome page used by the
navigator must implements the view interface. public static final String NAME ="welcomepage"; The id of
the welcome page to use with the navigator.
setMargin(true); Sets the margin of the layout. setSpacing(true); Sets the spacing of the layout.
Label welcome =new Label("Welcome"); Creates a label. welcome.addStyleName("h1"); Adds a prede-
fined style to the label.
addComponent(welcome); Adds the label to the layout.
Vaadin Programming Cookbook 33 / 134
The data entered by a user is prone to errors and mistakes and is sane to have a validation process in the input of the data. We
have a view with three input fields to show the validation process. To validate our input fields we use the Vaadin validator.
Input form
FormLayout inputForm = new FormLayout();
inputForm.setMargin(true);
inputForm.setSpacing(true);
inputPanel.setContent(inputForm);
FormLayout inputForm =new FormLayout(); Creates the input form. inputForm.setMargin(true); Sets
the margin of the input form.
inputForm.setSpacing(true); Sets the spacing of the input form. inputPanel.setContent(inputForm);
Sets the input form as the content of the input panel.
Name Field
TextField name = new TextField("Name");
name.setNullSettingAllowed(true);
name.setNullRepresentation("");
name.addValidator(new StringLengthValidator("Name must have 3-15 characters lenght", 3, 15, -
true));
name.setValidationVisible(true);
inputForm.addComponent(name);
Surname Field
TextField surname = new TextField("Surname");
surname.setNullSettingAllowed(true);
surname.setNullRepresentation("");
surname.addValidator(new StringLengthValidator("Surname must have 3-15 characters lenght", -
3, 15, true));
surname.setValidationVisible(true);
inputForm.addComponent(surname);
TextField surname =new TextField("Surname"); Creates a text field to the surname. surname.setNullSe
ttingAllowed(true); Alows null in the text field.
surname.setNullRepresentation(""); Sets the null representation to a empty string. surname.addValidator(
new StringLengthValidator("Surname must have 3-15 characters lenght", 3, 15, true)); Adds
the validator to the text field. The validator checks that the string entered into the text field has a length greater than 3 and less
than 15. surname.setValidationVisible(true); Sets the validator visible. inputForm.addComponent(sur
name); Add the text field to the form.
Vaadin Programming Cookbook 34 / 134
Age field
TextField age = new TextField("Age");
age.setNullRepresentation("0");
age.addValidator(new IntegerRangeValidator("Age must be between 1 and 110", 1, 110));
inputForm.addComponent(age);
TextField age =new TextField("Age"); Creates a text field for the age. age.setNullRepresentation("
0"); Sets the null representation to the "0" string.
age.addValidator(new IntegerRangeValidator("Age must be between 1 and 110", 1, 110)); Adds
the validator to the field. The value of the input must be an integer between 1 and 110. inputForm.addComponent(age);
Adds the text fiel to the form.
Validation buttons
HorizontalLayout btLayout = new HorizontalLayout();
Button btSave = new Button("Save");
btLayout.addComponent(btSave);
Button btClear = new Button("Clear");
btLayout.addComponent(btClear);
inputForm.addComponent(btLayout);
HorizontalLayout btLayout =new HorizontalLayout(); Creates a horizontal layout for the buttons. Button
btSave =new Button("Save"); Creates a button for save the form data.
btLayout.addComponent(btSave); Adds the button to the layout. Button btClear =new Button("Clea
r"); Creates a new button to clear the fields.
btLayout.addComponent(btClear); Adds the clear button to the layout. inputForm.addComponent(btLayo
ut); Adds the button layout to the form.
@Override
public void buttonClick(ClickEvent event) {
if(!name.isEmpty() && !surname.isEmpty() && !age.isEmpty()){
}else{
Notification.show("All fields must be filled");
}
}
}
}catch(InvalidValueException e){
Vaadin Programming Cookbook 35 / 134
save = false;
}
try{
surname.validate();
}catch(InvalidValueException e){
save = false;
}
try{
age.validate();
}catch(InvalidValueException e){
save = false;
}
Tries to validate the fields. A boolean is used to keep the status of the validation process. If any validation fails we set save to
false.
Save click listener
if(save){
VaadinbestpracticesUI.dataBean.addBean(
new DataBean(name.getValue(), surname.getValue(), Integer.valueOf( -
age.getValue())));
Notification.show("Data saved!");
name.setValue("");
surname.setValue("");
age.setValue("0");
btSave.setComponentError(null);
}
btClear.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
name.clear();
surname.clear();
age.clear();
}
});
name.clear(); Clears the name. surname.clear(); Clears the surname. age.clear(); Clears the age.
The container allow us to bind our input fields to a data type and help in the validation process.
Vaadin Programming Cookbook 36 / 134
Separation of the data from the UI allow us to change the UI or the data store without affecting each other.
In the image the UI, the datasets and the database are in different layers. If you change any of these three pieces you only have
to define the same interfaces to communicate each other. The change of one layer doesnt have to affect any other layer. If you
want to change the database from MySQL to PostgreSQL for example, this change is transparent to the UI code.
Data
Vaadin Programming Cookbook 37 / 134
This is a standard java class that extends serializable. This class has three fields to store the name, the surname and the age with
its getters and setters.
Data View
public static final String NAME = "datapage";
public DataPage() {
Table dataTable = new Table("Data Table", VaadinbestpracticesUI.dataBean);
dataTable.setVisibleColumns(new Object[]{"name", "surname", "age"});
dataTable.setHeight("200px");
addComponent(dataTable);
}
public static final String NAME ="datapage"; Creates the id of the data view. Table dataTable =new
Table("Data Table", VaadinbestpracticesUI.dataBean); Creates a table to show all the records we have
loaded. The table is using the container as a data source. dataTable.setVisibleColumns(new Object[]{"name",
"surname", "age"}); Sets the visible columns. dataTable.setHeight("200px"); Sets the height of the table.
addComponent(dataTable); Adds the table to the layout.
Vaadin Programming Cookbook 38 / 134
If our application is going to be on a public domain is better to deploy it using http secure protocol. Https encrypts our connection
protecting us for some kind of attacks that could compromise our data.
3.6.1 VaadinbestpracticesUI.java
VaadinbestpracticesUI.java
package com.example.vaadinbestpractices;
import javax.servlet.annotation.WebServlet;
import com.example.vaadinbestpractices.data.DataBean;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@SuppressWarnings("serial")
@Theme("vaadinbestpractices")
public class VaadinbestpracticesUI extends UI {
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Panel contentPanel = new Panel("Main Panel");
contentPanel.setSizeUndefined();
dataBean = new BeanContainer(DataBean.class);
dataBean.setBeanIdProperty("name");
@Override
public void menuSelected(MenuItem selectedItem) {
getNavigator().navigateTo(WelcomePage.NAME);
}
};
@Override
public void menuSelected(MenuItem selectedItem) {
getNavigator().navigateTo(InputPage.NAME);
}
};
@Override
public void menuSelected(MenuItem selectedItem) {
getNavigator().navigateTo(DataPage.NAME);
}
};
layout.addComponent(mainMenu);
layout.addComponent(contentPanel);
getNavigator().navigateTo(WelcomePage.NAME);
}
3.6.2 WelcomePage.java
WelcomePage.java
package com.example.vaadinbestpractices;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
public WelcomePage() {
setMargin(true);
setSpacing(true);
Label welcome = new Label("Welcome");
welcome.addStyleName("h1");
addComponent(welcome);
}
Vaadin Programming Cookbook 40 / 134
@Override
public void enter(ViewChangeEvent event) {
3.6.3 InputPage.java
InputPage.java
package com.example.vaadinbestpractices;
import com.example.vaadinbestpractices.data.DataBean;
import com.google.appengine.api.memcache.InvalidValueException;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.data.util.ObjectProperty;
import com.vaadin.data.util.PropertysetItem;
import com.vaadin.data.validator.IntegerRangeValidator;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
@SuppressWarnings("serial")
public class InputPage extends VerticalLayout implements View {
public InputPage() {
Panel inputPanel = new Panel("Input data");
inputPanel.setSizeUndefined();
addComponent(inputPanel);
btSave.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
if(!name.isEmpty() && !surname.isEmpty() && !age.isEmpty()) -
{
Boolean save = true;
try{
name.validate();
}catch(InvalidValueException e){
save = false;
}
try{
surname.validate();
}catch(InvalidValueException e){
save = false;
}
try{
age.validate();
}catch(InvalidValueException e){
save = false;
}
if(save){
VaadinbestpracticesUI.dataBean.addBean(
new DataBean(name.getValue -
(), surname.getValue(), -
Integer.valueOf(age. -
getValue())));
Notification.show("Data saved!");
name.setValue("");
surname.setValue("");
age.setValue("0");
btSave.setComponentError(null);
}
}else{
Notification.show("All fields must be filled");
}
}
Vaadin Programming Cookbook 42 / 134
});
btClear.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
name.clear();
surname.clear();
age.clear();
}
});
inputForm.setMargin(true);
inputForm.setSpacing(true);
inputPanel.setContent(inputForm);
}
@Override
public void enter(ViewChangeEvent event) {
3.6.4 DataPage.java
DataPage.java
package com.example.vaadinbestpractices;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
public DataPage() {
Table dataTable = new Table("Data Table", VaadinbestpracticesUI.dataBean);
dataTable.setVisibleColumns(new Object[]{"name", "surname", "age"});
dataTable.setHeight("200px");
addComponent(dataTable);
}
@Override
public void enter(ViewChangeEvent event) {
}
Vaadin Programming Cookbook 43 / 134
3.6.5 DataBean.java
DataBean.java
package com.example.vaadinbestpractices.data;
import java.io.Serializable;
Right click on the project folder and choose Run as Run on server choose Tomcat 8 server and click finish.
3.8 Results
This is the start page. Every time you open the application page, this page is shown.
Vaadin Programming Cookbook 44 / 134
In this page we can add records to our example. Here we validate the fields and then store the data into a container.
Vaadin Programming Cookbook 45 / 134
In this view, we retrieve all the records from the container and shown them into a table.
Vaadin Programming Cookbook 46 / 134
Chapter 4
Modern rapid application development environments usually have a visual tool to make the UI. The visual tool allows to put the
widgets on the application without use code.
Java JDK 8
4.2 Introduction
In this example we are going to bind widgets in Vaadin using some common techniques. We are going to use some text boxes
to bind labels using the same data. This can be used to bind any widget with either, widgets or a back end with data as a data
source.
4.3 Prerequisites
JDK installed
We are going to use the trial version of Vaadin Visual Designer. Go to the page Vaadin Designer. Click on Start your free trial.
Vaadin Programming Cookbook 48 / 134
Log in into your Vaadin account and now you can see the follow screen.
Vaadin Programming Cookbook 49 / 134
In this pop-up you can see your Vaadin license code and the installation instructions to get the Visual designer working. Start
eclipse and follow the instructions to install the visual designer.
Click next until the last screen and deselect the option "Create project template" and press finish.
Vaadin Programming Cookbook 52 / 134
Fill the name and the package of the design. Also choose the main layout and hit finish.
Vaadin Programming Cookbook 55 / 134
Now Vaadin is gonna ask for the license code of the designer, write the code and click apply.
Vaadin Programming Cookbook 56 / 134
Now eclipse changes the perspective to show the Vaadin visual designer. On the center of the screen you can see your design and
on the right side you can see 3 panels. The first panel has the widget pallette, the second panel has the outline of the design and
the third panel has the properties of the current selected widget.
Vaadin Programming Cookbook 57 / 134
From the widget palette, drag a button into the design view.
Vaadin Programming Cookbook 58 / 134
Click on the button and you can see the controls to expand and position the widget on a predefined place of the screen. Center
the button in the top center position of the screen, using the controls.
Open the code created by the designer using the button in the toolbar.
Design code
<!doctype html>
<html>
<head>
<meta charset="UTF-8" name="design-properties" content="{"RULERS_VISIBLE":true," -
GUIDELINES_VISIBLE":false,"SNAP_TO_OBJECTS":true,"SNAP_TO_GRID":true," -
SNAPPING_DISTANCE":10,"JAVA_SOURCES_ROOT":"src","THEME":"vaadindesigner"}">
</head>
<body>
<vaadin-vertical-layout size-full>
<vaadin-button plain-text _id="button" :center>
Button
</vaadin-button>
</vaadin-vertical-layout>
</body>
</html>
The code is a normal HTML5 document with special Vaadin tags for the layouts and the widgets. vaadin-vertical-
layout size-full is the main vertical layout used when we created the design. vaadin-button plain-text _id=
"button" :center is our button.
The designer also created a class for every view created by the designer. Open the class MyDesign.java.
MyDesign.java
package com.example.vaadindesigner;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.annotations.DesignRoot;
import com.vaadin.ui.Button;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.declarative.Design;
/**
* !! DO NOT EDIT THIS FILE !!
*
* This class is generated by Vaadin Designer and will be overwritten.
*
* Please make a subclass with logic and additional interfaces as needed,
* e.g class LoginView extends LoginDesign implements View { }
*/
@DesignRoot
@AutoGenerated
@SuppressWarnings("serial")
public class MyDesign extends VerticalLayout {
protected Button button;
public MyDesign() {
Design.read(this);
}
}
As you can see this class is only for Vaadin internal use. When you want to add code to the design you must create a subclass.
Design.read(this); reads the declarative design for the given root component.
Create a subclass of my design to use it.
MyDesign subclass
public class MyView extends MyDesign {
public MyView() {
button.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
Notification.show("Button");
}
});
}
public class MyView extends MyDesign extends the design. button.addClickListener(new ClickLi
stener() using the name of the button, adds a listener. Notification.show("Button"); when the button is clicked a
notification is shown.
Create the main class of our example.
Main Class
public class VaadindesignerUI extends UI {
@Override
protected void init(VaadinRequest request) {
MyView myview = new MyView();
setContent(myview);
}
In the init method of the main class: MyView myview =new MyView(); instantiates the view, that is a subclass of the
design. setContent(myview); sets the root of the project to the view.
VaadindesignerUI.java
package com.example.vaadindesigner;
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("vaadindesigner")
public class VaadindesignerUI extends UI {
Vaadin Programming Cookbook 62 / 134
@Override
protected void init(VaadinRequest request) {
MyView myview = new MyView();
setContent(myview);
}
MyDesign.java
package com.example.vaadindesigner;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.annotations.DesignRoot;
import com.vaadin.ui.Button;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.declarative.Design;
/**
* !! DO NOT EDIT THIS FILE !!
*
* This class is generated by Vaadin Designer and will be overwritten.
*
* Please make a subclass with logic and additional interfaces as needed,
* e.g class LoginView extends LoginDesign implements View { }
*/
@DesignRoot
@AutoGenerated
@SuppressWarnings("serial")
public class MyDesign extends VerticalLayout {
protected Button button;
public MyDesign() {
Design.read(this);
}
}
MyView.java
package com.example.vaadindesigner;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Notification;
public MyView() {
//Button myB = (Button) this.getComponent(0);
button.addClickListener(new ClickListener() {
@Override
Vaadin Programming Cookbook 63 / 134
}
});
}
MyDesign.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8" name="design-properties" content="{"RULERS_VISIBLE":true," -
GUIDELINES_VISIBLE":false,"SNAP_TO_OBJECTS":true,"SNAP_TO_GRID":true," -
SNAPPING_DISTANCE":10,"JAVA_SOURCES_ROOT":"src","THEME":"vaadindesigner"}">
</head>
<body>
<vaadin-vertical-layout size-full>
<vaadin-button plain-text _id="button" :center>
Button
</vaadin-button>
</vaadin-vertical-layout>
</body>
</html>
Right click on the project folder and choose Run as Run on server choose Tomcat 8 server and hit finish.
Vaadin Programming Cookbook 64 / 134
4.8 Results
As you can see, you have on the screen a button centered and when youn click on it you get a Vaadin notification.
Chapter 5
Data binding is a technique that binds the provider of the data with the consumer. Whenever the data change in the provider or
the consumer, the changes are reflected in the other side.
Java JDK 8
5.2 Introduction
In this example we are going to bind widgets in Vaadin using some common techniques. We are going to use some text boxes
to bind labels using the same data. This can be used to bind any widget with either, widgets or a back end with data as a data
source.
5.3 Prerequisites
JDK installed
Layouts
final VerticalLayout layout = new VerticalLayout();
layout.setSizeFull();
layout.setSpacing(true);
HorizontalLayout firstRowlayout = new HorizontalLayout();
firstRowlayout.setSizeFull();
Vaadin Programming Cookbook 68 / 134
firstRowlayout.setSpacing(true);
HorizontalLayout secondRowlayout = new HorizontalLayout();
secondRowlayout.setSizeFull();
secondRowlayout.setSpacing(true);
VerticalLayout stringLayout = new VerticalLayout();
VerticalLayout integerLayout = new VerticalLayout();
VerticalLayout doubleLayout = new VerticalLayout();
VerticalLayout beanLayout = new VerticalLayout();
VerticalLayout itemLayout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
final VerticalLayout layout =new VerticalLayout();, creates the main vertical layout. layout.setSi
zeFull(); sets the size of the main layout to occupy all the client screen. layout.setSpacing(true); for clarity we
set spaces between the rows of the layout.
HorizontalLayout firstRowlayout =new HorizontalLayout(); a first row of the vertical layout is horizontal
layout. firstRowlayout.setSizeFull(); sets the first row size to fill the screen. firstRowlayout.setSpacing
(true); for better visualization of the example sets space between widgets.
HorizontalLayout secondRowlayout =new HorizontalLayout(); second row of widgets. secondRowlay
out.setSizeFull(); second row layout size to full. secondRowlayout.setSpacing(true); second row space
between widgets.
VerticalLayout stringLayout =new VerticalLayout(); a layout for the string binding. VerticalLayout
integerLayout =new VerticalLayout(); a layout for the integer binding. VerticalLayout doubleLayout
=new VerticalLayout(); a layout for the double data type binding.
VerticalLayout beanLayout =new VerticalLayout(); a layout for the bean binding. VerticalLayout it
emLayout =new VerticalLayout(); a layout for the item binding. layout.setMargin(true); sets the margin
of the main layout.
setContent(layout); sets layout as main layout
Object property
ObjectProperty propertyString = new ObjectProperty("string", String.class);
ObjectProperty propertyInteger = new ObjectProperty(0, Integer.class);
ObjectProperty propertyDouble = new ObjectProperty(0.0, Double.class);
Create some object properties to make the binding of the data types.
ObjectProperty propertyString =new ObjectProperty("string", String.class); creates object prop-
erty of type string. ObjectProperty propertyInteger =new ObjectProperty(0, Integer.class); cre-
ates object property of type integer. ObjectProperty propertyDouble =new ObjectProperty(0.0, Double.
class); creates object property of type double.
The ObjectProperty class creates a property data source using a data type, this binding allows to validate at the runtime the
data binded to this property.
Custom CSS style
.v-label-mylabelstyle {
color: white;
text-align: center;
background-color: black;
border-color: white;
font-weight: bold;
}
background-color:black; sets the background color of the label to black. border-color:white; sets the border
color of the label to white. font-weight:bold; sets the font to bold.
String TextField
TextField textFieldString = new TextField("String Text Field");
textFieldString.setWidth("200px");
textFieldString.setPropertyDataSource(propertyString);
textFieldString.setImmediate(true);
This text field is binded to the propertyString, all content of this text field is going to be a string.
TextField textFieldString =new TextField("String Text Field"); creates the text field. textFiel
dString.setWidth("200px"); sets width of the text field to 200 pixels.
textFieldString.setPropertyDataSource(propertyString); binds the text field to the property string. tex
tFieldString.setImmediate(true); sets all the changes at the runtime sended immediate to the server.
String label
Label labelString = new Label();
labelString.setWidth("200px");
labelString.addStyleName("mylabelstyle");
labelString.setPropertyDataSource(propertyString);
This label is binded to the property string and is gonna change every time the string text field changes.
Label labelString =new Label(); creates the label. labelString.setWidth("200px"); sets the label width
to 200 pixels.
labelString.addStyleName("mylabelstyle"); adds a custom style to the label. labelString.setPropert
yDataSource(propertyString); binds the label to the property string using the property as a data source.
Integer TextField
TextField textFieldInteger = new TextField("Integer Text Field");
textFieldInteger.setWidth("200px");
textFieldInteger.setPropertyDataSource(propertyInteger);
textFieldInteger.setImmediate(true);
This class is a pojo java object that works as a data source for a bean field group.
private String bindBeanString; sets the string property. public BindBean(String bindBeanString)
sets the constructor.
public String getBindBeanString() sets the getter. public void setBindBeanString(String bindB
eanString) sets the setter.
BindFieldGroup
BindBean bindBean = new BindBean("string-Bind-Bean");
BeanFieldGroup beanItem = new BeanFieldGroup(BindBean.class);
beanItem.setItemDataSource(bindBean);
TextField textFieldBean = (TextField) beanItem.buildAndBind("BindBeanString", " -
bindBeanString");
textFieldBean.setWidth("200px");
Vaadin Programming Cookbook 71 / 134
We create a bind field group that is binded to a pojo class and set it as a text field data source.
BindBean bindBean =new BindBean("string-Bind-Bean"); creates a new instance to the BindBean class. Bea
nFieldGroup beanItem =new BeanFieldGroup(BindBean.class); creates a BeanFieldGroup using the Bind-
Bean class as skeleton.
beanItem.setItemDataSource(bindBean); sets the data source of the beanItem BeanFieldGroup using the insteance
created before. TextField textFieldBean =(TextField) beanItem.buildAndBind("BindBeanString"
, "bindBeanString"); creates a text field with the beanItem, this is possible because the BeanFieldGroup only have one
field.
textFieldBean.setWidth("200px"); sets the width of the text field.
labelBean
Label labelBean = new Label(textFieldBean);
labelBean.setWidth("200px");
labelBean.addStyleName("mylabelstyle");
labelBean.setPropertyDataSource(textFieldBean);
This label is binded to the bean text field so every time the text field changes this label is gonna change too.
Label labelBean =new Label(textFieldBean); creates the label. labelBean.setWidth("200px"); sets
the width to the label.
labelBean.addStyleName("mylabelstyle"); adds a custom style to the label. labelBean.setPropertyDat
aSource(textFieldBean); sets the data source of the label.
java
PropertysetItem item = new PropertysetItem();
item.addItemProperty("ItemProperty", new ObjectProperty("item-property"));
TextField textFieldItemProperty = new TextField("Item Property TextField");
textFieldItemProperty.setWidth("200px");
FieldGroup fieldGrouop = new FieldGroup(item);
fieldGrouop.bind(textFieldItemProperty, "ItemProperty");
stringLayout.addComponent(textFieldString);
stringLayout.addComponent(labelString);
integerLayout.addComponent(textFieldInteger);
integerLayout.addComponent(labelInteger);
doubleLayout.addComponent(textFieldDouble);
doubleLayout.addComponent(labelDouble);
beanLayout.addComponent(textFieldBean);
beanLayout.addComponent(labelBean);
itemLayout.addComponent(textFieldItemProperty);
itemLayout.addComponent(labelItem);
firstRowlayout.addComponent(stringLayout);
firstRowlayout.addComponent(integerLayout);
firstRowlayout.addComponent(doubleLayout);
secondRowlayout.addComponent(beanLayout);
secondRowlayout.addComponent(itemLayout);
layout.addComponent(firstRowlayout);
layout.addComponent(secondRowlayout);
VaadindatabindingUI.java
package com.example.vaadindatabinding;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.fieldgroup.BeanFieldGroup;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.data.util.ObjectProperty;
import com.vaadin.data.util.PropertysetItem;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@SuppressWarnings("serial")
@Theme("vaadindatabinding")
public class VaadindatabindingUI extends UI {
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
Vaadin Programming Cookbook 73 / 134
layout.setSizeFull();
layout.setSpacing(true);
HorizontalLayout firstRowlayout = new HorizontalLayout();
firstRowlayout.setSizeFull();
firstRowlayout.setSpacing(true);
HorizontalLayout secondRowlayout = new HorizontalLayout();
secondRowlayout.setSizeFull();
secondRowlayout.setSpacing(true);
VerticalLayout stringLayout = new VerticalLayout();
VerticalLayout integerLayout = new VerticalLayout();
VerticalLayout doubleLayout = new VerticalLayout();
VerticalLayout beanLayout = new VerticalLayout();
VerticalLayout itemLayout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
stringLayout.addComponent(textFieldString);
stringLayout.addComponent(labelString);
integerLayout.addComponent(textFieldInteger);
integerLayout.addComponent(labelInteger);
doubleLayout.addComponent(textFieldDouble);
doubleLayout.addComponent(labelDouble);
beanLayout.addComponent(textFieldBean);
beanLayout.addComponent(labelBean);
itemLayout.addComponent(textFieldItemProperty);
itemLayout.addComponent(labelItem);
firstRowlayout.addComponent(stringLayout);
firstRowlayout.addComponent(integerLayout);
firstRowlayout.addComponent(doubleLayout);
secondRowlayout.addComponent(beanLayout);
secondRowlayout.addComponent(itemLayout);
layout.addComponent(firstRowlayout);
layout.addComponent(secondRowlayout);
BindBean.java
package com.example.vaadindatabinding;
vaadindatabinding.scss
Vaadin Programming Cookbook 75 / 134
@import "../valo/valo.scss";
@mixin vaadindatabinding {
@include valo;
.v-label-mylabelstyle {
color: white;
text-align: center;
background-color: black;
border-color: white;
font-weight: bold;
}
Right click on the project folder and choose Run as Run on server choose Tomcat 8 server and hit finish.
5.8 Results
Chapter 6
REST stands for Representational State Transfer. Created by Roy Fielding in the year 2000, is a communication protocol where
everything is a resource. REST principal characteristics are: client-server, stateless, cache-able, layered and uniform interface
to access resources. Resources are accessed using a stateless protocol like HTTP. REST allows text, XML, JSON and other
resources. PUT, GET, POST and DELETE methods are implemented in the REST architecture. Java defines REST using the
JAX-RS Specification (JSR) 311. JAX-RS is implemented using Jersey.
6.1 Introduction
In this example we are going to create a server using Jersey with text, XML and JSON resources and access these resources from
Vaadin, to show it on the user interface. First we are going to create the server and run it. Next we are going to create the Vaadin
client and consume the resources on the server.
6.2 Prerequisites
JDK installed
Eclipse Mars installed and working
Vaadin 7.6.5 plug-in installed
Tomcat 8 installed and running
Download latest Jersey library from Download Jersey, uncompress the zip file and save it for later.
Vaadin Programming Cookbook 79 / 134
Fire up eclipse and choose from the menu File->New->Other. From the list choose Dynamic Web Project.
Vaadin Programming Cookbook 80 / 134
Copy all the Jersey jar files from the downloaded zip into the folder WebContent->WEB-INF->lib.
Vaadin Programming Cookbook 81 / 134
This class use the annotation @Path of the specification JAX-RS. Its a plain old java object because inherits no one. The
JAX-RS specification of Jersey uses annotations to create the REST services.
Text response
Vaadin Programming Cookbook 82 / 134
@GET
@Produces(MediaType.TEXT_PLAIN)
public String serverMessageText() {
return "This is a message from the server";
}
When you make an html request with a GET with plain text as the type of the data, this content is served. The annotation @GET,
serves an html GET request and the annotation @Produces, specify the type of data of the response according to the request.
The server first analyzes the request and then based on the data type requested it sends the response. Request/Response is the
standard html communication protocol. REST uses the standard request/response communication protocol.
XML response
@GET
@Produces(MediaType.TEXT_XML)
public String serverMessageXML() {
return " This is a message from the server ";
}
When you make an html request with a GET with XML as the type of the data, this content is served.
JSON response
@GET
@Produces(MediaType.APPLICATION_JSON)
public String serverMessageJSON() {
return "[{message : server json message, content : message content}]";
}
When you make an html request with a GET with JSON as the type of the data, this content is served.
In the server we are going to use the web.xml configuration to expose our REST services and define our paths.
servlet
<servlet>
<servlet-name>Rest Server</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.example</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
This defines the servlet and map the appropriate jersey class to our package. To make the Jersey library recognizes where are the
content to be served.
Servlet mapping
<servlet-mapping>
<servlet-name>Rest Server</servlet-name>
<url-pattern>/server/*</url-pattern>
</servlet-mapping>
The servlet mapping, maps the content of our class to the URI used in the browser.
Vaadin Programming Cookbook 83 / 134
We are going to create a supplementary client class to create the server REST services. Create a POJO class:
Vaadin Programming Cookbook 85 / 134
POJO client
public class RestClient {
In this class we are going to create all the client methods we need to access the data on the server.
fields
ClientConfig config;
Client client;
WebTarget webtarget;
In the constructor of the Jersey client, we have our base URI to access the REST services.
getResponse
public String getResponse(){
String response = webtarget.path("server").
path("restserver").
request().
accept(MediaType.TEXT_PLAIN).
get(Response.class).toString();
return response;
}
This is a method to get the response from the server. The response could tell us the state of the server and the availability of the
services.
Get text answer
public String getAnswerText(){
String answer =
webtarget.path("server").
path("restserver").
request().
accept(MediaType.TEXT_PLAIN).
get(String.class);
return answer;
}
This is a method to get a plain text answer. In the field accept, we specify the type of the response. With REST, the data
between the client and the server is just plain text but here we could know the kind of structure these plain text has. In this
example it could be just plain text, XML or JSON.
Get XML answer
public String getAnswerXML(){
String answer =
webtarget.path("server").
path("restserver").
request().
accept(MediaType.TEXT_XML).
Vaadin Programming Cookbook 86 / 134
get(String.class);
return answer;
}
This method gets an XML answer from the server, note the fields path, these fields are append to the base URI created in the
constructor of the class.
Get JSON
public String getAnswerJSON(){
String answer =
webtarget.path("server").
path("restserver").
request().
accept(MediaType.APPLICATION_JSON).
get(String.class);
return answer;
}
6.7.2 Vaadin UI
In the init class of our Vaadin application we create an instance of the client class to access the REST services from our web
application. Remember the REST server could be anywhere in the Internet. It could be on the same server as the client but we
can have multiples REST servers all around the world and a client accessing all of them.
Main layout
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
We create an instance of our REST client, to use it from the Vaadin user interface.
Feedback label
Label resultLabel = new Label();
resultLabel.setWidth("100%");
resultLabel.setHeight("200px");
resultLabel.addStyleName("h1");
resultLabel.addStyleName("mylabelstyle");
We create a label to put the feedback from our server, and make some adjustments and styles to the label just for this example
purpose.
Layout for buttons
HorizontalLayout hLayot = new HorizontalLayout();
We are going to create some buttons to get different answers from the server, and we organize it on an horizontal layout.
Get Response
Vaadin Programming Cookbook 87 / 134
This is a button to get the server response. With this response we can check the status of the server.
Text Answer
Button buttonGetText = new Button("Get Text Answer");
buttonGetText.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
resultLabel.setValue(restClient.getAnswerText());
}
});
This is a button to get the text answer from the REST server.
XML Answer
Button buttonGetXml = new Button("Get XML Answer");
buttonGetXml.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
resultLabel.setValue(restClient.getAnswerXML());
}
});
With this button we get an XML response from the server. We are using the client class created before to call these methods.
JSON Answer
Button buttonGetJson = new Button("Get JSON Answer");
buttonGetJson.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
resultLabel.setValue(restClient.getAnswerJSON());
}
});
A JSON answer from the server, JSON has been very popular lately and you could transfer it with REST.
Add elements to the layout
hLayot.addComponent(buttonGetResponse);
hLayot.addComponent(buttonGetText);
hLayot.addComponent(buttonGetXml);
hLayot.addComponent(buttonGetJson);
layout.addComponent(resultLabel);
layout.addComponent(hLayot);
RestServer.java
Vaadin Programming Cookbook 88 / 134
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/restserver")
public class RestServer {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String serverMessageText() {
return "This is a message from the server";
}
@GET
@Produces(MediaType.TEXT_XML)
public String serverMessageXML() {
return " This is a message from the server ";
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public String serverMessageJSON() {
return "[{message : server json message, content : message content -
}]";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp. -
org/xml/ns/javaee" xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns -
.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>JaxRestHello</display-name>
<servlet>
<servlet-name>Rest Server</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.example</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Rest Server</servlet-name>
<url-pattern>/server/*</url-pattern>
</servlet-mapping>
</web-app>
RestClient.java
package com.example.vaadin_rest_example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
Vaadin Programming Cookbook 89 / 134
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
public RestClient(){
config = new ClientConfig();
client = ClientBuilder.newClient(config);
webtarget = client.target("https://localhost:8080/JaxRestHello");
}
Vaadin_rest_exampleUI.java
package com.example.vaadin_rest_example;
import javax.servlet.annotation.WebServlet;
Vaadin Programming Cookbook 90 / 134
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
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.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@SuppressWarnings("serial")
@Theme("vaadin_rest_example")
public class Vaadin_rest_exampleUI extends UI {
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
resultLabel.setValue(restClient.getAnswerJSON());
}
});
hLayot.addComponent(buttonGetResponse);
hLayot.addComponent(buttonGetText);
hLayot.addComponent(buttonGetXml);
hLayot.addComponent(buttonGetJson);
layout.addComponent(resultLabel);
layout.addComponent(hLayot);
}
vaadin_rest_example.scss
@import "../valo/valo.scss";
@mixin vaadin_rest_example {
@include valo;
.v-label-mylabelstyle {
color: white;
text-align: center;
background-color: black;
border-color: white;
font-weight: bold;
}
}
First right click on the server project folder and choose Run as Run on server choose Tomcat 8 server and press finish. When
the server is running right click on the Vaadin project folder and choose Run as Run on server choose Tomcat 8 server and
press finish.
Vaadin Programming Cookbook 92 / 134
6.10 Results
Chapter 7
The relational model is the organization of data into collections of two-dimensional tables called relations, the relational data
model was developed for databases but you can use this model to group sets of items and define relations between these sets, a
container of sets of items and its relations.
Java JDK 8
Latest Eclipse Mars
Vaadin 7.6.4
Tomcat Server 8
7.2 Introduction
Vaadin Container is a set of Items, that have a relational model, you can use it to easily wrap a database and associate it with the
Vaadin controls that implements the Container interface. Its use is not restricted to a database, you can use it to model your
own sets of items and its relations inside your application, and get advantage of the strong structure that the Vaadin container
provides. A container must follow certain rules to use it:
7.3 Prerequisites
JDK installed
Eclipse Mars installed and working
Vaadin 7.6.4 plugin installed
Tomcat 8 installed and running
Vaadin Programming Cookbook 97 / 134
The BeanContainer is a container for JavaBean objects. It is a simple Java class that implements Serializable and has all the fields
that we want in our container.
MyBean.java
Vaadin Programming Cookbook 99 / 134
package com.example.vaadincontainer;
import java.io.Serializable;
this.name = pname;
this.surname = psurname;
this.osUsed = pSubBean;
MyBean has two string fields called name and surname and another bean which is called MySubBean with a parent-child
relationship. This is a simple pojo Java class with the field declarations, a single constructor public MyBean (String
pname, String psurname, MySubBean pSubBean) and standard getters and setters for each property field. Also
we have here MySuBean fields that are the fields that define the nested relationship, having as a member another bean.
MySubBean.java
package com.example.vaadincontainer;
import java.io.Serializable;
Vaadin Programming Cookbook 100 / 134
This is the child bean and has only one string field, to the purpose of this tutorial a nested bean is working. As before this is a
simple pojo Java class that has the field declarations, a constructor, getters and setters.
7.5.3 The UI
Random OS
private MySubBean randomOS()
{
Random osr = new Random();
int osn = osr.nextInt(5);
String oss = "";
switch (osn) {
case 0:
oss = "Linux";
break;
case 1:
oss = "OSX";
break;
case 2:
oss = "Android";
break;
case 3:
oss = "Unix";
break;
case 4:
oss = "Windows 10";
break;
default:
oss = "Linux";
break;
}
I created a function that generates random OS names. This function is going to be used to create our beans and to generate
random names. First I create a random generator with Random osr =new Random(); then i generate a random integer
between 0 and 4 with int osn =osr.nextInt(5); and choose an OS name with a switch statement.
The layout
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
First BeanContainer
BeanContainer beans = new BeanContainer(MyBean.class);
beans.addNestedContainerProperty("osUsed.os");
beans.setBeanIdProperty("name");
beans.addBean(new MyBean("John", "Doe", randomOS()));
beans.addBean(new MyBean("Matt", "Foe", randomOS()));
First I create a BeanContainer using MyBean.class as the blue print. BeanContainer is an in-memory container for
JavaBeans and the properties of the container are determined automatically by introspecting the used JavaBean class. beans.
addNestedContainerProperty("osUsed.os"); declares the nested properties of the container. beans.setBean
IdProperty("name"); tells the container what is the ID of the container and with beans.addBean we add two sample
items to the container with the name, surname and a using the random os generator name.
Second BeanContainer
BeanContainer filteredBeans = new BeanContainer(MyBean.class);
filteredBeans.addNestedContainerProperty("osUsed.os");
filteredBeans.setBeanIdProperty("name");
filteredBeans.addBean(new MyBean("John", "Doe", randomOS()));
filteredBeans.addBean(new MyBean("Matt", "Foe", randomOS()));
Filter filter = new SimpleStringFilter("surname", "Doe", true, false);
filteredBeans.addContainerFilter(filter);
This beam container is the same as the first container. I added a filter to show a filtered bean container. Filter filter
=new SimpleStringFilter("surname", "Doe", true, false); adds a string filter that only shows the items
with surname "doe", the case is indifferent in this particular filter. filteredBeans.addContainerFilter(filter);
associates the filter with the container.
Unfiltered Table
table = new Table("Employees", beans);
table.setColumnHeader("osUsed.os", "OS Used");
table.setHeight("200px");
table.setVisibleColumns(new Object[]{"name","surname", "osUsed.os"});
When I create the table "table", the bean container beans is passed as a parameter. With this parameter we tell to the table to
associate the data on the bean as a data source for the table. table.setColumnHeader("osUsed.os", "OS Used");
changes the name of the header that is the name of the variable to a humanized name. table.setVisibleColumns(new
Object[]{"name","surname", "osUsed.os"});, tells the table what columns are visible.
Vaadin Programming Cookbook 102 / 134
Filtered Table
Table famTable = new Table("Surname Doe", filteredBeans);
famTable.setColumnHeader("osUsed.os", "OS Used");
famTable.setHeight("200px");
famTable.setVisibleColumns(new Object[]{"name","surname", "osUsed.os"});
This famTable only shows items with surname "doe", all other items are filtered, thanks to the filter added to the filtered
Beans bean container.
Input
TextField tname = new TextField("Name");
TextField tsurname = new TextField("Surname");
Button badd = new Button("Add");
I created two text fields and a button to add items using the UI.
@Override
public void buttonClick(ClickEvent event) {
}
});
When you click the button, if(!tname.isEmpty() && !tsurname.isEmpty()) checks if the input is empty. If not
empty, we get both values and find if a duplicate exists with String result =findDuplicates(ctName, ctSurna
me);. If a duplicate exists in the name or in the surname a notification is send to the user. In any case the item is added to the
bean, which itself avoids to add items with duplicate ID.
Vaadin Programming Cookbook 103 / 134
findDuplicates
private String findDuplicates(String pName, String pSurname){
if(pName.equals(currName)){
return "name";
}
if(pSurname.equals(currSurname)){
return "surname";
}
}
return "none";
}
To find duplicates we need to iterate over the container, the table.getItemIds() method of Container returns a Collection
of items so you can iterate all the entire collection of items. String iid =(String) i.next(); gets the next item
ID.Item item =table.getItem(iid); gets the item using the ID. String currName =(String) item.get
ItemProperty("name").getValue();, gets the value of the current item "name" property. String currSurname
=(String) item.getItemProperty("surname").getValue(); gets the current surname.
VaadincontainerUI.java
package com.example.vaadincontainer;
import java.util.Iterator;
import java.util.Random;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Container.Filter;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.data.util.filter.SimpleStringFilter;
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.HorizontalLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@SuppressWarnings("serial")
@Theme("vaadincontainer")
Vaadin Programming Cookbook 104 / 134
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
@Override
public void buttonClick(ClickEvent event) {
randomOS()));
}else{
Notification.show("Missing Data ...", Notification. -
Type.WARNING_MESSAGE);
}
}
});
layout.addComponent(hl);
layout.addComponent(badd);
HorizontalLayout hlTab = new HorizontalLayout();
hlTab.addComponent(table);
hlTab.addComponent(famTable);
layout.addComponent(hlTab);
}
if(pName.equals(currName)){
return "name";
}
if(pSurname.equals(currSurname)){
return "surname";
}
}
return "none";
}
switch (osn) {
case 0:
oss = "Linux";
break;
case 1:
oss = "OSX";
break;
case 2:
oss = "Android";
break;
case 3:
oss = "Unix";
break;
case 4:
oss = "Windows 10";
Vaadin Programming Cookbook 106 / 134
break;
default:
oss = "Linux";
break;
}
MyBean.java
package com.example.vaadincontainer;
import java.io.Serializable;
this.name = pname;
this.surname = psurname;
this.osUsed = pSubBean;
MySubBean.java
Vaadin Programming Cookbook 107 / 134
package com.example.vaadincontainer;
import java.io.Serializable;
Right click on the project folder and choose Run as Run on server choose Tomcat 8 server and hit finish.
7.8 Results
When you first run the example you only get the harcoded sample data:
Vaadin Programming Cookbook 108 / 134
When you try to add a duplicate name, its not added because name is the primary ID and the container ensures unicity of the
primary ID:
Vaadin Programming Cookbook 111 / 134
Chapter 8
Suppose you need a reusable component in you web application, a component widget that you need to add in multiple places
into your application, instead of code the component functionality every time, Vaadin offers in handy the possibility of create a
reusable widget that you can use every time you need it, saving your time and giving you a more elegant solution than code the
whole thing every time.
Java JDK 8
Latest Eclipse Mars
Vaadin 7.6.2
8.2 Introduction
In this example we are going to create a Vaadin widget that you can adapt to your needs. With the Vaadin plugin you have an
automated way to make the widget and add it to your project ready to customize and use. Lets get started!
8.3 Prerequisites
JDK installed
Now you have a fresh Vaadin project ready to run. Lets add the custom component to the project.
Vaadin Programming Cookbook 116 / 134
Right click in the project folder inside eclipse and choose New Other:
In the following pop-up window, choose from the list Vaadin Widget and hit next.
Vaadin Programming Cookbook 117 / 134
Take a look at your project tree and note that Vaadin have created a bunch of files for you saving you to type a lot of boilerplate
code, also note that Vaadin organize your project in packages with your main application in one package com.example.
vaadinwidget and the custom component in other package com.example.vaadinwidget.client.mycomponent,
abstracting the inner details of the widget.
Vaadin Programming Cookbook 119 / 134
All the code of the widget are in the project for you to customize if your widget is complex enough or if you need to.
Vaadin have created a client side text widget when you click on it, it changes the text of the widget and if you click 5 times, make
the application fire an alert with a message.
Look at the code of the file that manage the functionality of the component, it extends com.vaadin.ui.AbstractCompon
ent
MyComponent.java
package com.example.vaadinwidget;
import com.example.vaadinwidget.client.mycomponent.MyComponentClientRpc;
import com.example.vaadinwidget.client.mycomponent.MyComponentServerRpc;
import com.vaadin.shared.MouseEventDetails;
import com.example.vaadinwidget.client.mycomponent.MyComponentState;
public MyComponent() {
registerRpc(rpc);
}
@Override
public MyComponentState getState() {
return (MyComponentState) super.getState();
}
}
we have clickCount that counts the mouse clicks and also we have a function clicked that capture the mouse click and
when clickCount is 5 it fire an alert also modifies the widget text with getState().text ="You have clicked "
+ clickCount + " times";
and after a while you widgetset is compiled using the GWT compiler shipped with the Vaadin plugin.
Right click in the project folder and choose Run As Run on server.
Vaadin Programming Cookbook 121 / 134
Chapter 9
Server push is a technology when the server pushes data to the client without the client asking for that data just like the old
intranet client/server architecture when the clients get updated by the server. This kind of communication was near to impossible
in the web few years before, first the bandwidth, when the Internet begins was not enough for server push, several attempts before
the HTML5 websocket like webcasting and comet have not been successfull enough and is with HTML5 that server push become
widely used.
Java JDK 8
Latest Eclipse Mars
Vaadin 7.6.4
Tomcat Server 8
9.2 Introduction
Vaadin make very easy to use server push, you only need to use the @Push annotation and Vaadin is using server push. In
this example I am going to show you how to handle the server push to send content to the client. I am using here Labels as
a containers to the data pushed from the server but you can use any container you want. In the first server push, the server is
pushing the time every second and in the second one the server is pushing every 10 seconds.
9.3 Prerequisites
JDK installed
Eclipse Mars installed and working
@Push annotation
@Push
@SuppressWarnings("serial")
@Theme("vaadinseverpushbeta")
public class VaadinseverpushbetaUI extends UI{
To use server push just add the annotation @Push to the UI class annotations. Adding @Push to a UI class configures the UI for
automatic push.
Class Variables
private QuoteGenerator qg;
private VerticalLayout layout;
private Label theTime;
The private QuoteGenerator qg; is used for the custom POJO Class created before to generate quotes. private
VerticalLayout layout; the layout of our UI class and private Label theTime; to store the datetime pushed
from the server.
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
access(new Runnable() {
@Override
public void run() {
theTime.setValue("Its now : " + Instant.now -
());
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Vaadin Programming Cookbook 128 / 134
This thread update the private Label theTime; every second as long as the webpage is running, the time is coming from
the server using server push. Thread.sleep(1000);, sleep the thread for 1000 milliseconds = 1 second. access(new
Runnable() locks the UI and provide exclusive access to the current runnable, All the UI operations must be inside an access
block because the thread needs a lock to modify the UI, if you try to modify the UI outside an access block an exception is raised.
theTime.setValue("Its now :" + Instant.now()); modify the content of the Label using server push.
Second Thread
class MySecondThread2 extends Thread {
int count = 0;
@Override
public void run() {
try {
while (count < 4) {
Thread.sleep(10000);
access(new Runnable() {
@Override
public void run() {
layout.addComponent(new Label(qg.getQuote() -
));
count++;
}
});
}
access(new Runnable() {
@Override
public void run() {
layout.addComponent(new Label("No more -
messages for you !"));
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
This thread run four times every 10 seconds and every time it runs, adds a label with a random quote from the server using server
push.int count =0; its a counter to limit the number of times this thread runs.
while (count < 4) {, the while checks the counter.
Thread.sleep(10000); the thread sleep for 10 seconds, remember the parameter of the sleep is in miliseconds
access(new Runnable() { using the access block to lock the UI
layout.addComponent(new Label(qg.getQuote())); adds a new Label with a random quote every time it runs
count++; Update the counter. After the thread have added 4 labels it exits from the while and add a last label to show to the
user that it finish
layout.addComponent(new Label("No more messages for you !")); with no more messages.
Init Method
Vaadin Programming Cookbook 129 / 134
@Override
protected void init(VaadinRequest request) {
qg = new QuoteGenerator();
layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
theTime = new Label();
theTime.setValue("Its now : " + Instant.now());
layout.addComponent(theTime);
new MyFirsthThread().start();
new MySecondThread2().start();
}
In the init method first create the random quote generator instance qg =new QuoteGenerator();. Then create the layout
layout =new VerticalLayout();. Create the label to hold the time theTime =new Label();. Start the first
thread new MyFirsthThread().start(); and start the second thread new MySecondThread2().start();.
QuoteGenerator.java
package com.example.vaadinserverpush;
import java.util.Random;
VaadinserverpushUI.java
package com.example.vaadinserverpush;
import java.time.Instant;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Push
@SuppressWarnings("serial")
@Theme("vaadinserverpush")
public class VaadinserverpushUI extends UI {
@Override
protected void init(VaadinRequest request) {
qg = new QuoteGenerator();
layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
theTime = new Label();
theTime.setValue("Its now : " + Instant.now());
layout.addComponent(theTime);
new MyFirsthThread().start();
new MySecondThread2().start();
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
access(new Runnable() {
@Override
public void run() {
theTime.setValue("Its now : " + Instant.now());
}
});
}
Vaadin Programming Cookbook 131 / 134
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
try {
while (count < 4) {
Thread.sleep(10000);
access(new Runnable() {
@Override
public void run() {
layout.addComponent(new Label(qg.getQuote()));
count++;
}
});
}
access(new Runnable() {
@Override
public void run() {
layout.addComponent(new Label("No more messages for you !& -
quot;));
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Right click on the project folder and choose Run as Run on server choose Tomcat 8 server and hit finish.
9.8 Results
Open your application in a browser and fire Up the developer tools CTRL+SHIFT+i shortcut in most browsers, you should see
something like the following image, go to the console tab:
Vaadin Programming Cookbook 132 / 134
Lets run the application and examine the console output to see whats Vaadin doing under the hood.
After running the application for a while you get a lot of messages lets filter these messages to get only the server push messages.
Vaadin Programming Cookbook 133 / 134
Also you get: INFO:Received push (websocket) message: that is telling you that the webapplication is receiving
server push messages.
Now we are sure that Vaadin is using server push to update our page.