brought to you by... #85

CONTENTS INCLUDE:

n About n Vaadin: A Familiar Way to Creating an Application n Components n Layout Components n Themes Build Web Apps with n and more... By Marko Grönroos Visit refcardz.com

The application can change the components and the layout ABOUT VAADIN dynamically according to the user input.

Vaadin is a server-side development framework that allows you to build web applications just as you would with traditional desktop frameworks, such as AWT or . An application is built from user interface components contained hierarchically in layout components.

In the server-driven model, the application code runs on a server, Get More Refcardz! Refcardz! Get More while the actual user interaction is handled by a client-side engine running in the browser. The client-server communications and any client-side technologies, such as HTML and JavaScript, are invisible to the developer. As the client-side engine runs as JavaScript in the browser, there is no need to install plug-ins.

Figure 2: Architecture for Vaadin Applications

You can create a Vaadin application project easily with the Vaadin Plugin for , with NetBeans, with Maven or with Spring Roo. Figure 1: Vaadin Client-Server Architecture Event Listeners If the built-in selection of components is not enough, you can In the event-driven model, user interaction with user interface develop new components with the (GWT) components triggers server-side events, which you can handle in Java. with event listeners.

CREATING AN APPLICATION In the following example, we handle click events for a button with an anonymous class: An application that uses the Vaadin framework needs to inherit the Button button = new Button(“Click Me!”); com.vaadin.Application class and implement the init() method. button.addListener(new ClickListener() { public void buttonClick(ClickEvent event) { getWindow().showNotification(“Thank You!”); import com.vaadin.ui.*; } }); public class HelloWorld extends com.vaadin.Application { public void init() { Window main = new Window(“Hello window”); from setMainWindow(main); $99 main.addComponent(new Label(“Hello World!”)); } per } month To write an application class and the initialization method, Vaadin you should: Pro Account • inherit the Application class • create and set a main window Support from the • populate the window with initial components Vaadin team • define event listeners to implement the UI logic Pro Add-on compo- nents and tools Optionally, you can also: Try one month for free

A Familiar Way to Build Web Apps with Java to Build Web A Familiar Way • set a custom theme for the window with code: DZONE Bug fix guarantee, • bind components to data feature voting and vaadin.com/pro knowledge base • bind components to resources Vaadin:

DZone, Inc. | www.dzone.com 2 Vaadin: A Familiar Way to Build Web Apps with Java

readOnly If true, the user can not change the value. (Default: false) Hot You can embed Vaadin applications to any web page Tip in div or iframe elements. See the Book of Vaadin visible Whether the component is actually visible or not. (Default: true) for more info. Field Properties Field properties are defined in the Field interface and the Below is a list of the most important event interfaces; their AbstractField base class for fields. corresponding listener interface is named -Listener.

Property Description Event Interface Description required Boolean value stating whether a value for the field is required. Property.ValueChangeEvent Field components except Button (Default: false) Button.ClickEvent Button click requiredError Error message to be displayed if the field is required but empty. Window.CloseEvent A sub-window or an application-level window has been closed Sizing The size of components is defined in theSizeable interface. Unless the immediate property (see below) is set, value change events are not communicated immediately to the server-side Method Description when the user changes the values. Instead, they are delayed until setWidth() Set the component size in either fixed units (px, pt, pc, the first immediate interaction. Certain events, such as button setHeight() cm, mm, in, or em) or as a relative percentage (%) of the clicks, are immediate by default. containing layout. The value “-1” means undefined size (see below). Deployment setSizeFull() Sets both dimensions to 100% relative size of the space To deploy an application as a servlet, you must define a given by the containing layout. WEB-INF/web.xml deployment descriptor. The application setSizeUndefined() Sets both dimensions as undefined, causing the class must be defined in the application parameter. component to shrink to fit the content.

Notice that a layout with an undefined size must not contain a myproject component with a relative (percentual) size. Myproject Application com.vaadin.terminal.gwt.server.ApplicationServlet Validation All components implementing the Validatable interface, such Vaadin application class to start application as all fields, can be validated withvalidate() or isValid(). You com.example.myproject.HelloWorld need to implement a Validator and its validate() and isValid() methods and add the validator to the field withaddValidator() . Myproject Application /* Built-in validators are defined in thecom.vaadin.data.validator package and include:

You can also deploy to a portal as a portlet. Validator Description DoubleValidator A floating-point value COMPONENTS EmailValidator An email address IntegerValidator An integer value Vaadin components include field, layout, and other components. RegexpValidator String that matches a regular expression The component classes and their inheritance hierarchy is Length of string is within a range illustrated in Figure 4. StringLengthValidator Component Properties Resources Common component properties are defined in the Component Icons, embedded images, hyperlinks, and downloadable files are interface and the AbstractComponent base class. referenced as resources.

Property Description Button button = new Button(“Button with an icon”); button.setIcon(new ThemeResource(“img/myimage.png”)); caption A label that identifies the component for the user, usually shown above, left of, or inside a component, depending on the The external and theme resources are usually static resources. component and the containing layout. Application resources are served by the Vaadin application description A label that identifies the component for the user, usually servlet, or by the user application itself. shown above, left of, or inside a component, depending on the component and the containing layout. enabled If false, the user can not interact with the component. The component is shown as grayed. (Default: true) icon An icon for the component, usually shown left of the caption. immediate If true, value changes are communicated immediately to the server- side, usually when the selection changes or (a text field) loses input focus. The default is false for most components, but true for Button. Figure 3: Resource classes and interfaces locale The current country and/or language for the component. Meaning and use is application-specific for most components. (Default: application locale) Continued on Page 4...

DZone, Inc. | www.dzone.com 3 Vaadin: A Familiar Way to Build Web Apps with Java

Figure 4: The Class Diagram presents all user interface component classes and the most important interfaces, relationships, and methods.

DZone, Inc. | www.dzone.com 4 Vaadin: A Familiar Way to Build Web Apps with Java

...Continued from Page 2 Custom themes are placed under the WebContent/VAADIN/themes/ folder of the web application. This location is fixed. TheVAADIN Class Name Description folder specifies that these are static resources specific to Vaadin. ExternalResource Any URL The name of the theme folder defines the name of the theme, to ThemeResource A static resource served by the application server from the current theme. The path is relative to the theme folder. be used for the setTheme() method:

FileResource Loaded from the file system public void init() { setTheme(“mytheme”); ClassResource Loaded from the class path … StreamResource Generated dynamically by the application The theme folder must contain the styles. style sheet and custom layouts must be placed in the layouts sub-folder, but LAYOUT COMPONENTS other contents may be named freely.

The layout of an application is built hierarchically with layout Custom themes need to inherit a base theme in the beginning of components or more generally component containers. the styles.css file. The default theme for Vaadin 6 is reindeer.

You start by creating a root layout for the main window and set it @import url(../reindeer/styles.css); with setContent(), unless you use the default, and then add the other layout components hierarchically with addComponent(). Margins The margin of layout components is controlled with the margin property, which you can set with setMargin(). Once enabled, the HTML element of the layout will contain an inner element with -margin style, for example, v-verticallayout- margin for a VerticalLayout. You can use the padding property in CSS in a custom theme to set the width of the margin. Spacing Some layout components allow spacing between the elements. You first need to enable spacing withsetSpacing(true) , which enables the -spacing-on style for the layout, for example, v-gridlayout-spacing-on for GridLayout. You can then set the amount of spacing in CSS in a custom theme with the padding-top property for vertical and padding-left for horizontal spacing.

Alignment Figure 5: Theme contents When a layout cell is larger than a contained component, the component can be aligned within the cell with the Try adding ?debug or ?restartApplication to setComponentAlignment() method. Hot Tip the application URL. Custom Layout The CustomLayout component allows the use of a HTML template that contains location tags for components, such as DATA BINDING

. The components are inserted in the location elements with the addComponent() method as shown below: Vaadin allows binding components directly to data. The data

CustomLayout layout = new CustomLayout(“mylayout”); model, illustrated in Figure 4, is based on interfaces on three layout.addComponent(new Button(“Hello”), “hello”); levels of containment: properties, items, and containers. The layout name in the constructor refers to a corresponding Properties . file in thelayouts subfolder in the theme folder, in the The Property interface provides access to a value of a specific above example layouts/mylayout.html. See Figure 5 for the class with the setValue() and getValue() methods. location of the layout template. All field components provide access to their value through the Creating Composite Components Property interface, and the ability to listen for value changes with You can create composite components by extending layout a Property.ValueChangeListener­ . The field components hold components. The CustomComponent allows component their value in an internal data source by default but you can bind composition while hiding the implementation details. You them to any data source with setPropertyDataSource(). need to extend it and set the composition root, usually a layout For selection components, the property value points to the component, with setCompositionRoot() in the constructor. item identifier of the current selection, or a collection of item THEMES identifiers in themultiSelect mode. Items Vaadin allows customization of appearance of the user interface An item is an ordered collection of properties. The Item interface with themes. Themes can include CSS style sheets, custom layout also associates a name with each property. Common uses of HTML templates, and any graphics. items include Form data and Table rows.

DZone, Inc. | www.dzone.com 5 Vaadin: A Familiar Way to Build Web Apps with Java

The BeanItem is an adapter that allows accessing any Java bean (or Creating a Client-Side Widget POJO with the proper setters and getters) through the Item interface. To create a client-side component, you should: This is useful for binding a Form to a bean. • Implement the Paintable interface Containers • Maintain a reference to the ApplicationConnection object A container is a collection of items. It allows accessing the • Implement updateFromUIDL() to deserialize state changes items with an item identifier associated with each item. from server-side Common uses of containers include selection components, as • Serialize state changes to server-side with calls to defined in theAbstractSelect class, especially the Table and Tree updateVariable() components. (The current selection is indicated by the property of the field, which points to the item identifier of the selected item.) Creating a Server-Side Component To create a server-side component, you should: Vaadin includes the following container implementations: • Use @ClientWidget annotation for the server-side component

Container Class Description class to bind the component to the client-side counterpart IndexedContainer Container with integer index keys • Implement paintContent() to serialize state changes to BeanItemContainer Container for BeanItems client-side with addVariable() and addAttribute() calls HierarchicalContainer Tree-like container, used especially by the Tree • Implement changeVariables() to deserialize state changes component from client-side FilesystemContainer Direct access to the file system Buffering All field components implement theBuffered interface that allows buffering user input before it is written to the data source. Buffering is disabled by default.

Method Description commit() Writes the buffered data to the data source discard() Discards the buffered data and re-reads the data from the data source

set-/getWriteThrough() Set to false to enable write buffering

set-/getReadThrough() Set to false to enable read buffering

USING ADD-ON COMPONENTS

In addition to the core features, you can find additional components, themes, container implementations, and various tools from the Vaadin Directory.

To install an add-on, download the Jar or Zip package from the Directory. If packaged as a Zip, extract the Jar library from it. Copy the Jar to the WEB-INF/lib path in your project.

Most add-on components contain a widget set. The widget sets from different add-ons need to be combined with the core widgets by compiling a project widget set. The widget set must be referenced in the web.xml descriptor. • With Eclipse IDE, click the “Compile Vaadin Widgets” button in the toolbar. This requires the Vaadin Plugin for Eclipse. • With NetBeans IDE and others, copy the build-widgetset. xml script template from the Vaadin installation package, edit it for your project, and run it with Ant.

More detailed instructions are given in the Directory (http://vaadin.com/directory) and Book of Vaadin.

CREATING NEW COMPONENTS

Vaadin components consist of a server-side component and a client-side GWT widget counterpart. Figure 6: Widget integration within the vaadin client-server communication architecture

DZone, Inc. | www.dzone.com 6 Vaadin: A Familiar Way to Build Web Apps with Java

Defining a Widget Set Widget Project Structure A widget set is a collection of widgets that, together with the communication framework, form the Client-Side Engine of Vaadin, when compiled with the GWT Compiler into JavaScript.

A widget set is defined in a .gwt.xml GWT Module Descriptor. You need to specify at least one inherited base widget set, typically the DefaultWidgetSet or a custom set.

The client-side source files must be located in theclient sub- package under the package of the descriptor.

You can associate a stylesheet with a widget set with the element in the .gwt.xml descriptor: Figure 7: Widget set source structure. The Figure 7 illustrates the source code structure of a widget You can create new widgets easily with the Vaadin Plug-in project (for the Color Picker example). for Eclipse. For more information on Vaadin, visit the Vaadin Blog at http://vaadin.com/blog or the Forum at http://vaadin.com/forum

ABOUT THE AUTHOR RECOMMENDED BOOK Marko Grönroos is a professional writer and Book of Vaadin is a comprehensive software developer working at Vaadin Ltd, the documentation of Vaadin. It shows how to get company behind Vaadin. He has been involved started, gives a good overview of the features, in web application development since 1994 and and tutors you through advanced aspects of the has worked on several application development framework. frameworks in C, C++, and Java. He has been active in many open-source software projects and READ NOW holds an M.Sc. degree in Computer Science from http://vaadin.com/book the University of Turku. He lives in Turku, Finland.

Website: http://iki.fi/magi Blog: http://markogronroos.blogspot.com/

#82

CONTENTS INCLUDE:

■ Browse our collection of over 100 Free Cheat Sheets About Cloud Computing ■ Usage Scenarios Getting Started with dz.com ■ Underlying Concepts ■ Cost ... ® efcar ■ #64 Data Tier Technologies . Cloud Computing omply brought■ Platform to you Management by and more... e. C . Collaborat

isit r isit AldonChange By Daniel Rubio V

dz! also minimizes the needCONTENTS to make designINCLUDE: changes to support ABOUT CLOUD COMPUTING one time events. ■ HTML Basics dz.com ■ Upcoming Refcardz HTML vs XHTML Web applications have always been deployed on servers Automated growth & scalable technologies ■ Validation connected to what is now deemed the ‘cloud’. Having the capability■ to support one time events, cloud efcar

e Refcar Useful Open Sour computing platforms also facilitate the gradual growth curves ■ Page Structur #84 However, the demands and technology used on such servers ce T faced by web applications.■ ools isit r Key Structural Elementse Elements and m E: has changed substantiallyBy Paul in recent M. years, Duvall especially with V

the entrance of service providers like Amazon, Google and Large scale growth scenarios involving specialized equipment Integration Continuous Integration: CONTENTS INCLUD Microsoft. (e.g. load balancers and clusters) are all but abstractedore... away by Patterns and Anti-Patternse changes dz! Continuous Delivery ■ e at Every Change About Continuous rns orkspace to isolat relying on a cloud computing platform’s technology. Cor ■ Build Softwar Description e in a Private W epository HTML BASICS These companies have long deployedntrol r web applications

■ Patterns and Anti-patteol Develop softwar rging and to manage dz.com n that adapt and scale to large user bases, making them In addition, several cloud computing platforms support data e Patter fi les to a version-co ■ HTML Version Contr HTML and XHTML ar more... orkspaceknowledgeableCommit allin manyline aspects to minimize r meelated to cloud computing. tier technologies that exceed the precedent set by Relational ■ Build Management Private W hat utilizes multiple e Refcar HTML is used as the graphical user interface in client-side

Develop on a main Database Systems (RDBMS): Map Reduce,e the foundationweb service of ,all web development. efcar ■ Build Practices and Repository active code lines e within a system t ts of work pr TION This Refcard will introducear to you to cloud computing, with an etc. Some platformsograms support written lar gein JavaScript.scale RDBMS Server deployments. The sr By CSS3 e Mainline Developing softw by task-oriented uni and Java also r c attribute describes wher Andy Harris war Get Mor emphasis on these providers, so you can better understand codelines and the alt attribute describes alternate text that is displayed if

ask Level Commit isit r isit ce code changes ol as the output mechanism.eceive data The fr emer what it is a cloudganize computing sour es as aplatform T can offer your web the image is unavailable.

V ocess of building soft Codeline Policy Or ce without likewise use HTML and XHTML as their visual-side engine. languages HTML like PHP e the image Get Mor om web pages and use HTML s version contr applications.it and submit chang h unique name e from sour CLOUD COMPUTING PLATFORMS AND ABOUT CONTINUOUS INTEGRAoject’ was once a very loosely-defi Nested tags file can be found,

tion (CI) is the pr e.com Task-Level Comm Label the build wit ies to build softwar re minimum UNDERLYING CONCEPTS

dz! dz! oblem ging Ajax technologies T standar ags can be (and fr committed to a pr USAGE SCENARIOSAutomate all gurationactivit pendencies to the ba dization, but as it has become mor Continuous Integra Label Build manual confi same deployment need for standar ned language with very little cannot overlap, so zon onment , a solution to a pr e-installed tool de equently ar NoSQL blem) target envir Amazon EC2: Industry standard software and virtualization b> with every change. Automated Build Reduce pr whether you chooseds tohas write become HTML mor or XHTML, understanding e) nested inside each other patterns (i.e. ns (i.e., ineffective . deployment, use the is fi epository Pay onlyncies what you consumeAR or EAR) in each Amazon’s cloudthe curr computing platform is heavily based on ne. r For each tagged e important, the

x” the particulare solutions pro thatuce Web application deployment until a few years agoonment was similar ent standar e appar is not legal, but e Refcar e xt) and anti-patter Minimal Depende package (e.g. W dent libraries get envir industry standarthat willd simplifysoftwar alle and your virtualization other web coding. technology Fortunately. HTML erns ar ent. Regar HTML VS XHTML . T CI can be explained via s used to “fi t can fi le that all tar ds will help you pr ags Binaryto Integrity most phone services:Centralize plans all depen withte alloted resources, with an and XHTML ar

Get Mor Get appear to befects. bene They aresults when compa The various resources consumed by web applicationsly, continually (e.g. Every page (HTML or XHTML shar Perform a Private velopment team individual operating system sinstances. Browser manufactur

adverse ef egration Staged Builds Repository tion Build periodical common.) All ar bandwidth, memory, CPU) are tallied on aom per CI server-unit to basis de web developers came up with clever workar produce unintended r Private Build Perform an Integra edback fr extension. HTML ers added many competing estandar than anybody Refcard (starting from zero) by all major cloud computing platforms. As a user of Amazon’s eEC2 essentially cloud computing plain text platform, you are result is a lack of standar ation term Continuous Int y occur es certain elements in the pattern. ch as Send automated fe ith builds based on processor ors as soon as the assigned an operating systemfiles should in the not same be cr way as on all hosting The latest web standar tional use of thend test” cycle, this Integration Build er documentation w e.com

Continuous Integr clude concepts su While the convenefers to the n“build of CI ato in Generate develop

expands on the notio DZone, Inc. Cloud Computing 140 Preston Executive Dr. Suite 100 Cary, NC 27513 DZone communities deliver over 6 million pages each month to 888.678.0399 more than 3.3 million software developers, architects and decision 919.678.0300 makers. DZone offers something for everyone, including news, Refcardz Feedback Welcome tutorials, cheat sheets, blogs, feature articles, source code and more. [email protected]

“DZone is a developer’s dream,” says PC Magazine. $7.95 Sponsorship Opportunities Copyright © 2011 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, [email protected] Version 1.0 without prior written permission of the publisher.