Seminar : Rich Java Client with GWT, Ext JS and GXT Presenter: Yoav Aharoni, Chief Architect

Post on 26-Feb-2016

241 views 8 download

description

Seminar : Rich Java Client with GWT, Ext JS and GXT Presenter: Yoav Aharoni, Chief Architect. Agenda. What is RIA? RIA Solutions Overview Focus on Leading RIA JavaScript Solution Ext-JS in a nutshell GWT – The Java Advantage What is it, Why it is good for us, How to use it - PowerPoint PPT Presentation

transcript

Rich Java Client Seminar

1

Seminar:Rich Java Client with GWT, Ext JS and GXT

Presenter: Yoav Aharoni, Chief Architect

Rich Java Client Seminar

2

Agenda What is RIA?

– RIA Solutions Overview Focus on Leading RIA JavaScript Solution

– Ext-JS in a nutshell GWT – The Java Advantage

– What is it, Why it is good for us, How to use it GXT – Great Library for GWT

– Creating beautiful RIAs with GWT & GXT

Rich Java Client Seminar

3

Agenda Best Practices & Design Patterns Alternative Solutions Other 3rd Party Libraries & Frameworks Recap

Rich Java Client Seminar

4

RIA

Let’s get started...

Rich Java Client Seminar

An HTML Tale

Rich Java Client SeminarTim Berners-Lee

Evolution

HTML

90

Rich Java Client Seminar

Evolution

HTML

CSS

JS

LESS

JS Libs

CSS Libs

HTML5GWT

Ajax

1990

SASS

90

Rich Java Client Seminar

Then, an idea...

Rich Java Client Seminar

And that’s were things went wrong...

Rich Java Client Seminar

Because HTML wasn’t designed for it

Rich Java Client Seminar

Heck, developers aren’tdesigned for it...

Rich Java Client Seminar

So what’s bothering us withHTML/CSS/JS development?

Rich Java Client Seminar

13

What is RIA Type of application Not a framework Specs

– Responsive– Desktop-like

Not a website Usually runs on the client (plugins / js)

Rich Java Client Seminar

» Play Media: Video, Audio» Draw: 2D, 3D» Store Local Data» Bi-directional Client-Server

Communication» Concurrent JavaScript» More...

» JavaScript: Dynamic Prototype based OO Lack of Tools

» HTML/CSS: Quirks Hacks Boilerplate code

Stuff We Can’t Do Hard to Develop

Web Development Issues

Rich Java Client Seminar

Evolution

HTML

CSS

JS

LESS

JS Libs

FlashApplets

FlexJavaFXCSS Libs

Silverlight

Ajax SASS

Rich Java Client Seminar

Evolution

HTML

CSS

JS

LESS

JS Libs

FlashApplets

FlexJavaFXCSS Libs

Silverlight

Ajax SASS

HTML5GWT

W3C

Better Specs, Better Browsers

Rich Java Client Seminar

JavaScript

HTML

CSS

GWT in a Nutshell

Rich Java Client Seminar

Web Development Sore Spots Cross Browser Compatibility Issues JavaScript:

– Dynamic– Prototype based OO– Lack of tools– Managing 3rd party dependencies and a large code base is an issue.

HTML/CSS:– Quirks– Hacks– Boilerplate code

Rich Java Client Seminar

19

GWTThe Java Advantage

Rich Java Client Seminar

GWT in a Nutshell

JavaScript

GWTCompile

r

Java

Rich Java Client Seminar

JavaScript

HTML

CSS

GWT in a Nutshell

Rich Java Client Seminar

GWT Benefits Develop using Java.

– Using YOUR IDE.– Java tools: refactoring, debugging, profiling, etc…– Detect error in compile-time rather than runtime.– JUnit integration.

Good holistic development environment. Cross browser compatible. Runs natively on the browser, no plugins needed.

Rich Java Client Seminar

GWT Benefits Built for speed, lots of optimizations. Has everything a framework needs.

– Dynamic, rich, reusable widgets. Lots of them.– Ajax, utilities and more.

Plus:– It’s Open source, Apache v2.0 license. – It’s Google’s...

Rich Java Client Seminar

24

GWT Cons Google has practically stopped actively

developing GWT Java is less powerful than JavaScript

Rich Java Client Seminar

25

Who Is Using GWT? Used by Google:

– iGoogle, Google Flights, Blogger, Google Shopping, Google Offers, Google Wallet, AdWords, AdSense, Orkut, Google Health,Google Wave (may it RIP)

Companies I’ve been to and use GWT:– PayPal, HP, Intel, BillGuard, Malam-Team, EMC, CA,...

Rovio and King.com And also...

Rich Java Client Seminar

Agenda Introduction GWT Basics Developing with GWT Widgets Internationalization ClientBundle Ajax UiBinder Security Bookmarks & History

Rich Java Client Seminar

Agenda Best Practices & Design Patterns Testing & Profiling 3rd Party Libraries Reference

Rich Java Client Seminar

Introduction

GWT What?

Rich Java Client Seminar

Rich Internet Applications RIA – a cross between web applications and

desktop applications. Introduced in a Macromedia whitepaper in

March 2002. RIA is typically run in a web browser, or do not

require software installation. Current solutions include Flash/Flex, Silverlight

and JavaScript.

Rich Java Client Seminar

GWT Introduction Google Web Toolkit Is: A Web Framework. A SOUI / SOFEA Framework. A Sort of JavaScript Framework. One of Google’s gifts to Java developers. All of the Above.

Service-Oriented Front-End Architecture or Service-Oriented User Interface

Rich Java Client Seminar

Introduction GWT in a Nutshell... A web framework for rapid developing and

debugging of JavaScript front-end applications in Java.1. Develop in Java.2. Compile into JavaScript.3. Run on a Browser. BrowserJavaScriptJava

Rich Java Client Seminar

Introduction Mission Statement

“GWT's mission is to radically improve the web experience for users by enabling developers to use existing Java tools to build no-compromise AJAX for any modern browser.”

Rich Java Client Seminar

Introduction What’s so good about it? It’s built for speed and it’s fast as it gets. Runs natively on the browser, no plugins needed. Cross browser compatible. Has everything a framework needs.

– Dynamic, rich, reusable widgets. Lots of them.– Utilities and more.

Big active community. Many 3rd party libraries already out there. Simple built-in Ajax/RPC mechanism.

Rich Java Client Seminar

Introduction What’s so good about it? Develop using Java.

– Using YOUR IDE.– Detect error in compile-time rather than runtime.– Java tools: refactoring, debugging, profiling, etc…– JUnit integration.

Good development environment. It’s Open source: Apache v2.0 license. It’s Google’s – will be around for a long time.

Rich Java Client Seminar

Introduction History Announced at JavaOne, 2006.

Formerly known as “Project Red Pill”. Current release: 2.1.

05/2006

10/2010

06/2009

1.0 RC 1

08/2006

11/2006

02/2007

08/2007

08/2008

04/2009

12/2009

2.01.7 2.21.5

10/2010

2.1

Rich Java Client Seminar

Introduction History Announced at JavaOne, 2006.

Formerly known as “Project Red Pill”. Current release: 2.1.

•Support for Java 5 features.•Even more compiler optimizations.•UI library additions (animations,

themes).•I18N (Bi-di, pluralizations), accessibility.•Better DOM API.

05/2006

10/2010

06/2009

1.0 RC 1

08/2006

11/2006

02/2007

08/2007

08/2008

04/2009

12/2009

2.01.7 2.21.5

10/2010

2.1

Rich Java Client Seminar

Introduction History Announced at JavaOne, 2006.

Formerly known as “Project Red Pill”. Current release: 2.1.

•Development Mode•Speed Tracer •Code Splitting•Compiler Optimizations•Draft Compile•Declarative UI•ClientBundle•HtmlUnit

05/2006

10/2010

06/2009

1.0 RC 1

08/2006

11/2006

02/2007

08/2007

08/2008

04/2009

12/2009

2.01.7 2.21.5

10/2010

2.1

Rich Java Client Seminar

Introduction History Announced at JavaOne, 2006.

Formerly known as “Project Red Pill”. Current release: 2.1.

•Cell Widgets•MVP Framework•Request Factory•Editor framework•Logging•SafeHtml•Spring Integration

05/2006

10/2010

06/2009

1.0 RC 1

08/2006

11/2006

02/2007

08/2007

08/2008

04/2009

12/2009

2.01.7 2.21.5

10/2010

2.1

Rich Java Client Seminar

Introduction History Announced at JavaOne, 2006.

Formerly known as “Project Red Pill”. Current release: 2.1.

•Integrated designer•HTML5 Canvas, Audio and

Video•CellTable Updates•SafeHtml lenient parser•Mobile touch events•Improved Bidi support

05/2006

10/2010

06/2009

1.0 RC 1

08/2006

11/2006

02/2007

08/2007

08/2008

04/2009

12/2009

2.01.7 2.21.5

10/2010

2.1

Rich Java Client Seminar

How does it work?

... and why is it so damn fast...

Rich Java Client Seminar

Architecture

JRE Emulation

GWT Compiler

Dev.Mode

Class Library

Deve

lopm

ent

Servlet Container

GWT RPCRemote Service Servlet

Web Services

Serv

er-S

ide

Ajax

GWT Runtime

Compiled JavaScript

Clie

nt-S

ide

Compile

Rich Java Client Seminar

JRE emulation library JavaScript implementations of the most

commonly used classes in JRE– most of the java.lang package– a subset of the java.util package

Several classes are missing– java.util.Calendar– date-formatting classes

More Info

Rich Java Client Seminar

Deferred Binding Definition: a technique used by the GWT compiler

to create and select a specific implementation of a class based on a set of parameters.

GWT produces a different application permutations for each browser environment.– Only one permutation is downloaded and executed by

the browser.– Permutations can be created for each Locale.– Additional custom parameters can be configured.

DOMImpl impl = GWT.create(DOMImpl.class);

Rich Java Client Seminar

Deferred Binding - Benefits Branching is done in compile time rather than runtime.

– No runtime penalty for lookup. Download and evaluate only the minimum needed

code.– Reduce download size.– Reduce execution time.

Saves development time by automatically generating code to implement an interface or create a proxy class.

More Info

Rich Java Client Seminar

Development Lifecycle Download SDK + Browser Plugin

Create Project with IDE/Maven Develop & Code

View & Debug using Dev. Mode

Compile to JavaScript

Deploy to Prod Server

Profile withSpeed Tracer

Unit Test with Java Tools

Debug using Dev. Mode

Fix Bugs

Rich Java Client Seminar

Developing with GWT

Lets get to work!

Rich Java Client Seminar

Developing with GWT

Available Tools Standard Directory Layout Building Blocks

– Module– Host Page– Entry Point– RootPanel

Running the Application– Application Modes– Development Mode

Rich Java Client Seminar

Available Tools Google SDK Eclipse

– Google Plugin for Eclipse– Google GWT Designer (previously Instantiations)

IntelliJ IDEA – GWT Support Plugin (built-in). Netbeans - GWT4NB Plugin Maven - gwt-maven-plugin Speed Tracer GWT Theme Generator

Rich Java Client Seminar

Creating a New Project webAppCreator - Generates all files needed in

order to start a new GWT project.– Generates Eclipse project files and launch

configuration– Generates Ant build.xml

Rich Java Client Seminar

Creating a Project: webAppCreator -out specifies which directory to place the

generated files in A second argument specifies the GWT logical

module name. From the project root directory, use:

– ant devmode: runs in development mode– ant build: runs in production mode

Rich Java Client Seminar

Creating a Project: Eclipse File -> New -> Web Application Project

1. Enter project name2. Enter package name3. Select default GWT SDK4. Select default Google App Engine SDK (optional)5. Click Finish

Rich Java Client Seminar

Creating a Project: IntelliJ File -> New Project Select Create new project from scratch

– Enter Project Name– Enter Project Location– Select “Java Module” in Module Settings– Select “Next”

Edit source directory, Select “Next”

Rich Java Client Seminar

Creating a Project: IntelliJ Create a new GWT Module by right click src folder

Rich Java Client Seminar

Creating a Project: Maven Use gwt-maven-plugin. mvn archetype:generate

-DarchetypeRepository=repo1.maven.org -DarchetypeGroupId=org.codehaus.mojo -DarchetypeArtifactId=gwt-maven-plugin -DarchetypeVersion=2.1.0-1

Or (since GWT 2.1.0):webAppCreator -maven -noant com.example.MyApplication

Rich Java Client Seminar

Rich Java Client Seminar

Standard Directory LayoutPackage folder (root) E.g. com.alphacsp

<app-name>.gwt.xml Module definition file

client The client package containing code that will be cross compiledto JavaScript

server The package containing server-side implementation code

public Folder containing assets used by the module (images,CSS files, other resources)

rebind The package containing compile-time code (generators)

Rich Java Client Seminar

Building Blocks Module - An individual unit of GWT

configuration and resources.– Composed of Java sources, static resources and an

XML configuration file.– Defines an application starting point called

Entry Point. Module’s entry point is invoked from an HTML

page called Host Page.

Rich Java Client Seminar

Module A module bundles configuration and execution settings

for a GWT project.

Modules can be inherited. – Most modules inherit built-in modules.

XML descriptor, which contains:– Entry point class name.– Source path entries.– Deferred binding rules (for example I18n).– Other rules...

Rich Java Client Seminar

XML Descriptor<module> <inherits name="com.google.gwt.user.User"/> <inherits name="com.google.gwt...Standard"/>

<entry-point class="com.alphacsp.gwt.client.Demo"/>

<source path="client"/> <public path="public"/>

<stylesheet src="Demo.css"/></module>

Rich Java Client Seminar

Host Page HTML page hosting our GWT application. Meaning, application will run in this page. This is done by including reference to the compiled

JavaScript file: <ModuleName>.nocache.js– Created during GWT compilation.– This “Ignites” the application loading process.

Host pages can be either static or dynamic server pages.

Rich Java Client Seminar

Minimal Host Page<!DOCTYPE html><html><head>

<script type="text/javascript" language="javascript“ src="com.alphacsp.gwt.Demo.nocache.js"></script></head><body></body></html>

Rich Java Client Seminar

Entry Point & Root Panel Entry Point is to GWT is as main() is to Java. Contains module initialization code. It is a class implementing the EntryPoint interface.

Root Panel, a default wrapper around <body> tag, is usually being used.– RootPanel.get()

Composite elements can be added as decedents of the root panel.

Rich Java Client Seminar

Sample EntryPointpublic class Demo implements EntryPoint { @Override public void onModuleLoad() { RootPanel.get().add(new Label("Hello World")); }}

Rich Java Client Seminar

Root Panel & Placeholders You may insert widgets into specific

placeholders in an HTML page.Java

button = new Button("Click me");label = new Label(); ...RootPanel.get("slot1“).add(button);RootPanel.get("slot2“).add(label);

HTML

<body> <!-- ... More HTML ... --> <table align=center> <tr> <td id="slot1"></td> <td id="slot2"></td> </tr> </table> </body>

Rich Java Client Seminar

Application Modes There are two application modes:

– Production mode – Development mode.

Production Mode– Application is compiled into JavaScript.– Deploy into a web server.– Compilation may take a couple of minutes...

Rich Java Client Seminar

Compilation Only “used” code is compiled. Produced artifacts:

– Highly optimized JavaScript– and CSS.– Images & Sprites java -cp “%CLASSPATH%;gwt-dev.jar” com.google.gwt.dev.Compiler %MODULE%

Rich Java Client Seminar

Compilation Style –style command-line option:

– OBF: obfuscated mode, suitable for production use.

– PRETTY: pretty printed JavaScript.• Useful for debugging.

– DETAILED: pretty printed JavaScript with fully qualified names.

Rich Java Client Seminar

IntelliJ GWT Compiler

Rich Java Client Seminar

Development Mode Replaces what used to be called “hosted

mode” up until GWT 1.7.– Start Application in Development mode using

GWT Shell (inside SDK) or an IDE plugin.– Lunch application in a regular browser with a GWT

Developer Plugin installed.– Java code is interpolated on-the-fly. No need to

compile to JavaScript. Just edit, save and refresh. You may start development mode to debug

production server.

Rich Java Client Seminar

Eclipse Development Mode Running using Eclipse:

Copy/paste the URL in Dev Mode view onto your favorite browser:

Rich Java Client Seminar

Eclipse Development Mode You may be prompted to install the Google

Web Toolkit Developer Plugin:

In order to use GWT compiler, use:

Rich Java Client Seminar

IntelliJ Development Mode

Rich Java Client Seminar

IntelliJ Development Mode Running using IntelliJ

You may be prompted to install the Google Web Toolkit Developer Plugin

Rich Java Client Seminar

Rich Java Client Seminar

Widgets

UI Components

Rich Java Client Seminar

GWT Widgets Widgets area UI Components. Developed in Java. Implemented natively using JavaScript and

DOM elements. Meant for reuse. Compiled, packaged and

distributed in jar files. Two categories:

– “Regular” Widgets – which users may interact with(e.g. buttons, links)

– Panels - containers for other components.

Rich Java Client Seminar

DOM Tree Example

<html><head> <title>My title</title></head><body> <h1>My header</h1> <a href=“url”>My link</a></body></html>

Rich Java Client Seminar

Sample Widgets new Button()

new TextBox()

new Tree()

new RichTextArea()

Rich Java Client Seminar

Widgets

Rich Java Client Seminar

Widgets

• Wraps DOM element.• Cannot receive events.• Methods: getElement(), getStyleName(),

isVisible(),...

Rich Java Client Seminar

Widgets

• Base for most components.• Receives events.• Can be added to panels.• Methods: getParent(), addHandler(),

isAttached(),...

Rich Java Client Seminar

Widgets

• Base for most widgets that can receive keyboard focus.

• Methods: setFocus(), getTabIndex(), setAccessKey(), ...

Rich Java Client Seminar

Rich Java Client Seminar

Panel Container of other widgets. Propose: Layout widgets on the page.

– Position and manage the visibility of widgets.– May use child’s layout data hint.

Can be nested. Implemented using DOM elements such as

DIV or TABLE.

Rich Java Client Seminar

Panels

Rich Java Client Seminar

Panels

• Base for most containers.• Layout children using layoutData.• Methods: add(), remove(), clear(),...

Rich Java Client Seminar

Panels

@Deprecated:• HorizontalSplitPanel, VerticalSplitPanel• DockPanel• TabPanel

Rich Java Client Seminar

Panels

• Rectangular grid.• Rresized explicitly.

• Creates cells on demand.• Can be jagged (rowSpan / colSpan).

Rich Java Client Seminar

Panels

• Notice: RootPanel is an AbsolutePanel

Rich Java Client Seminar

DOM Related Classes Window – represents browser’s window.

– Window.alert(message)– Window.confirm(message)– Window.setTitle(title)

Document – represents HTML document.– Document.get().getClientWidth()– Document.get().createDivElement()– Document.get().getElementById(id)

DOM – utility for manipulating DOM– DOM.insertChild(parent, child, index)

Rich Java Client Seminar

GWT Events Involved Classes:

– GwtEvent<H extends EventHandler>– GwtEvent.Type<H>– EventHandler– HasHandlers (e.g: EventBus)

Rich Java Client Seminar

Event Classes

GwtEvent Type

EventHandler

HasHandlers

Has

Fires

Registers at

Handles Listens to

Rich Java Client Seminar

Events API Registration:

– widget.addHandler(EventHandler, Type)

“Shortcut” Methods:– e.g: button.addClickHandler(ClickHandler)

Returned value:– HandlerRegistration instance. Used to unregister

handlers.

Note: EventListener and related methods are deprecated.

Rich Java Client Seminar

DOM Events DOM Event Registration:

– widget.addDomHandler(handler, type)

DOM Events are bubbled.– Mouse events can be captured.

– Event.setCapture(element)

DOM Events can be “previewed”:– Event.addNativePreviewHandler(handler)

Rich Java Client Seminar

Event.addNativePreviewHandler (new Event.NativePreviewHandler() {

public void onPreviewNativeEvent (NativePreviewEvent event) {

switch (event.getTypeInt()) {case Event.ONCLICK:case Event.ONKEYPRESS:

...}

}});

Handling Previewed Events

Rich Java Client Seminar

Low Level DOM Event API

Event.sinkEvents(element, eventBits) Event.setEventListener(element, listener)

Rich Java Client Seminar

Widget Events (i.e. addHandler) AttachEvent ValueChangeEvent Window.ScrollEvent SelectionEvent CloseEvent ResizeEvent More... Your custom events

Rich Java Client Seminar

DOM Events (i.e. addDomHandler) Mouse Events MouseDownEvent

MouseWheelEvent MouseUpEvent DoubleClickEvent MouseOverEvent MouseOutEvent MouseMoveEvent ClickEvent

KeyPressEvent KeyDownEvent KeyUpEvent

BlurEvent FocusEvent ChangeEvent ScrollEvent

Key Events

Other Events

Rich Java Client Seminar

Themes A GWT Theme is a simple module, containing

CSS Style Sheet defining widgets look n’ feel. To apply a theme, inherit it in your module’s

xml descriptor:<inherits name="com...theme.standard.Standard"/>

Rich Java Client Seminar

Available Themes GWT is bundled with several themes:

– com.google.gwt.user.theme.standard.Standard– com.google.gwt.user.theme.dark.Dark– com.google.gwt.user.theme.chrome.Chrome

All of which have a secondary RTL version: StandardRTL, DarkRTL, ChromeRTL.

When custom theme is required, bundled themes can be either patched, partially overridden or replaced.

Rich Java Client Seminar

Styling Widgets Styling is applied using HTML’s class attribute. All widgets have StylePrimaryName. And may have StyleDependentName. Styles are added using methods:

– widget.setStylePrimaryName()– widget.setStyleName(), widget.addStyleName()– widget.addStyleDependentName()

Low level DOM API:– element.getStyle()– element.addClassName()

Rich Java Client Seminar

Adding CSS Styles Sheets Style Sheets can be added in several ways: Add style sheet directly to Host Page.

Add style sheet to module’s xml descriptor.

Add style using ClientBundle and CssResource.– Some advantages when using this method.– Will be discussed later in details.

<link type="text/css" rel="stylesheet" href="style.css"/>

<stylesheet src=“style.css"/>

Rich Java Client Seminar

Restyling Existing Components Methods for Finding CSS Class Names 1. See CSS Style Rules section in each widget’s JavaDoc.

2. Look for method invocations (e.g. addStyleName).

3. Inspect elements using:– Firefox’s Firebug– Internet Explorer Developer Toolbar– Chrome Developers Tools– Opera Dragonfly.

Rich Java Client Seminar

Rich Java Client Seminar

Custom Components Use cases A Brand new unique component is needed –

rare use case.– Example: Slider

Component build as composition of other existing components – common use case.– Example: TextBox

+ Button + Popup + DatePicker = DateField

01/02/2003

Rich Java Client Seminar

Creating Unique Components Achieved by subclassing Widget class. Tasks:

– Create elements using Document.get().createXXX()

– Set widget’s element by calling widget.setElement()

– Manipulate elements using Element methods and DOM utility class.

– Listen to events, prefer addDomHandler(handler) over overriding onBrowserEvent().

Rich Java Client Seminar

Creating Compositions» Rather than subclassing Panel, subclass Composite

class:– A widget that wraps another widget, typically a

Panel.– When added to a Panel, behaves as if the

wrapped widget has been added. Incentive: control which methods are publicly

accessible. API Contract:

– Initialize by calling initWidget(widget).

A newer alternative (since GWT 2.1):– Implement IsWidget interface.

Rich Java Client Seminar

Implemented Interfaces When creating a custom component, it might

be useful to let is implement interfaces such as:– HasValue<T>– HasText – HasName– HasHandlers, HasClickHandlers,

HasKeyPressHandlers, ...

Rich Java Client Seminar

Rich Java Client Seminar

Cell Widgets Useful set widgets used for displaying lists or

trees. Introduced in GWT 2.1, improved in GWT 2.2. Supports sorting, paging, selection, etc.

Rich Java Client Seminar

Cell Widgets API Cell Widget Classes Cell – responsible for displaying or editing a

value(e.g. NumberCell, DateCell, TextCell, PersonCell).

Cell Widget – receives data and cells; uses cell to display data (e.g. CellTable, CellTree).

Rich Java Client Seminar

Simple Cell Example Code:

Result:

CellList<String> cellList = new CellList<String>(new TextCell());List<String> strings = createStringList();cellList.setRowData(strings);add(cellList);

Rich Java Client Seminar

Cell Interface Rendering

Rich Java Client Seminar

Cell Interface Event Handling

Rich Java Client Seminar

Cell Types Base: AbstractCell, AbstractEditableCell Text: TextCell , ClickableTextCell, SafeHtmlCell Formatted: NumberCell, DateCell Images: ImageCell, ImageResourceCell,

ImageLoadingCell Actions: ActionCell, ButtonCell Editable: CheckboxCell, EditTextCell,

SelectionCell, TextInputCell, DatePickerCell Other: CompositeCell, IconCellDecorator

Rich Java Client Seminar

Available Cell Widgets CellWidget – Displays one cell. CellList – Displays a list of cells. CellTable – Each column displays a cell. CellTree – Each node is a cell. CellBrowser – Displays a TreeViewModel as a

“browser”.

Rich Java Client Seminar

Cell Widgets: Related Classes Key Provider – Provides key for each data

item.

Returned Key must implement equals() and hashCode().

Among other things, key is used by various Cell methods, determines selected item, etc.

» Default implementation – SimpleKeyProvider.

public interface ProvidesKey<T> { Object getKey(T item);}

Rich Java Client Seminar

Cell Widgets: Value Updater ValueUpdater and FieldUpdater – used by

CellList and CellTable respectively to update values of editable cells.interface ValueUpdater<C> {

void update(C value);{

interface FieldUpdater<T, C> { void update(int index, T object, C value);{

Rich Java Client Seminar

Cell Widgets: Sort Handler ColumnSortEvent are fired whenever a

sortable column is clicked. A ColumnSortEvent.Handler is implemented

to handle the sort event.

Default implementations exist: – ListHandler – used for client-side sorting.– AsyncHandler – used for server-side sorting.

public static interface Handler extends EventHandler { void onColumnSort(ColumnSortEvent event);{

Rich Java Client Seminar

Cell Widgets: Pagers Pagers provide paging GUI. A pager is bound to a cell widget and invoke

cellWidget.setVisibleRange() method whenever used.

Existing pagers:– SimplePager – a simple pager.

– PageSizePager – controls # of rows in page.

– AbstractPager – base class for implementing your one pager.

Rich Java Client Seminar

Cell Widgets: Data Provider Data Provider – holds data and is bound to

one or more cell widgets (CellTable or CellList).

» Available classes: AbstractDataProvider, ListDataProvider, AsyncDataProvider.

» DataProvider is useful for implementing paging and sorting.Cell Widget DataProvidersetRowData()

Sort HandlerPager

Fire RangeChangeEvent

setVisibleRange() May UseColumnSortEvent

Rich Java Client Seminar

Rich Java Client Seminar

Editor Framework Introduced in GWT 2.1. Use conventions and annotations to bind UI

to model beans. Framework is composed of Editors and

Drivers.– Editor is an object, usually a widget, responsible

for editing a specific type (e.g. String, Long, Person).

– A Driver is used to initialize Editors and to copy data from Editor to model and vice versa.

Rich Java Client Seminar

Editors All built-in field widgets (e.g. TextBox) are

Editors. Composite Editors are created by

implementing marker interface Editor<T>. Mapping is done by using fields of other

Editors.public class PersonEditor implements Editor<Person> {

TextBox name;public IntegerBox ageEditor;...

}

Rich Java Client Seminar

Editor Conventions Editor’s class must be public. Sub-Editor field must be package visible (or

public). Property xxx is edited by sub-editor in a field

named xxx or xxxEditr. You can’t edit primitives (e.g. long), only

objects (Long).

public class PersonEditor implements Editor<Person> { TextBox name; public IntegerBox ageEditor;

...}

public class Person { public String getName() { ... } public void setName(String name) { ... }

public Integer getAge() { ... } public void setAge(Integer age) { ... }{

Rich Java Client Seminar

Editor Composition Composite Editors can contain other

composite Editors. public class PersonEditor implements Editor<Person> { TextBox name; AddressEditor addressEditor;

...}

public class Person { public String getName() { ... } public void setName(String name) { ... }

public Integer getAddress() { ... } public void setAddress (Address age) { ... }{

public class AddressEditor implements Editor<Address> { TextBox city;}

public class Address { public String getCity() { ... } public void setCity(String city) { ... }{

Rich Java Client Seminar

Editor Drivers A Driver must be created for root Editor. Drivers allow Editors to edit objects (i.e. copy

object values to UI) and to flush changes back to objects.

Two Drivers exists:– SimpleBeanEditorDriver – used to edit client-side

beans. – RequestFactoryEditorDriver – used for editing

server-side objects using RESTful web services.

Rich Java Client Seminar

Driver Usage - Exampleinterface Driver extends SimpleBeanEditorDriver<Person, PersonEditor> { }

public class PersonEditor implements Editor<Person> { ... }

public void init() {// Create and initialize Person DriverPersonEditor personEditor = new PersonEditor();Driver driver = GWT.create(Driver.class);driver.initialize(personEditor);

// Edit Person beanPerson person = new Person();driver.edit(person);

// Flush changes back to persondriver.flush();

{

Rich Java Client Seminar

Editor Annotations @Editor.Path annotation can be used to

specify edited property name (and ignore naming conventions).– It can also be used to edit nested properties.

@Editor.Ignore can be used to mark package visible fields which aren’t meant to be used as Editors.

public class PersonEditor implements Editor<Person> { @Path("phone") TextBox phoneNumber; @Path(“address.city") TextBox cityEditor; @Ignore DatePicker datePicker;

...{

Rich Java Client Seminar

Custom Editors Custom Leaf Editors can be created by

implementing LeafValueEditor<V>.– void setValue(V value) and V getValue(); must

be

implemented. Editors which delegate editing to other Editors

can be easily created by implementing IsEditor<E> interface.

class DateField implements IsEditor<LeafValueEditor<Date>> { private DateBox dateBox; public LeafValueEditor<Date> asEditor() { return dateBox.asEditor(); {{

Rich Java Client Seminar

Editors Adapters Several Editor adapters are bundled with

GWT. This is useful when using IsEditor<E>

interface. Existing Adapters:

– HasDataEditor - Adapts the HasData interface.– HasTextEditor - Adapts HasText to

LeafValueEditor<String>.– ListEditor - Keeps a List<T> in sync with a list of

sub-Editors.– OptionalFieldEditor – For nullable bean

properties.– SimpleEditor - Used as a headless property Editor.– TakesValueEditor - Adapts a TakesValue<T>.– ValueBoxEditor - Adapts a ValueBoxBase<T>.

Rich Java Client Seminar

Advanced Configuration Editor Subtypes:

– HasEditorDelegate - Every Editor has a peer EditorDelegate that provides framework-related services to the Editor (e.g. notify errors, get editor path).

– ValueAwareEditor – allows editor to be notified when object is being edited or flushed.

– HasEditorErrors – allows editor to be notified about ConstraintViolations in the value being edited.

Rich Java Client Seminar

Rich Java Client Seminar

Ajax Ajax - Asynchronous JavaScript and XML

– Allows client-server interaction without refreshing the entire page.

– Client usually invoke Web Services, passing JSON or XML.

GWT Ajax APIs– GWT-RPC– RequestBuilder– RequestFactory

Rich Java Client Seminar

Ajax Ajax - Asynchronous JavaScript and XML

– Allows client-server interaction without refreshing the entire page.

– Client usually invoke Web Services, passing JSON or XML.

GWT Ajax APIs– GWT-RPC– RequestBuilder– RequestFactory

<person><name>Paul</name><age>23</age><isSingle>false</isSingle><luckyNumbers>

<number>10</number><number>13</number>

</luckyNumbers></person>

Rich Java Client Seminar

Ajax Ajax - Asynchronous JavaScript and XML

– Allows client-server interaction without refreshing the entire page.

– Client usually invoke Web Services, passing JSON or XML.

GWT Ajax APIs– GWT-RPC– RequestBuilder– Request Factory

{ "personal": {"name": "Paul","age": 23, "isSingle": true, "luckyNumbers": [5,17,21]

}, "favoriteBands": ["Band ABC", "Band XYZ“]}

Rich Java Client Seminar

GWT RPC - Introduction RPC - Remote Procedure Calls Mechanism for passing Java objects to and

from a server over standard HTTP.– Based on Java Servlet API.

Best choice when creating your own interface and run Java on the server.

The server-side code gets invoked from the client is often referred to as a service.

Making a remote procedure call is sometimes referred to as invoking a service.

Rich Java Client Seminar

GWT RPC - Components In order to define an RPC interface, you need

to write three components:1. An interface for the service that extends

RemoteService and lists RPC methods.2. A class that implement the server-side code,

extending RemoteServiceServlet and implements the interface

3. An asynchronous interface to the service, to be called from the client-side code.

Rich Java Client Seminar

GWT RPC – Classes DiagramClient-Side Server-Side

Rich Java Client Seminar

RemoteService Interface An RPC service is an interface that extends

RemoteService interface The @RemoteServiceRelativePath annotation

associates the service with a default path relative to the module base URL.

Reside on client directory (source path).@RemoteServiceRelativePath(“contacts")public interface ContactService extends RemoteService { public Contact findContactById(Long id); }

Rich Java Client Seminar

Service Implementation A service implementation must implement the

associated interface. Implementation is ultimately a servlet.

– Extends RemoteServiceServlet.– Reside on server directory (server path).– Automatically handles serialization.– Invokes the intended method in your service

implementation.

Rich Java Client Seminar

Service Implementation Example

public class ContactServiceImpl extends RemoteServiceServlet implements ContactService {

@Overridepublic Contact findContactById(Long id) {

Contact contact;...return contact;

}}

@RemoteServiceRelativePath(“contacts")public interface ContactService extends RemoteService { public Contact findContactById(Long id); }

Rich Java Client Seminar

Servlet Mapping – web.xml Add <servlet> and <servlet-mapping>

elements to the web.xml– Point to the implementation class

In <servlet-mapping>, url-pattern can take form of an absolute directory path.

Make sure the url-pattern matches the @RemoteServiceRelativePath annotation value.

Rich Java Client Seminar

web.xml Example

<servlet> <servlet-name>Contacts Service</servlet-name> <servlet-class>hp.server.ContactServiceImpl</servlet-class></servlet><servlet-mapping> <servlet-name>Contacts Service</servlet-name> <url-pattern>/hp.Demo/gwt-rpc/*</url-pattern></servlet-mapping>

@RemoteServiceRelativePath(“contacts")public interface ContactService extends RemoteService { public Contact findContactById(Long id); }

web.xml Snippet

Rich Java Client Seminar

Asynchronous Service Interface Client creates a “proxy” that communicates

with the service implementation asynchronously.

When calling a remote procedure, a callback object is passed and executed when the call completes.

Rich Java Client Seminar

Asynchronous Service Conventions You must define a new interface that:

– Have the same name as the service interface, appended with Async.

– Located in the same package as the service interface.

– Has methods with the same name and signature as in the service interface, but with an important difference: The method returns void, and the last parameter is an AsyncCallback object.

public interface ContactServiceAsync { void findContactById(Long id, AsyncCallback<Contact> async);}

Rich Java Client Seminar

Callback methods Making an RPC call from the client:

1. Instantiate the service interface using GWT.create().

2. Create an asynchronous callback object to be notified when the RPC completes.

3. Make the call. It’s safe to cache the service proxy to avoid

creating it for subsequent calls.

Rich Java Client Seminar

RPC Invocation ExampleContactServiceAsync service = GWT.create(ContactService.class);service.findContactById(id,new AsyncCallback<Contact>() {

@Overridepublic void onFailure(Throwable caught) {

// handle exception{

@Overridepublic void onSuccess(Contact contact) {

// use result{

});

Rich Java Client Seminar

Serialization GWT RPC requires that all service method

parameters and return types be serializable. A type is serializable if one of the following is

true:– Type is a primitive types or primitive Wrapper

Object.– Type is an array of serializable types.– Type is a serializable class.

Rich Java Client Seminar

Serialization A class is serializable if it meets these three

requirements: – It implements either Java Serializable or GWT

IsSerializable interface, directly or by inheritance.– Its non-final, non-transient instance fields are

themselves serializable.– It has a default (zero argument) constructor with

any access modifier

Rich Java Client Seminar

Handling Exceptions When a remote procedure call fails, the cause

is either unexpected or checked exception. Unexpected exception: communication

problems, or undeclared exceptions in server side– In client-side, the onFailure(Throwable) the

callback method will receive an InvocationException with the generic message

– Find stack trace in the development mode log.

Rich Java Client Seminar

Handling Exceptions Checked Exception: GWT supports the throws

keyword so you can add it to your service interface methods as needed– GWT will serialize the exception and send it back

to the client for handling.

@RemoteServiceRelativePath(“contacts")public interface ContactService extends RemoteService { public Contact findContactById(Long id) throws MyException; }

Rich Java Client Seminar

Rich Java Client Seminar

I18N - Internalization I18N - Internationalization L10N - Localization Locale - Language + Location (Country) Examples:

– language=English, location=United States.– language=German, location=Switzerland– language=German, location=Germany,

variant=Euro

Rich Java Client Seminar

Java Locale Has two arguments:

– Language (ISO-639)• Lowercase two-letter code

– Country code (ISO-3166)• Uppercase two-letter code

– Locale germanGermany = new Locale("de", "DE");– Locale germanSwitzerland = new Locale("de",

"CH");

Rich Java Client Seminar

Java Localized Objects Numbers and Currencies Date and Time Resource Bundles

Rich Java Client Seminar

Resource Bundles Motivation:

– Avoid hard-coded strings.– Supply different strings for different Locales.

In Java, Resource Bundles are defined in *.properties files.

Naming convention: BundleName_language_COUNTRY.properties

e.g:– MyMessages_he.properties– MyMessages_en_US.properties

new Label("Name");new Label("שם");

Rich Java Client Seminar

I18N in GWT Resources Bundles (*.properties files) must be

saved as UTF-8. Client-side implementation relays on Deferred

Binding.– A different application permutation is generated

for each Locale.– Additional benefit: we can define different class

implementation for each Locale (i.e. different logic/UI).

Locales are configured in module’s xml descriptor.– You must specify which Locales are used in your

application, in order for proper permutation to be compiled.

– No locale is set by default. It is advisable to always configure a default, fallback, Locale.

Rich Java Client Seminar

Module Configuration<!– Available Locales --><extend-property name="locale" values="en"/><extend-property name="locale" values="en_US"/><extend-property name="locale" values=“he_IL"/>

<!-- Default Locale --><set-property-fallback name="locale" value="en_US"/>

<inherits name="com.google.gwt.i18n.I18N"/> <inherits name="com.google.gwt.i18n.CldrLocales"/>

<head><meta http-equiv="content-type“ content="text/html; charset=UTF-8"> ...

Module.get.xml Snippet

Host Page Snippet

Rich Java Client Seminar

Setting Locale Locale can be set by:

– Passing “locale” parameter in URL query string:

– Using gwt:property meta tag:<head> <meta http-equiv="content-type“ content="text/html; charset=UTF-8"> <meta name="gwt:property" content="locale=ja_JP"></head>

Host Page Snippet

http://domain/module/page.html?locale=he_IL

Rich Java Client Seminar

Getting Locale Information Locale information get be viewed in runtime

using LocalInfo class:– LocalInfo.getCurrentLocale();– LocalInfo.getAvailableLocaleNames();– LocalInfo.getLocaleQueryParam()

Rich Java Client Seminar

GWT Localized Objects Static String Initialization

– Constants– Messages

Dynamic String Initialization– Dictionary

Formatting– com.google.gwt.i18n.client.NumberFormat– com.google.gwt.i18n.client.DateTimeFormat

Rich Java Client Seminar

Static String initialization Uses standard Java properties files to store

translated strings and parameterized messages.

Implements strongly-typed Java interfaces to values.

Benefits:– Simple technique to implement.– Requires very little overhead at runtime.– Work with methods, instead of Strings and

constants.– Easier refactoring and usage detection.

Two Java interfaces– Constants - For constants (usually strings).– Messages - For parameterized messages.

Rich Java Client Seminar

GWT Constants Composed of:

1. An interface which extends the Constants Interface.

2. Property files containing the constant values. This interface is bound to *.properties files in

the same package (i.e. folder) with the interface name.

Interface contains methods for each of the constants in the properties files.

Constants are usually Strings, but can also be primitives, Arrays or Maps.

Rich Java Client Seminar

Constants Example

loginMessage=Welcome back!builtInUsers=admin,usermaxPasswordLength=10adminEnabled=true

key1=value1admin=admin123user=myPasspasswords=key1,admin,user

UserConstants_en.properties

Public interface UserConstants extends Constants {

String loginMessage(); String[] builtInUsers(); int maxPasswordLength(); boolean adminEnabled();

Map<String, String> passwords();{

UserConstants.java

Rich Java Client Seminar

Constants Usage// ...

UserConstants userConstants = GWT.create(UserConstants.class);

String msg = userConstants.loginMessage();String[] users = userConstants.builtInUsers();int passLen = userConstants.maxPasswordLength();boolean enabled = userConstants.adminEnabled();Map<String,String> passwords = userConstants.passwords();

// ...

Rich Java Client Seminar

Annotations Use @Key annotation to provide a property

key different from method name. The default String values are expressed either:

– A default properties file (no locale suffix)– A @DefaultXXX annotation:

• String - @DefaultStringValue• String[] - @DefaultStringArrayValue• int - @DefaultIntValue• float - @DefaultFloatValue• double - @DefaultDoubleValue• boolean - @DefaultBooleanValue• Map - @DefaultStringMapValue

Rich Java Client Seminar

Constants Example

...passLength=15...

UserConstants_he_IL.properties

public interface UserConstants extends Constants {@DefaultStringValue("Welcome!")String loginMessage();

@DefaultStringArrayValue({"admin", "user"})String[] builtInUsers();

@Key("passLength")int minPasswordLength();

{

Rich Java Client Seminar

ConstantsWithLookup ConstantsWithLookup – an extension of

Constants. Adds ability to look up constants at runtime:

Received parameter is a method name.

UserConstants userConstants = GWT.create(UserConstants.class);String msg = userConstants.getString("loginMessage");

Rich Java Client Seminar

Messages Messages interface – similar to Constants

interface. Used for parameterized string messages. Follows same rules and conventions as

Constants interface, except:– Methods can receive parameters.– Methods return only String.

Rich Java Client Seminar

Messages Example

MyMessages messages = GWT.create(MyMessages.class);String msg = messages.likeFruitMessage("Yoav", "Apple");

public interface MyMessages extends Messages {String welcome(String name);String likeFruitMessage(String name, String fruit);

{

MyMessages Interface

MyMessages.propertieslikeFruitMessage=Hello, {0}, your favorite fruit is {1}welcome=Welcome {0}

Usage

Rich Java Client Seminar

Annotations @DefaultLocale – Specifies the default Locale.

@DefaultMessage - Default text to be used if no translation is found.

@Optional - Indicates the parameter is optional.

@DefaultLocale("en_US")public interface MyMessages extends Messages { ... }

@DefaultMessage("Welcome, {0}!") String welcome();

String displayName(String firstName, @Optional String lastName, String id);

Rich Java Client Seminar

Annotations – Plural Form @PluralCount - Provides multiple plural forms

based on a count.– The parameter chosen must be of type short or

int.– Available translation values are Locale dependent,

but include at least:• one – passed value is 1.• other – other value passed.

@AlternateMessage – Use to provide default plural messages.

@Offset - Provides an offset to be subtracted from the value before a plural rule is chosen.

Rich Java Client Seminar

Constants Example

rowsSelected={0} items selected.rowsSelected[one]=One item selected.

public interface MyMessages extends Messages {@AlternateMessage({"one", "One row selected"})String rowsSelected(@PluralCount int itemCount);

{

MyMessages.properties

Rich Java Client Seminar

Dynamic String Initialization Very flexible. Applications look up localized strings in the

module's host page. No need to recompile upon adding a new

Locale. Suitable when integrating a GWT application

with an existing server-side localization system.

To learn more see Dictionary interface.

Rich Java Client Seminar

Localizable Interface Most powerful. Allows developers to create localized versions

of custom types. Very advanced and not often used.

Rich Java Client Seminar

Number and Date Formatting GWT does not fully emulates the date and

number formatting classes. Instead it provides:

– com.google.gwt.i18n.client.NumberFormat– com.google.gwt.i18n.client.DateTimeFormat

Rich Java Client Seminar

NumberFormat Number formats:

– NumberFormat.getDecimalFormat() (default: “#,##0.###”)

– NumberFormat.getScientificFormat() (default: “#E0”)

– NumberFormat.getPercentFormat() (default: “#,##0%”)

– NumberFormat.getFormat(format) Commonly used pattern symbols for decimal

formats:

Rich Java Client Seminar

Using Number Formats NumberFormat is used to format() numbers

or parse() strings:NumberFormat fmt = NumberFormat.getDecimalFormat();double value = 12345.6789;String formatted = fmt.format(value);

//Convert a numeric string back into a doublevalue = NumberFormat.getDecimalFormat().parse("12345.6789");

//You can also specify your own pattern for formatting numbersformatted = NumberFormat.getFormat("0000.0000").format(value);

Rich Java Client Seminar

DateFormat Date Formats:–DateTimeFormat.getFormat(redefinedFormatEnumV

alue);e.g. DateTimeFormat.getFormat(PredefinedFormat.DATE_FULL)

–DateTimeFormat.getFormat(stringFormat);e.g. DateTimeFormat.getFormat("dd/MM/yyyy")

Rich Java Client Seminar

DateFormat Pattern Symbols

Rich Java Client Seminar

Bidirectional Widgets Some widgets are Bidirectional (“bidi” in

short). That is, they may have Direction, right-to-left

or left-to-right. GWT uses a special algorithm to automatically

estimate text direction. This is done using a DirectionEstimator and

widgets with this ability implement HasDirectionEstimator. e.g. TextBox, TextArea, Anchor, Label, HTML, ...

To disable (or replace) this behavior use: widget.setDirectionEstimator(false) or widget.setDirectionEstimator(estimatorImpl)

Rich Java Client Seminar

Rich Java Client Seminar

ClientBundle API for bundling multiple UI resources in one

interface. Advantages:

– Work with Java interface & methods, instead of Strings and constants.

• Eliminate mismatches between filenames and constants.

• Easier refactoring and usage detection.

– Support I18N

Rich Java Client Seminar

ClientBundle API for bundling multiple UI resources in one

interface. Advantages

– Consistency checks: Eliminate mismatches between physical filenames and constants in Java code

– Better cache control– I18N + Direction (RTL) support– Highly optimized (Image Sprites & other CSS

Optimizations)– Use constants and evaluation in CSS– And more...

Rich Java Client Seminar

ClientBundle Resource types DataResource

ImageResource TextResource & ExternalTextResource GwtCreateResource CssResource

Rich Java Client Seminar

ClientBundle - DataResource Offers a URL by which the contents of a file

can be retrieved at runtime– Automatically renames files based on their

contents in order to make the resulting URL strongly-cacheable by the browser

interface Resources extends ClientBundle {  Resources INSTANCE = GWT.create(Resources.class);

  @Source("mycursor.cur")  DataResource customCursor();}

// ElsewheresomeDiv.getStyle().setProperty("cursor","url(" + Resources.INSTANCE.customCursor().getUrl() + ")");

Rich Java Client Seminar

ClientBundle - ImageResource ImageResouceinterface Resources extends ClientBundle {  @Source("logo.png")  ImageResource logo();

  @Source("arrow.png")  @ImageOptions(flipRtl = true)  ImageResource pointer();}

Resources resources = GWT.create(Resources.class);Image img = new Image(resources.logo());

Rich Java Client Seminar

ClientBundle - ImageResource @ImageOptions

– flipRtl: The image will be mirrored about its Y-axis when LocaleInfo.isRTL() returns true

– repeatStyle: Used in combination with the @sprite directive to indicate that the image is intended to be tiled

Supported formats– All common web image formats (uses Java’s

ImageIO)– Animated GIF files will not be incorporated into an

image strip

Rich Java Client Seminar

ClientBundle - ImageResource ImageResource available methods:

– getLeft()– getTop()– getHeight()– getWidth()– getUrl()– isAnimated()

ImageResource can be annotated with @ImageOptions which has the following properties– flipRtl– height– repeatStyle (none, horizontal, vertical, both)– width

Rich Java Client Seminar

ClientBundle - ExternalTextResource Provide access to static text content

– TextResource: Interns the text into the compiled JavaScript

– ExternalTextResource: Bundles related text resources into a single file, which is accessed asynchronously

Rich Java Client Seminar

ClientBundle - ExternalTextResourceinterface Resources extends ClientBundle {  Resources INSTANCE = GWT.create(Resources.class);

  @Source("a.txt")  TextResource synchronous();

  @Source("b.txt")  ExternalTextResource asynchronous();}

// Using a TextResourcemyTextArea.setInnerText(Resources.INSTANCE.synchronous().getText());

// Using an ExternalTextResourceResources.INSTANCE.asynchronous().getText(new ResourceCallback<TextResource>() {  public void onError(ResourceException e) { ... }  public void onSuccess(TextResource r) {    myTextArea.setInnerText(r.getText());  }});

Rich Java Client Seminar

ClientBundle - GwtCreateResource

GwtCreateResource Ability to act as a factory of some other (resource) type that is default-instantiable

Rich Java Client Seminar

ClientBundle - GwtCreateResourceinterface Resources extends ClientBundle {  Resources INSTANCE = GWT.create(Resources.class);

  @ClassType(SomeClass.class)  GwtCreateResource<ReturnType> factory();}

// ElsewhereReturnType obj = Resources.INSTANCE.factory().create();

The above is equivalent to:

ReturnType obj = GWT.<ReturnType> create(SomeClass.class);

It allows the consuming classes to be ignorant of the specific class literal passed into GWT.create)(

Rich Java Client Seminar

ClientBundle – CssResource ensureInjected() Before we start working with CssResource, we

should make sure that the contents of the stylesheet have been injected to our instance. We do that by invoking the ensureInjected method:

This method is safe to call multiple times, as subsequent invocations will be a no-op

// Inject the contents of the CSS fileMyResources.INSTANCE.css().ensureInjected();

Rich Java Client Seminar

ClientBundle – CssResource Constants Give us the possibility to define constants in our

CSS and the reuse them We can use them for:

– Property values (1px, 100%, etc.)– CSS classes (.myClass { … })

Rich Java Client Seminar

ClientBundle – CssResource ConstantsOur CSS:

Our CssResource:

Calling small() would return the value 1(the return type is int)

@def small 1px;@def black #000;border: small solid black;

interface MyResources extends CssResource {  int small();}

Rich Java Client Seminar

ClientBundle – CssResource ConstantsOur CSS:

Our CssResource:

Calling small() returns "1px"Calling black() returns "#000"

@def small 1px;@def black #000;border: small solid black;

interface MyResources extends CssResource {  String small();  String black();}

Rich Java Client Seminar

@def myIdent 10px;.myIdent {  ...}

interface MyResources extends CssResource {  String myIdent();

  @ClassName("myIdent")  String myIdentClass();}

ClientBundle – CssResource ConstantsWhat happens if we have a constant with the same name of a CSS class?

returns @def value "10px"

returns the obfuscated class name for .myIdent

Rich Java Client Seminar

ClientBundle – CssResource Runtime Substitution Provides support for evaluating static methods

when the stylesheet is injected. Allows us to substitute in our CSS values that

come from our Java written code.@eval userBackground com.module.UserPreferences.getUserBackground();div {  background: userBackground;}

Rich Java Client Seminar

ClientBundle – CssResource Value function The value function takes 2 parameters:– A sequence of dot-separated identifiers– An optional suffix

The function evaluates the dot-separated expression using the interface passed to GWT.create() as the root namespace

.myDiv {  offset-left: value('imageResource.getWidth', 'px');}

Rich Java Client Seminar

ClientBundle – CssResource Value function The value function may also be combined with

@def@def SPRITE_WIDTH value('imageResource.getWidth', 'px')

.selector {  width: SPRITE_WIDTH;}

Rich Java Client Seminar

ClientBundle – CssResource Literal function Some user agents make use of property values

that do not conform to the CSS grammar. The literal() function exists to allow these non-standard property values to be used.

Note that it is necessary to escape the backslash (\) and double-quote (") characters.

div-with-literal {  top: literal("expression(document.compatMode==\"CSS1Compat\" ?

documentElement.scrollTop : document.body.scrollTop \\ 2)");}

Rich Java Client Seminar

ClientBundle – CssResource Conditional CSS Allows is to write if blocks on our CSS

evaluating:– Static context (like @eval)– Compile time evaluation (like the value function)

We can decide which CSS block to use if the user.agent (browser) is IE or Firefox, if the locale is en or il, if we are in one skin of our application or other one, etc.

Rich Java Client Seminar

ClientBundle – CssResource Conditional CSS/* Runtime evaluation in a static context */

@if (com.module.Foo.staticBooleanFunction()) {  ... css rules ...}

/* Compile-time evaluation */@if <deferred-binding-property> <space-separated list of values> {  ... css rules ...}@if user.agent safari gecko1_8 { ... }@if locale en { ... }

Rich Java Client Seminar

ClientBundle – CssResource Conditional CSS Negation and chaining are supported

/* Negation is supported */@if !user.agent ie6 opera {  ...}

/* Chaining is also supported */@if (true) {} @elif (false) {} @else {}

Rich Java Client Seminar

ClientBundle – CssResource Image Sprites For every image that we include in our

application, there is minimum a request to the server

Sprite combines several images in one single image and with the use of CSS we load a specific region of it

Sprite decreases in a great amount the number of request to the web server

GWT does all the work for us: combines our images and display the apropiate area of the sprite

Rich Java Client Seminar

ClientBundle – CssResource Image Sprites @sprite on our CSS:

@sprite .mySpriteClass {gwt-image: "imageAccessor"; other: property;}

=> generates =>

  .mySpriteClass {    background-image: url(gen.png);    clip: ...;    width: 27px;    height: 42px;    other: property;  }

Rich Java Client Seminar

ClientBundle – CssResource Image Spritesinterface MyCssResource extends CssResource {

  String mySpriteClass();}

class MyResources extends ClientBundle {  @Source("my.css")  MyCssResource css();

  @Source("some.png")  ImageResource imageAccessor();

  @Source("some.png")  @ImageOptions(repeatStyle=RepeatStyle.Horizontal)  ImageResource repeatingImage();}

Rich Java Client Seminar

ClientBundle – CssResource References to Data Resources GWT allows us to reference to the url of a

DataResource directly from the CSS. As we saw, DataResource give us a convenient

and cache friendly way of access resources. We can use those DataResources from our own CSS

Rich Java Client Seminar

ClientBundle – CssResource References to Data Resources Suppose we declare a DataResource which source is

myCursor.cur and we obtain it calling the fancyCursorResource method on our MyResource interface

We also declare our CssResource

interface MyResources extends ClientBundle {  @Source("myCursor.cur")  DataResource fancyCursorResource();

  @Source("my.css")  CssResource css();}

Rich Java Client Seminar

ClientBundle – CssResource References to Data Resources Now on our CSS we can reference directly to

that DataResource and use it as the URL of an element/* @url <constant name> <DataResource method name> */@url myCursorUrl fancyCursorResource;

.myClass {  cursor: myCursorUrl, pointer;}

Rich Java Client Seminar

ClientBundle – CssResource RTL support CssResource supports automatic

transformations of CSS code into a right-to-left variant at compile time.

Very important for right to left languages (e.g. Hebrew)

The transformations depends on the value of com.google.gwt.i18n.client.LocaleInfo.getCurrentLocale().isRTL()

Rich Java Client Seminar

ClientBundle – CssResource RTL support Some of the transformations are:– The left and right properties are flipped– Any properties that have values left or right are

flipped• clear• float• text-align• page-break-before• page-break-after

Rich Java Client Seminar

ClientBundle – CssResource RTL support– The background/background-position property is

flipped. Attachments expressed in percentage points are mirrored: 40% becomes 60%

– The following four-valued properties are flipped:1px 2px 3px 4px becomes 1px 4px 3px 2px

• margin• padding• border-color• border-style• border-width

Rich Java Client Seminar

ClientBundle – CssResource RTL support– Any xyz-right or xzy-right-abc property is flipped

to xzy-left or xzy-left-abc– The direction property on a body selector will be

flipped from ltr to rtl; on any other selectors, the direction property is unchanged

– When the cursor property has an resize value, it will be flipped: ne-resize becomes nw-resize

Rich Java Client Seminar

ClientBundle – CssResource RTL support Sections of CSS can be exempted from

automatic flipping by enclosing it in a @noflip block:@noflip {

  .selector {    left: 10;  }}

Rich Java Client Seminar

ClientBundle – CssResource RTL support ImageResources can be automatically flipped in

RTL contexts via the use of the @ImageOptions annotation:

@Source("icon128.png")@ImageOptions(flipRtl = true)ImageResource logo();

Rich Java Client Seminar

ClientBundle – CssResource Selector obfuscation What happens if we have two selectors (e.g.

two CSS classes) with the same name? The second one loaded will override the first one.

What if we misspelled the name of a selector?, is there any check that when we apply a class to an element, that class exists on the CSS? The answer is no.

Rich Java Client Seminar

ClientBundle – CssResource Selector obfuscation For dealing with those situations, GWT

obfuscates (changes) the name of the selectors on the CSS.

That way, if we wrote myCssClass somewhere and the myCssClass somewhere else, GWT is going to change those class names to something different from each other and avoid the style override problem.

Also, when we’ll write out CssResource, GWT is going to check that the CSS selector we are referring to, does exist on out stylesheet.

Rich Java Client Seminar

ClientBundle – CssResource Selector obfuscationjava:

    class Resources {      MyCSSResource myCSSResource();    }    class MyCSSResource extends CSSResource {      Sprite mySpriteClass();      String someOtherClass();      String hookClass();    }    myWidget.addStyleName(resource.mySpriteClass());

css:    @sprite mySpriteClass mySpriteImage;    .someOtherClass {      /* ... */    }    .hookClass{} /* Empty and stripped, but left for future expansion */

Rich Java Client Seminar

ClientBundle – CssResource Selector obfuscation - @external In many cases, newly-developed CSS will need

to be combined with external or legacy CSS. The @external at-rule can be used to suppress selector obfuscation while still allowing programmatic access to the selector name.@external legacySelector;.legacySelector { .... }.obfuscatedSelector { .... }

Rich Java Client Seminar

ClientBundle – CssResource Selector obfuscation - @NotScrict In the normal case, any class selectors that do

not match String accessor functions is an error. This behavior can be disabled by adding a @NotStrict annotation to the CSS accessor method. Enabling @NotStrict behavior is only recommended for applications that are transitioning from external CSS files to CssResource

Rich Java Client Seminar

ClientBundle – CssResource Selector obfuscation - @NotScrict

interface MyCssResource extends CssResource {  String foo();}

interface Resources {  @Source("my.css")  @CssResource.NotStrict  MyCssResource css();}

/* This is ok */.foo {}

/* This would normally generate a compile error in strict mode */.other {}

Rich Java Client Seminar

ClientBundle – CssResource Selector obfuscation – Imported Scopes The Java type system can be somewhat

ambiguous when it comes to multiple inheritance of interfaces that define methods with identical signatures, although there exist a number of cases where it is necessary to refer to multiple, unrelated CssResource types. Consider the case of a Tree that contains Checkboxes.

Rich Java Client Seminar

ClientBundle – CssResource Selector obfuscation – Imported Scopes@ImportedWithPrefix("tree")

interface TreeCss extends CssResource {  String widget();}

@ImportedWithPrefix("checkbox")interface CbCss extends CssResource {  String widget();}

interface MyCss extends CssResource {  String other();}

interface Resources extends ClientBundle {  @Import({TreeCss.class, CbCss.class})  MyCss css();}

Rich Java Client Seminar

ClientBundle – CssResource Selector obfuscation – Imported Scopes/* Now we can write a descendant selector using the

prefixes defined on the CssResource types */.tree-widget .checkbox-widget {  color: red;}

.other {  something: else;}

Rich Java Client Seminar

ClientBundle – CssResource Optimizations The CssResource also applies several

optimizations to our CSS code. These optimizations relates to:– Reduce the amount of bytes to represent the CSS

code– Rules merging when they are applied to the same

selector– Property merging when two or more properties

have the same rules

Rich Java Client Seminar

ClientBundle – CssResource Optimizations - Basic minification Removal of comments, unnecessary

whitespace, and empty rules

would be transformed into

.div {  /* This is the default background color */  background: blue;}.empty {}

.div{background:blue;}

Rich Java Client Seminar

ClientBundle – CssResource Optimizations – Selector merging Rules with identical selectors can be merged

together

becomes

.div {prop: value;}

.div {foo: bar;}

.div {prop:value;foo:bar;}

Rich Java Client Seminar

ClientBundle – CssResource Optimizations – Property merging Rules with identical properties can be merged

together

can be transformed into

.a {background: blue;}

.b {background: blue;}

.a,.b{background:blue;}

Rich Java Client Seminar

CssResource Constants

– @def NAME replacement-expression Runtime substitution

– @eval NAME Java-expression Value function

– att: value('imageResource.getWidth', 'px');

Rich Java Client Seminar

Rich Java Client Seminar

UiBinder A framework for building widget and DOM

structures from XML.– Introduced with GWT 2.0.– Build your applications as HTML pages with

sprinkled GWT widgets.

Rich Java Client Seminar

Elements xmlns:ui='urn:ui:com.google.gwt.uibinder' ui:UiBinder - Root

ui:style – Add CSS ui:with – Add Reference (i.e: ClientBundle) ui:msg – Translated message ui:ph – Translator place holder

Rich Java Client Seminar

Attributes xmlns:ui='urn:ui:com.google.gwt.uibinder' ui:field

ui:ph

ui:defaultLocale ui:generateFilename ui:generateFormat ui:generateKeys ui:generateLocales

Rich Java Client Seminar

Annotations @UiField(provided=false) @UiConstructor @UiFactory @UiTemplate

Rich Java Client Seminar

Rich Java Client Seminar

Security There is much to say about web applications

security. Web applications are vulnerable to many

types of attacks: Brute Force, Phishing, MITM, Injections, CSRF, DoS, XSS,...

A subject for an entire course...

Attacks most relevant to JavaScript are XSS and CSRF caused by Misplaced Trust.

Unfortunately, those are also the most common attacks...

Rich Java Client Seminar

XSS: Cross-Site Scripting Attack Description:

– Attacker causes target website to include a malicious script in the page presented to the victim.

– If successful, the attacker can then lunch other attacks. e.g. CSRF, still users cookies, login as the user, still credentials etc.

Mitigation:– Never trust the user.– Validate input.

Rich Java Client Seminar

XSS Mitigation in GWT» Constrain client, allow only the minimum. Validate all input on the server-side. Limit fields length using field.setMaxLength(). Use IntegerBox, DoubleBox or LongBox for

number fields. Use SafeHtml.

Rich Java Client Seminar

Safe HTML SafeHtml = API and a set of utilities used for

escaping and sanitizing HTML. SafeHtml object – an object representing

HTML that is guaranteed to be safe.– Should be passed instead of plain string.– Is created by using SafeHtml utilities.

Many widgets receive SafeHtml objects:

– e.g: instead of

– Use:

public HTML(String html) { ... }

public HTML(SafeHtml html) { ... }

Rich Java Client Seminar

SafeHTML Utilities SafeHtmlUtils SafeHtmlBuilder SimpleHtmlSanitizer SafeHtmlTemplates

Rich Java Client Seminar

SafeHtmlUtils Methods Creating SafeHtml instances: fromString(string) – returns SafeHtml of escaped string.– To be used on user input and untrusted strings.

fromTrustedString(string) - returns SafeHtml of given string.– To be used only on trusted strings (e.g. numbers,

constants) fromSafeConstant(string) - returns SafeHtml of given string.

– Extended version of fromTrustedString()– Also asserts that given HTML is “complete”,

meaning: all tags are closed (e.g. “<div” is invalid).– This assertion is executed only in tests and in

Development Mode.

Rich Java Client Seminar

ExamplesSafe HTML Unsafe HTMLnew HTML(fromString(name)) new HTML(name)new HTML(fromSafeConstant( "<b>Name:</b>"))

new HTML("<b>Name:</b>")

Rich Java Client Seminar

SafeHtmlUtils Methods Escaping Methods htmlEscape(string) – returns escaped string.– Escaped chars: & < > “ ‘

htmlEscapeAllowEntities(string)– Smarter version of htmlEscape.– Does not double-escape HTML-entities (e.g. &nbsp;

&gt;)

Rich Java Client Seminar

SafeHtmlBuilder A builder that facilitates the building up of

XSS-safe HTML from text snippets.

Rich Java Client Seminar

SimpleHtmlSanitizer A simple and relatively inexpensive HTML

sanitizer. Accepts the subset of HTML consisting of the

following attribute-free tags: – <b>, <em>, <i> – <h1>, <h2>, <h3>, <h4>, <h5>, <h6> – <ul>, <ol>. <li> – <hr>

Usage:

SimpleHtmlSanitizer.sanitizeHtml(html)

Rich Java Client Seminar

SafeHtmlTemplates Facilitate the creation of SafeHtml instances

containing more complex HTML markup. Allows creation of SafeHTML instances using

templates. Usage:

1. Create an interface which extends SafeHtmlTemplates.

2. Add methods which return SafeHtml .3. Annotate methods with @Template annotation

and define the HTML template.4. Create proxy of the interface using GWT.create()5. Invoke the template methods.

Rich Java Client Seminar

SafeHtmlTemplates Examplepublic interface MyTemplates extends SafeHtmlTemplates { @Template("<span class=\"{3}\">{0}: <a href=\"{1}\">{2}</a></span>") SafeHtml messageWithLink(SafeHtml message, String url, String linkText, String style);{

private static final MyTemplates TEMPLATES = GWT.create(MyTemplates.class);

public void useTemplate(...) { HTML messageWithLinkInlineHTML = new InlineHTML( TEMPLATES.messageWithLink(message, url, linkText, style));{

Rich Java Client Seminar

Same Origin Policy - SOP To minimize the damage caused by cross-site attacks

all modern browsers implement SOP - Same Origin Policy.

Security policy that restricts all JavaScript activities to the current domain, port and protocol.

This means you cannot send Ajax requested to a different domain.– e.g: http://www.hp.com/gwtApp cannot send Ajax

requests to http://server2.hp.com/services/

Rich Java Client Seminar

Rich Java Client Seminar

History Done by keeping track of application's

"internal state" in the URL fragment identifier– Updating the fragment doesn't typically cause the

page to be reloaded.– Provides good feedback to the user.– Application’s state is bookmarkable.

Rich Java Client Seminar

History Add this to host page.

Use History:– History.newItem(token)– History.addValueChangeHandler()

* Since GWT 2.1 there’s also a higher abstraction as part of MVP.

<iframe src=“javascript:'‘”id=“__gwt_historyFrame” tabIndex=“-1”style=“width:0;height:0;border:0”></iframe>

Rich Java Client Seminar

Rich Java Client Seminar

GWT Best Practices Inspired by Ray Ryan's

Best Practices For Architecting Your GWT App session at Google I/O 2009

Highlights:– Embrace Asynchrony.– Command (dispatcher) pattern.– Decoupling, decoupling, decoupling.– MVP (Model/View/Presenter) pattern.– Dependency Injection.– Event Bus.– Support history from the start (using

PlaceManager).

Rich Java Client Seminar

Code Splitting Enterprise applications can have lots of client-

side code.– This means big JavaScript files to download and

evaluate.– And this means long startup time.

Code splitting allows us to *easily* spilt our code into several JavaScript files.– Main startup files can now be very small.– Other JavaScript files are lazily loaded when

needed.

GWT.runAsync(new RunAsyncCallback() {@Overridepublic void onSuccess() { /* code */ {

});

Rich Java Client Seminar

Event Bus A global bus which is aware of all events that

should be shared between different panels, and fires them to the right components.

Eases decoupling by allowing objects to interact without having direct dependencies upon one another.

There will typically be one EventBus per application

Pattern highlights:– Instead of referencing one another, widgets

communicate though the EventBus.– This is done by firing events to the event bus and

listening to fired events.

Rich Java Client Seminar

Event Bus - Motivation

Rich Java Client Seminar

MVP The model is an interface defining the data to

be displayed The view is an interface that displays data (the

model) and routes user commands (events) to the presenter

The presenter retrieves data from repositories (the model), persists it, and formats it for display - assumes the functionality of the "middle-man"

Model-View-Presenter is a derivative of the Model-View-Controller design pattern`

Rich Java Client Seminar

MVP Motivation:

– Facilitate automated unit testing– Improve the separation of concerns: presentation

& logic.

Many 3rd party libraries implementing these concepts has spawned.

GWT 2.1 added a built-in support for MVP, activities and places.– Joining the existing event bus support.

Rich Java Client Seminar

MVP Diagram

Rich Java Client Seminar

GWT’s Implementation - Activities Activities are analogous to a presenter in

MVP terminology. Activities are designed to be disposable. Can automatically display a warning

confirmation when the Activity is about to be stopped.

An Activity needs a corresponding Place.

Rich Java Client Seminar

Places A Java object representing a particular state of

the UI. Can be converted to and from a URL history

token. A Place must have an associated

PlaceTokenizer which knows how to serialize the Place's state to a URL token that consists of the Place's simple class name (like "HelloPlace") followed by a colon (:) and the token returned by the PlaceTokenizer

Rich Java Client Seminar

PlaceManager The one that takes care of History

management The PlaceManager works as an intermediary

between the GWT History API and Activity (Presenter)

The PlaceManager sets up event listener relationships to synchronize between History and Places.

Rich Java Client Seminar

GWT 2.1 Place Managment In GWT Place Management is handled by

several components:– PlaceController - Used to navigate between

application places. Responsible for firing PlaceChangeRequestEvent and PlaceChangeEvent .

– ActivityMapper – Maps places to activities.– ActivityManager - Manages Activity objects that

should be kicked off in response to PlaceChangeEvent events.

– PlaceHistoryMapper – Maps history tokens to places.

– PlaceHistoryHandler - Monitors PlaceChangeEvents and History events and keep them in sync.

Rich Java Client Seminar

MVP Viewpublic interface HelloView extends IsWidget {void setName(String helloName);void setPresenter(Presenter listener);

public interface Presenter {void goTo(Place place);

}}

Rich Java Client Seminar

MVP View Implementationpublic class HelloViewImpl extends Composite implements HelloView { private static HelloViewImplUiBinder uiBinder = GWT.create(HelloViewImplUiBinder.class);

interface HelloViewImplUiBinder extends UiBinder<Widget, HelloViewImpl> { }

@UiField Label fName; @UiField Anchor goodbyeLink; private Presenter presenter; private String name;

public HelloViewImpl() { initWidget(uiBinder.createAndBindUi(this)); }

@Override public void setName(String name) { this.name = name; fName.setText(name); }

@UiHandler("goodbyeLink") void onClickGoodbye(ClickEvent e) { presenter.goTo(new GoodbyePlace(name)); }

@Override public void setPresenter(Presenter listener) { this.listener = listener; }}

Rich Java Client Seminar

MVP Binder template<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent"><ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"

xmlns:g="urn:import:com.google.gwt.user.client.ui"><ui:style>

.important {font-weight: bold;}</ui:style><g:HTMLPanel> Hello, <g:Label styleName="{style.important}" ui:field="fName" /> <g:Anchor ui:field="goodbyeLink" text="Say good-bye"></g:Anchor></g:HTMLPanel>

</ui:UiBinder>

Rich Java Client Seminar

MVP Activity/Presenterpublic class HelloActivity extends AbstractActivity implements HelloView.Presenter {

// Used to obtain views, eventBus, placeControllerprivate ClientFactory clientFactory;private String name;

public HelloActivity(HelloPlace place, ClientFactory clientFactory) {this.name = place.getHelloName();this.clientFactory = clientFactory;

}

// Invoked by the ActivityManager to start a new Activity@Overridepublic void start(AcceptsOneWidget containerWidget, EventBus eventBus) {

HelloView helloView = clientFactory.getHelloView();helloView.setName(name);helloView.setPresenter(this);containerWidget.setWidget(helloView.asWidget());

}

// Navigate to a new Place in the browserpublic void goTo(Place place) {

clientFactory.getPlaceController().goTo(place);}

}

Rich Java Client Seminar

Dispatcher Pattern Replaces simple GWT RPC. It is a GWT implementation of the command

pattern that wraps the GWT-RPC mechanism. Instead of invoking Service methods we send

Actions (i.e. commands) to a dispatcher. A dispatcher dispatches each Action to the

server and invoke the appropriate action handler.

Advantages:– Allows command batching.– Allows client-side caching of responses..

Rich Java Client Seminar

Dependency Injection All over our code we need dependencies:

– The database driver to execute a query– The instance of a service to do something on our

controller– Some singleton that we want to have access to– Etc.

We used to go and get all these instance from our class, which created a tight couple between our code and some few classes like, for instance, a GWT service we want to invoke from a controller class

Rich Java Client Seminar

Dependency Injection What if we want to change the

implementation of a GWT service in our application? We’ll need to change every single class that makes use of it.

The solution: Inversion of Control

Rich Java Client Seminar

Dependency Injection Inversion of Control Dependency Injection is a design pattern which makes

use of an Inversion of Control container that injects our code with what we need on a specific class without us knowing how to get it.

That way, a controller in our MVC defines that it needs a GWT service but not which one. The Inversion of Control container injects the appropriate service implementation.

If we want to change the service implementation, we just change the configuration of our IOC container.

Rich Java Client Seminar

GIN (GWT INjection)

GWT’s Inversion of Control container

Rich Java Client Seminar

GIN GIN (GWT INjection) brings automatic

dependency injection to GWT client-side code. GIN is built on top of Guice and uses (a subset

of) Guice's binding language One of the most important differences

between Guice and GIN is that GIN can only inject dependencies trough the constructor, not setter methods

Rich Java Client Seminar

GIN Inheriting the GIN module The first step is to inherit the GIN module in our

application<module>  ...  <inherits name="com.google.gwt.inject.Inject"/>  ...</module>

Rich Java Client Seminar

GIN Defining the Ginjector GIN’s injector looks very similar to client

bundles and messages. You simply create a method for each object type you want to create

public interface MyWidgetGinjector extends Ginjector {  MyWidgetMainPanel getMainPanel();}

Rich Java Client Seminar

GIN Defining the Ginjector You only need to create injector methods for

classes that you would directly access in your top-level initialization code, such as the UI classes to install in your RootPanel.

If a class is used by one of those defined main classes, GIN will automatically inject it, it will be attached to the container so there is no need to declare it on the injector.

Rich Java Client Seminar

GIN Binding declaration Bindings are declared the same way as Guice,

using a module. The module class looks almost exactly like it would in regular Guice although we use GinModule and AbstractGinModule instead of Module and AbstractModule.public class MyWidgetClientModule extends AbstractGinModule {  protected void configure() {    bind(MyWidgetMainPanel.class).in(Singleton.class);    bind(MyRemoteService.class).toProvider(MyRemoteServiceProvider.class);  }}

Rich Java Client Seminar

GIN Module and Injector association Add the GinModules annotation to your

Ginjector, specifying the module(s) needed to configure the application@GinModules(MyWidgetClientModule.class)public interface MyWidgetGinjector extends Ginjector {  MyWidgetMainPanel getMainPanel();}

Rich Java Client Seminar

GIN Injector creation To create the injector instance, use the

standard GWT.create() call. This can be done during static initializationpublic class MyWidget implements EntryPoint {  private final MyWidgetGinjector injector = GWT.create(MyWidgetGinjector.class);

  public void onModuleLoad() {    MyWidgetMainPanel mainPanel = injector.getMainPanel();    RootPanel.get().add(mainPanel);  }

}

Rich Java Client Seminar

GIN Injection After you declared your bindings on your

modules, you can inject dependencies on your constructors’ objects using @Inject

public class MyWidget {

  @Inject  public MyWidget(MyRemoteService service) {  }}

Rich Java Client Seminar

Rich Java Client Seminar

Logging Logger

– use java.util.logging.Logger Handlers

– SystemLogHandler - Logs to stdout.– DevelopmentModeLogHandler – Logs to GWT.log.– ConsoleLogHandler - Logs to the javascript

console.– FirebugLogHandler - Logs to Firebug.– PopupLogHandler - Logs to the popup.– HasWidgetsLogHandler – can be used with any

container.– SimpleRemoteLogHandler - Discussed below, in

the Remote Logging section

Rich Java Client Seminar

GWT Unit Testing GWT provides integration with JUnit

– Both in dev mode and production mode webAppCreator specifies ant targets

designated for testing in build.xml, once –junit option is specified– javac.tests: Compiles test code– test.dev: Run development mode tests– test.prod: Run production mode tests

Rich Java Client Seminar

GWT Unit Testing Inherit the JUnit Module

GWT JUnit tests extend GWTTestCase– Directly or indirectly

Implement the abstract method (getModuleName) that returns the GWT module name

<inherits name="com.google.gwt.junit.JUnit"/>

Rich Java Client Seminar

GWT Unit Testing 1 /** 2 * GWT JUnit tests must extend GWTTestCase. 3 */ 4 public class SimplestPossibleTest extends GWTTestCase { 5 6 /** 7 * Must refer to a valid module that sources this class. 8 */ 9 public String getModuleName() { 10 return "com.alphacsp.gwt.Course"; 11 } 12 13 /** 14 * Add as many tests as you like. 15 */ 16 public void testSimple() { 17 assertTrue(true); 18 } 19 20 } 21

Rich Java Client Seminar

Running unit tests Using your IDE TestRunner From command line, using Ant Manual Mode

– More about it later

Rich Java Client Seminar

JUnitShell The main class in test infrastructure To control aspects of test execution, pass

arguments to this class– By defining a system property gwt.args

To run tests in production mode, declare -Dgwt.args="-prod“– First compile to JS, than run tests

To get a full list of supported options, declare -Dgwt.args="-help"

Rich Java Client Seminar

JUnitShell

Rich Java Client Seminar

Running unit tests in manual mode Runs unit tests manually on a browser

– Using JUnitShell Instead of running the test, prints a URL and

waits for browser connection Use: -Dgwt.args="-runStyle Manual"

Rich Java Client Seminar

Running unit tests in manual mode Point the browser to the specified URL In browser, you may be prompted by Google

Web Toolkit Developer Plugin

Rich Java Client Seminar

Server side testing Server side code runs as native Java in a JVM It is not necessary to run tests of server side

code using GWTTestCase Use JUnit TestCase and or other test

framework directly when writing tests for your application's server side code

Rich Java Client Seminar

» A bunch of new specs» WHATWG, since 2004» W3C, picked up at 2007

» Plus additional specs» Contains new APIs

» Empower us» Ease development

HTML 5Web Hypertext Application Technology Working Group

World Wide Web Consortium

Rich Java Client Seminar

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Media

HTML Markup

Semantics Tags

Link Relations

ARIA

Cache

Forms & Applications

Device

MetersMenu

Editable ContentFields Validations

Rich Java Client Seminar

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Media

HTML Markup

Semantics Tags

Link Relations

ARIA

Cache

Forms & Applications

Device

MetersMenu

Editable ContentFields Validations

Vector Graphics Markup + CSS + Effects + Transitions + Animations + JavaScript Events + Design Tools

Rich Java Client Seminar

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Media

HTML Markup

Semantics Tags

Link Relations

ARIA

Cache

Forms & Applications

Device

MetersMenu

Fields Validations

<menu type=“toolbar”> <command type=“command”>Click Me!</command></menu>

Editable Content

Rich Java Client Seminar

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Media

HTML Markup

Semantics Tags

Link Relations

ARIA

Cache

Forms & Applications

Device

MetersMenu

Fields Validations

<meter min="0" max="100" low="40" high="90" optimum="100" value=“75“/>

<progress value="75" max="100“/>

Editable Content

Rich Java Client Seminar

Forms & Applications

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Device

Media

HTML Markup

Semantics TagsMeters

Menu

Link Relations

ARIA

Editable Content CacheFields

<input type=“date” min=“...” max=“...” /><input type=“range” min=“...” max=“...” /><input type=“number” step=“1” min=“...” max=“...” /><input type=“search” results=“10” placeholder=“Search...” />

Validations

Rich Java Client Seminar

Forms & Applications

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Device

Media

HTML Markup

Semantics TagsMeters

Menu

Link Relations

ARIA

Editable Content CacheFields Validations

HTML<input type=“text” required /><input type=“email” value=“yoava@alphacsp.com” /><input type=“number” step=“1” min=“1” max=“10” /><input type=“date” min="2010-12-16" max="2011-12-16"/><input type=“tel“ pattern=“\d{3}-\d{7}” />

CSSinput:invalid { outline: solid 3px red; }

Rich Java Client Seminar

Forms & Applications

Device

MetersMenu

Fields Validations

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Media

HTML Markup

Semantics Tags

Link Relations

ARIA

Cache

HTML<html manifest="cache.manifest">

Cache Manifest

CACHE MANIFEST

# version 1

CACHE:/html5/src/logic.js/html5/src/style.css/html5/src/background.png

Editable Content

Rich Java Client Seminar

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Media

HTML Markup

Semantics Tags

Link Relations

ARIA

Cache

<div itemscope itemtype="http://data-vocabulary.org/Person"> My name is <span itemprop="name">Yoav</span> aka <span itemprop="nickname">Aharoni</span>. </div>

Forms & Applications

Device

MetersMenu

Editable ContentFields Validations

Rich Java Client Seminar

Forms & Applications

Device

MetersMenu

Editable ContentFields Validations

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Media

HTML Markup

Semantics Tags

Link Relations

ARIA

Cache

HMTL<div id=“me” data-id=“012" data-name=“Yoav“ data-user=“yoava"></div>JavaScriptdocument.getElementById(‘me’).dataset[‘name’]

Rich Java Client Seminar

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Media

HTML Markup

Semantics Tags

Link Relations

ARIA

Cache

Forms & Applications

Device

MetersMenu

Editable ContentFields Validations

<header> <hgroup> <h1/> <h2/> </hgroup></header>

... <section/> ... <article/> ...

... <nav/> ... <aside/> ...

... <figure/> ... <figcaption/> ...

... <footer> ...

<time datetime=“2010-12-16“/>

Rich Java Client Seminar

Semantics & Data

HTML5 – New Features

SVGMicroData

VideoAudio Data Att.

Media

HTML Markup

Semantics Tags

Link Relations

ARIA

Cache

Forms & Applications

Device

MetersMenu

Editable ContentFields Validations

Rich Java Client Seminar

HTML5 – New Features

Transitions

CSS 3.0

Fonts

TransformsColor

Border

Image

Radius

Shadow

Background

Origin

Size

Clip

Multiple

Colors

Color UIText

RGBA

HSLA

Opacity

HSL

Outline

Box SizingNav

Resize Overflow

Shadow Word Wrap

Columns

Media Queries

3D

Selectors

Rich Java Client Seminar

HTML5 – New Features

Transitions

CSS 3.0

Fonts

TransformsColor

Border

Image

Radius

Shadow

Background

Origin

Size

Clip

Multiple

Colors

Color UIText

RGBA

HSLA

Opacity

HSL

Outline

Box SizingNav

Resize Overflow

Shadow Word Wrap

Columns

Media Queries

3D

Selectors

transform: rotate(7deg); transform: scale(0.5);transform: skew(-25deg);

Rich Java Client Seminar

HTML5 – New Features

Transitions

CSS 3.0

Fonts

TransformsColor

Border

Image

Radius

Shadow

Background

Origin

Size

Clip

Multiple

Colors

Color UIText

RGBA

HSLA

Opacity

HSL

Outline

Box SizingNav

Resize Overflow

Shadow Word Wrap

Columns

Media Queries

3D

Selectors

perspective: 600;perspective-origin: 25% 75%;transform: perspective(600) rotateZ(90deg); translateZ(z); scaleZ(z); translate3d(x,y,z) scale3d(x,y,z)

Rich Java Client Seminar

HTML5 – New Features

Transitions

CSS 3.0

Fonts

TransformsColor

Border

Image

Radius

Shadow

Background

Origin

Size

Clip

Multiple

Colors

Color UIText

RGBA

HSLA

Opacity

HSL

Outline

Box SizingNav

Resize Overflow

Shadow Word Wrap

Columns

Media Queries

3D

Selectors

transition-property: color, left | all;transition-duration: 2s;transition-timing-function: ease | linear | ease-in | ease-out | ease-in-out;

Rich Java Client Seminar

HTML5 – New Features

Transitions

CSS 3.0

Fonts

TransformsColor

Border

Image

Radius

Shadow

Background

Origin

Size

Clip

Multiple

Colors

Color UIText

RGBA

HSLA

Opacity

HSL

Outline

Box SizingNav

Resize Overflow

Shadow Word Wrap

Columns

Media Queries

3D

Selectors

@font-face { font-family: 'LeagueGothic'; src: url(LeagueGothic.otf);}

Rich Java Client Seminar

HTML5 – New Features

Transitions

CSS 3.0

Fonts

TransformsColor

Border

Image

Radius

Shadow

Background

Origin

Size

Clip

Multiple

Colors

Color UIText

RGBA

HSLA

Opacity

HSL

Outline

Box SizingNav

Resize Overflow

Shadow Word Wrap

Columns

Media Queries

3D

Selectors

text-overflow: ellipsis;text-overflow: ellipsis-word;

Lorem ipsum dolor sit amet, consec

Lorem ipsum dolor sit…

Rich Java Client Seminar

HTML5 – New Features

Transitions

CSS 3.0

Fonts

TransformsColor

Border

Image

Radius

Shadow

Background

Origin

Size

Clip

Multiple

Colors

Color UIText

RGBA

HSLA

Opacity

HSL

Outline

Box SizingNav

Resize Overflow

Shadow Word Wrap

Columns

Media Queries

3D

Selectors

tr:nth-child(odd) { ... }tr:nth-child(even) { ... }tr:nth-child(3n+1) { ... }div:nth-child(2n+1) { ... }div[att=value] { ... }p:not(.class) { ... }h2 ~ p { ... }input:empty { ... }input:enabled { ... }input:enabled { ... }

Rich Java Client Seminar

HTML5 – New Features

Transitions

CSS 3.0

Fonts

TransformsColor

Border

Image

Radius

Shadow

Background

Origin

Size

Clip

Multiple

Colors

Color UIText

RGBA

HSLA

Opacity

HSL

Outline

Box SizingNav

Resize Overflow

Shadow Word Wrap

Columns

Media Queries

3D

Selectors

Rich Java Client Seminar

Offline & Storage

Graphics

HTML5 – New Features

Offline

Web Storage

Canvas 2D

Web SQL

WebGL

Indexed DB

DOM

New Selectors

Class List

JavaScript

History

Rich Java Client Seminar

Offline & Storage

Graphics

HTML5 – New Features

Offline

Web Storage

Canvas 2D

Web SQL

WebGL

Indexed DB

DOM

New Selectors

Class List

JavaScript

History

document.getElementsByClassNamedocument.querySelectorAlldocument.querySelector

Rich Java Client Seminar

File & Hardware Access

HTML5 – New FeaturesJavaScript

Cross DomainWeb Messaging

Geolocation

Drag n’ Drop

Orientation

Realtime & Communication

NotificationsWeb

Sockets

Web Workers

Rich Java Client Seminar

HTML5 Status Specs: Still Working Draft.

Few features supportedby all browsers.

Many features supported by all modern browsers (mobiles included).

Most features supportedby bleeding-edge browsers.

Rich Java Client Seminar

GWT + HTML5 Show Case

Rich Java Client Seminar

335

GXT

Rich Java Client Seminar

336

Rich Java Client Seminar

337

HTML5 in GXT State API - Full support of HTML5 local storage

HtmlStorageProvider StorageReadProxy StorageWriteProxy

Rich Java Client Seminar

338

Let’s RecapWrap it up...

Rich Java Client Seminar

» Mature open source project.» Driven by a big corporation.» Big community + 3rd parties.» Ease developer’s pains.

Java is easier to learn and maintain.

Good holistic dev env.» Fast, highly optimized code =>

Scalable, responsive apps.» No plugins needed.

» Lots of new APIs.» Lots of new abilities.» Less boilerplate.» Better SEO and accessibility.» No plugins needed.

GWT HTML5

Pros

Combined» Complete filthy RIA solution.» Cross browser compatibility. » Using maintainable Java

code and a good dev env.

Rich Java Client Seminar

» Relies entirely on JavaScript. JavaScript must be enabled. Limited SEO.

» HTML is harder to tweak.» Longer design-refresh cycles

(Compared with pure HMTL/CSS/JavaScript development).

» JavaScript bootstrap overhead.

» Many features still not supported by current browsers.

» IE6 to IE8 will not be adding support.(Can be solved using plugins).

GWT HTML5

Cons

Rich Java Client Seminar

» Best for: Building RIA. Desktop like applications. HTML5 Games. Gadgets.

» Not to be used for: Building simple/content

websites. Applications which relies

heavily on form submit.

» Must use it: When you can’t deploy to

iPhone App Store.

» Should use it: Whenever you need:

• On mobile devices.• And modern browsers.

»Can’t use it: Older IEs.

GWT HTML5

When Should I Use It?

Rich Java Client Seminar

Reference

...Hyperlinks...

Rich Java Client Seminar

3rd Party Libraries & Frameworks Google Web Toolkit Incubator Widgets and more:

– Ext GWT (aka GXT), based on Ext-JS– SmartGWT, based on Smart-Client– Tatami, based on Dojo– GWT Mosaic

Rich Java Client Seminar

3rd Party Libraries & Frameworks Ajax/REST:

– GWT-REST– RestyGWT – Restlet– Gwittir (+ other utilities)

Rich Java Client Seminar

3rd Party Libraries & Frameworks Patterns (MVP, MVC,...):

– GWT-Presenter– GWT-Dispatch– GWT-MVP– GWTP– GWT-Pectin – MVP4G

Charts:– Gchart – HTML5/Canvas Charts (no Plugins).– OFCGWT – Open Flash Chart integration. – Charts4j-GWT – Google API Charts.

Rich Java Client Seminar

3rd Party Libraries & Frameworks Dependency Injection:

– GIN – Guice-like DI– GWToolbox – Spring-like DI + utilities + widgets.– Rocket-GWT – DI + utilities.

Utilities:– GWT-Log – Logging.– GWT-Validation – Validation. – GWT-DND – Drag n’ drop. – GWT-FX – Animations. – Goda-Time – Joda Time for GWT.– GWT-Mobile-Webkit – HTML 5 support.

Rich Java Client Seminar

3rd Party Libraries & Frameworks Canvas:

– GWT-Canvas– GWT-G2D– GWTCanvas – inside Google Incubator.

Misc:– Emite – XMPP (Jabber) Chat Client.– GWT-Cal – Calendar widget (like Google Calendar, Outlook, iCal).– Vaadin – Framework based on GWT.– GWT-Client-Storage – HTML5 local storage.

Rich Java Client Seminar

Integration Spring Integration

– Spring MVC– Spring Roo (since GWT 2.1)– Spring Insight profiler.

» Vaadin – Framework based on GWT.

Rich Java Client Seminar

357

References

Rich Java Client Seminar

360