Google Web Toolkit

redlemonbalmMobile - Wireless

Dec 10, 2013 (3 years and 9 months ago)

120 views

GWT Roundup: An Overview

of Google’s Web Toolkit

Including Hybrid Integration


Scott Selikoff

Moderator, CodeRanch

Owner, Selikoff Solutions, LLC

March 16, 2011

Overview

I.
Introduction

II.
A GWT Module

III.
6 Reasons to Use GWT

IV.
3 Reasons to Avoid GWT

V.
GWT Server Integration


VI.
Google App Engine

VII.
What’s New in GWT?

VIII.

Beyond GWT

IX.
Further Readings

X.
Contact

I. Introduction


What is GWT?



Is it a UI or Ajax library?


Is it a server platform?


Is it a set of tools?


Is it a web framework
?

The Web Before Ajax


Slow, page
-
based reloads


Limited interactive tools


Flash/Flex, Silverlight, Java FX, Java Applets


Heavyweight and required platform
-
dependent plugins


J2EE focused on improving server interactions


Struts, XML/XSLT, JavaBeans


Very little work on improving user experience


No fat (desktop) clients


2005: Ajax Joins the Party


Ajax (Asynchronous JavaScript and XML) is a group of
technologies that manipulate JavaScript to support
dynamic page generation


Avoid slow page
-
based reload


Page changes after initial request is complete

Ajax Frameworks


Direct frameworks
: Ajax libraries built in JavaScript
and called from JavaScript


Requires mastery of JavaScript, CSS, HTML, and the framework


jQuery, Prototype, Yahoo! UI Library


Indirect frameworks
: Ajax pages authored in high
-
level
languages and translated into JavaScript


Requires only high
-
level knowledge of web technologies


GWT, Apache Wicket, Wt, ASP .NET Ajax, Pyjamas, Quicknet


Both attempt to bridge cross
-
browser issues


II. A GWT Module


Google Web Toolkit is a set of
tools for developing complex
interactive web applications,
primarily in Java

1)
Client component:

Java
-
to
-
JavaScript
compiled code. Can access client/shared.

2)
Server component:

Runs inside servlet
container. Can access all folders.

3)
Shared component:

Contains
POJOs/interfaces used by client/server.

III. 6 Reasons to Use GWT


Reason #1: Powerful UI Widgets


Popup & Dialog Box


Rich Text Editor


Suggest Box (AutoComplete)


III. 6 Reasons to Use GWT (cont)


Panel


Horizontal, Vertical, Split, Dock, Tab*, Stack*


Menu Bars


Trees and Grids

Reason #2: Cross
-
browser Support


GWT handles cross
-
browser and cross
-
platform
conversions automatically


Compiler generates multiple variants of the website for
different browsers and locales


Testing Tip: Speed up compiler by skipping variants in
module.gwt.xml


Compile for IE:


<set
-
property name=”user.agent” value=”ie6″/>


Locale optimization:


Comment out all locales


䝗吠Ti汬 畳u
“default” locale

Reason #2: Cross
-
browser Support (cont)


Plugin developers often concerned with cross
-
browser
customizations


General GWT developers should avoid if possible


GWT offers
deferred binding

as an alternative to Java’s
dynamic classloading:


Class replacement for Firefox 3 in project XML:


<
replace
-
with class
="net.selikoff.gwt.client.FirefoxCountryBox">


<when
-
type
-
is class="net.selikoff.gwt.client.CountryBox
"
/>


<when
-
property
-
is name="user.agent" value="gecko1_8" />



</replace
-
width>

Reason #3: Supports Native Web


Support for native web components


HTML can be inserted directly or programmatically (Class: HTML)


CSS/Javascript files can be dropped into the web application


New UiBinder allows for direct XML component building


Native components have limited cross
-
browser support
guarantees

Reason #4: Supports Native Web (cont)


JavaScript Native Interface (JSNI) allows for JavaScript
annotated code in Java applications


public
static native void alert(String msg) /*
-
{



$wnd.alert(msg);

}
-
*/;


public static native int badExample() /*
-
{



return "Not A Number";

}
-
*/;



Can reference Java classes but syntax is ugly!


Reason #4: Debugging


GWT Hosted Mode


Prior to GWT 2.0, debugging was performed in a specialized web
browser that ran Java code in a JVM

Reason #4: Debugging (cont)


GWT Development Mode


Java byte code is run natively skipping JavaScript translation


Runs in standard web browser with plugin


Since 2.0, much closer to real production environment


GWT Production Mode


Java client code is fully translated to JavaScript (time
-
consuming)


Generally, code executes faster than development mode


Components customized for browser

Reason #4: Debugging (cont)


GWT Development Mode supports standard Java
debugging by starting application in Debug mode


Add breakpoints, watch expressions


Monitor current state and variables

Reason #5: Performance Enhancements


Compiling JavaScript for production can take a lot of
time


Multiple permutations for cross
-
browser and locale support are
generated


JavaScript file size optimization/shortener + obfuscation


Configurable with

style

tag


Perfect Caching: JavaScript files stored with unique MD5 name


Reason #5: Performance Enhancements


Image Bundles


Idea: Take a large group of images and combine them into a single
image with an interface for accessing each image


Significant performance gains since:


More responsive UI since all images are downloaded
together


HTTP 1.1 limits number of outgoing connections to 2 per domain


Bundles
use less bandwidth than separate images


How to create image bundle?


Create an interface that
extends
ImageBundle

and define methods:



@
Resource("open
-
file
-
icon.gif")



AbstractImagePrototype
openFileIcon
();

Reason #6: Data exchange


Client can communicate with variety of services


Can
create asynchronous Ajax callbacks
on components


Uses
XMLHttpRequest

with POST/GET (limited PUT/DELETE)


Built
-
in support for Object Serialization, JSON, and XML


JSON and XML code not always short!


JSON: {"name": "Scott"}

String response = (JSONObject) JSONParser.parse(response.getText());

String name = ((JSONString)response.get("name")).stringValue();


XML: <name>Scott</name>

Document doc = XMLParser.parse(response);

Element root = (Element) doc.getFirstChild();

String name = root.getElementsByTagName("name").item(0)




.getFirstChild().getNodeValue();

Reason #6: Data exchange (cont)


Server component can handle client requests


Unlike client, Server has access to full Java API


Except if Google App Engine is enabled


GWT RPC


Utilize client
-
owned Serializable POJOs


Can be in a shared project/JAR if declared as a GWT module


Must implement
IsSerializable

or
java.io.Serializable


Prefer
java.io.Serializable

since leaves code less
dependent on Google Jars

Reason #6: Data exchange (cont)


Define Synchronous and Asynchronous coupled
interfaces

1)
Synchronous
implemented
by server


public
Integer saveWidget(Widget widget, Context context
);


2)
Asynchronous used by client


public
void saveWidget(Widget widget, Context context,





AsyncCallback<Integer
> callback
);



Implement service that extends
RemoteServiceServlet

and implements the
SyncService


Reason #6: Data exchange (cont)


Instantiate RPC connection on the client:

AsyncService service = GWT.create(SyncService.class)


Create Async call:


AsyncCallback<Integer> callback = new AsyncCallback<Integer>() {



public void onFailure(Throwable caught) {



}



public void onSuccess(Object result) {





// Do stuff!



}


});


service.saveWidget(widget,context,callback);

IV. 3 Reasons to Avoid GWT


The grass is not always greener!

Reason #1: API is a Moving Target


GWT API and code base is in a constant state of flux


Cutting (bleeding) edge technology


Not for the faint of heart


New plugins/add
-
ons often


Not all plugins are cross
-
platform or fully tested


API deprecation happens frequently


May need to rewrite code after upgrading to latest GWT release

Reason #2: Restrictive Runtime


JRE != GWT emulated runtime


Key Differences


Some common Java classes excluded from use


Google implemented its own replacement classes


Examples: DateTimeFormat, NumberFormat, Timer, etc


Single
-
threaded (HTML5 will change this!)


Regular expression syntax is JavaScript
-
based


long

implemented as two 32
-
big integers in GWT 1.5+


Compatibility information:


http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsCompatibility.html



Reason #3: Can’t edit live code


Compiled JavaScript code cannot (and should not) be
edited by hand


Interferes with GWT caching


Conversion from Java to JavaScript only one
-
way


Need to rebuild your library


Compile
-
time step isn’t fast


Limited support for hot swapping

V. GWT Server Integration


Technique #1: RPC


As previously discussed, RPC allows creation of server
-
side service
that directly integrates with GWT client application

GWT Web Application

GWT Service

GWT Client

User

Database

Technique #1: RPC (cont)


Review of Technique


Advantages:


Full JVM access on server component


Server and client shared code in same project


Deployed as single WAR


Disadvantages


Tight coupling of server and client code


Limited code reuse by other projects


Technique #2: Client Communication


Client can make direct calls to external services in the
JavaScript layer


Wide range of web service protocols accepted


POX/REST/XML


JSON


Text


Alternative to RPC approach which relies little on GWT
server code



Technique #2: Client Communication (cont)

GWT Web Application

GWT Service

GWT Client

User

Remote
Service

Protocol: XML,

JSON, text, etc

Database

Technique #2: Client Communication (cont)


Review of Technique


Advantages


Simple Client/Server interactions


Loose coupling of client and server


Disadvantages


Same origin
-
policy prevents direct external connections


Can bypass same
-
origin policy via external scripts


Loss of built
-
in serialization support

Technique #3: Redirect to J2EE Service


Redirect RPC calls to external service:

1)
Shared JAR:

Place shared POJO’s GWT project JAR

1)
Must also be a GWT module to be usable by GWT web app

2)
Distribute client Jar to J2EE service and GWT application

3)
Prefer java.io.Serializable over IsSerializable

2)
GWT Client:

Create as before with RPC calls

3)
GWT Service:

Thin service layer that redirects call to external J2EE
service


Implement the J2EE service interface


捡汬猠s牥 敡獹 瑯⁲e
-
牯畴r

4)
J2EE Service:

External process that handles all J2EE requests

Technique #3: Redirect to J2EE Service

GWT Web Application

GWT Service

[thin]

GWT Client

User

Shared JAR

JavaScript Compiled

Version of GWT Module

GWT Module

Database

J2EE Service

Compiled JAR with

GWT metadata
removed

Technique #3: Redirect to J2EE Service


Review of Technique


Advantages


Best of Both Worlds: Power of J2EE and UI of GWT


Decoupled GWT (presentation) and J2EE services (business)


Stand alone service does not reference any GWT libraries


GWT metadata can be stripped out in Server version of JAR


Works for web services, J2EE/EJB server, Hessian service, etc


Disadvantages


Potential latency problem if the J2EE service is on a separate
server from the GWT web server


Works better for stateless calls

VI. Google App Engine


Web application capable of running in Google hosted
environment


GWT applications can be converted to Google App Engine projects by
adding libraries and XML configuration


GWT Eclipse plugin can handle this automatically


GWT Eclipse plugin also includes deployment tools


Applications run in secure sandbox


Custom JVM with restrictions


Can read but not write files to the file system, nor open sockets


Included Jars may not be compatible


VII. What’s New in GWT?


Development mode replaced “hosted mode” in 2.0


HTML5
-
specific features added in 2.2


Client
-
side logging has been added in 2.1


Partially emulates java.util.logging framework


Minus any file/socket interactions


RemoteLogHandler can be used to forward client logging to the server
and then to disk


Model
-
View
-
Presenter added in GWT 2.1


Relies on Activities and Places

Speed Tracer


New Google Chrome extension to analyze web site
performance in GWT 2.0


Two forms of measure as well as hints


Sluggishness Graph:

Shows UI responsiveness






Network Graph:

Network activity and latency


UiBinder and GWT Designer


UiBinder
: Allows creation of interfaces in XML with
support for bundled
resources/localization in GWT 2.0


Analogous to
creating Flex/Flash
MXML
files instead of
ActionScript classes


<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'





xmlns:g='urn:import:com.google.gwt.user.client.ui'>




<g:HTMLPanel>





Hello, <g:ListBox ui:field='listBox' visibleItemCount='1'/>.



</g:HTMLPanel>


</ui:UiBinder>

UiBinder and GWT Designer (cont)


GWT Designer
: Set of visual tools for creating
UiBinder files added in GWT 2.2

RequestFactory


RequestFactory


Alternative to RPC for data
-
centric services


Object relational mapping with foundations in JPA

and JDO


Client support for ORM tools


Entities defined on the server


Accessed via RequestFactory, RequestContext, and EntityProxy
interfaces


Contain JPA annotations


Client calls persist() methods to save objects


Asynchronous callbacks available on the client as fire() methods


VIII. Beyond GWT


Still is a young platform


Growing in leaps and bounds into full
-
feature platform


Unstable and growing API compared to other open source projects


Plugin developers can barely keep up


Needs more customizable UI widgets!


Many developers rely on proprietary advanced toolkits


Needs more enterprise
-
level server features

IX. Further Readings


Books:


Google Web Toolkit Applications

by Ryan Dewsbury


Excellent introductory material and example applications


GWT in Practice

by Robert T. Cooper and Charlie E. Collins


Chapter 5 lists even more techniques for remote server integration


Support


CodeRanch:


http://www.coderanch.com/forums/f
-
99/GWT

IX. Further Readings (cont)


Web pages


GWT Web Toolkit Home:


http://code.google.com/webtoolkit/


Google App Engine Home:


http://code.google.com/appengine/


GWT Compatibility Document


http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasi
csCompatibility.html


GWT API:


http://google
-
web
-
toolkit.googlecode.com/svn/javadoc/2.1/index.html

X. Contact


GWT Roundup: An Overview of Google’s Web Toolkit
Including Hybrid Integration


Presented By Scott Selikoff


E
-
mail: info@selikoffsolutions.com


Blog:
Down Home Country Coding


Co
-
author Jeanne Boyarsky


http://www.selikoff.net


CodeRanch


http://www.coderanch.com/forums