Building Rich Internet Applications Using Google Web Toolkit

56
Karthik Shyamsunder Building Rich Internet Applications Using Google Web Toolkit (GWT) Karthik Shyamsunder October 2008

Transcript of Building Rich Internet Applications Using Google Web Toolkit

Page 1: Building Rich Internet Applications Using  Google Web Toolkit

Karthik Shyamsunder

Building Rich Internet ApplicationsUsing Google Web Toolkit (GWT)

Karthik Shyamsunder

October 2008

Page 2: Building Rich Internet Applications Using  Google Web Toolkit

2 VeriSign Proprietary and Confidential Information

Who am I?

+ Karthik Shyamsunder▪ Principal Engineer, VeriSign Inc.

▪ Application Architect for the VeriSign Naming Division▪ Adjunct Faculty at Johns Hopkins University▪ Speak at conferences on Architecture, Security, Performance, Distributed

Computing, Language/Design

Page 3: Building Rich Internet Applications Using  Google Web Toolkit

3 VeriSign Proprietary and Confidential Information

Overall Goal of this Session

1. Introduce you to the GWT framework andapplication development

2.Discuss key features in GWT that willallow you to build no compromise AJAXapplications

Page 4: Building Rich Internet Applications Using  Google Web Toolkit

4 VeriSign Proprietary and Confidential Information

Agenda

+ RIA Technologies, Frameworks and GWT

+ GWT Quickstart

+ GWT Architecture

+ Key GWT Features

+ Summary

+ Q&A

Page 5: Building Rich Internet Applications Using  Google Web Toolkit

5 VeriSign Proprietary and Confidential Information

Agenda

+ RIA Technologies, Frameworks and GWT

+ GWT Quickstart

+ GWT Architecture

+ Key GWT Features

+ Summary

+ Q&A

Page 6: Building Rich Internet Applications Using  Google Web Toolkit

VeriSign Proprietary and Confidential Information

What are Rich Internet Applications?

+ Web applications that have the features andfunctionality of traditional desktop applications

+ Typically do the following:▪ run in a web browser, or do not require software

installation▪ run locally in a secure environment called asandbox

+ Typically transfer the processing necessary for theuser interface to the web client but keep the bulk ofthe data back on the application server

+ Make asynchronous/synchronous calls to thebackend based on user actions/events

+ “Thick Client” Application

Backend Processes

Server Logic

Server

(Sandbox Client Engine)

Page 7: Building Rich Internet Applications Using  Google Web Toolkit

VeriSign Proprietary and Confidential Information

Technologies for Building RIAs

+ Several technologies available for buildingRich Internet Applications

+ Key Technologies for building RIAs▪ Adobe Flex▪ Microsoft Silverlight▪ Java Applets/WebStart▪ AJAX

+ Other Technologies and Frameworks forbuilding RIAs▪ Java FX▪ Open Laszlo

Backend Processes

Server Logic

Server

(Sandbox Client Engine)

Page 8: Building Rich Internet Applications Using  Google Web Toolkit

VeriSign Proprietary and Confidential Information

Building RIAs using Java EE and AJAX

We can classify building applications in AJAX into 2 :1. Client Side AJAX Development

– Presentation using HTML/JSP pages using client side frameworks such asScriptaculous, JQuery, Dojo client side components

– Presentation logic using JavaScript– Server Side development using traditional Java EE Servlets/Services

exposing backend services as REST, XML RPC Web Services– Call backend business logic in the background using the JavaScript

language and XMLHttpRequest object built into the browser

2. Server Side AJAX Development– Presentation using component frameworks JSTL tag libraries such as JBoss

RichFaces, Icesoft Icefaces built on on top of JSF– Presentation logic done as event handlers in JSF component model– Call to backend business logic using JSF event Model

Page 9: Building Rich Internet Applications Using  Google Web Toolkit

9 VeriSign Proprietary and Confidential Information

Challenges with typical AJAX development

+ JavaScript▪ Not a strongly typed language▪ Static Type checking?▪ Code completion?▪ Runtime-only bugs

+ Browser compatibilities = “if/else soup”▪ OK, we have frameworks▪ Too many frameworks!

+ Juggling multiple languages (JavaScript, JSP tags,Java, XML, HTML etc.)▪ Less modularization▪ Maintenance nightmare

+ Poor debugging▪ Window.alert(), Firebug▪ But what about end to end

+ Back button+ Limited IDE support

Page 10: Building Rich Internet Applications Using  Google Web Toolkit

10 VeriSign Proprietary and Confidential Information

Introducing Google Web Toolkit

Page 11: Building Rich Internet Applications Using  Google Web Toolkit

11 VeriSign Proprietary and Confidential Information

Introducing GWT

+ What is GWT?▪ GWT is an open source Java development framework▪ Provides set of tools for building AJAX apps in the Java language

+ What makes GWT interesting?▪ Write, run, test, and debug everything in JAVA!

+ GWT ≠ applets▪ GWT converts your Java source into equivalent JavaScript

+ Is GWT a compiler?▪ GWT has a compiler, but it has lot more to offer…

Page 12: Building Rich Internet Applications Using  Google Web Toolkit

12 VeriSign Proprietary and Confidential Information

Why Use Java Language for AJAX Development?

+ Static type checking in the Java language boosts productivity whilereducing errors

+ Common JavaScript errors (typos, type mismatches) are easilycaught at compile time rather than by users at runtime

+ Code prompting/completion is widely available

+ Automated Java refactoring is pretty snazzy these days

+ Java-based OO designs are easier to communicate and understand,thus making your AJAX code base more comprehensible with lessdocumentation.

Page 13: Building Rich Internet Applications Using  Google Web Toolkit

13 VeriSign Proprietary and Confidential Information

Advantages of GWT

+ No need to learn/use JavaScript language▪ Leverage Java programming knowledge you already have

+ No need to handle browser incompatibilities and quirks▪ GWT handles them for you

+ No need to learn/use DOM APIs▪ Use Java APIs

+ No need to handle forward/backward buttons browser-history▪ GWT handles it for you

+ No need to build commonly used Widgets▪ Most of them come with GWT

+ Can send complex Java types to/from the server▪ Data gets serialized across network

Page 14: Building Rich Internet Applications Using  Google Web Toolkit

14 VeriSign Proprietary and Confidential Information

Advantages of GWT

+ Leverage various tools of Java programming language forwriting/debugging/testing▪ For example, NetBeans or Eclipse

+ Internationalization▪ GWT includes a flexible set of tools to help you internationalize your

applications and libraries▪ GWT internationalization support provides a variety of techniques

+ JUnit integration▪ GWT's direct integration with JUnit lets you unit test both in a debugger

and in a browser and you can even unit test asynchronous RPCs

+ Support by major company▪ From the company that popularized Ajax in the first place▪ Company won't go away like perhaps with AjaxTags

Page 15: Building Rich Internet Applications Using  Google Web Toolkit

15 VeriSign Proprietary and Confidential Information

Disadvantages of GWT

+ Only for Java developers▪ Most Ajax environments do JavaScript on the client and have a choice

for the server. GWT is based entirely around Java.

+ Big learning curve▪ Java developers can deploy with AjaxTags in just a few minutes,

whereas it takes much longer to get anything running with GWT.

+ Cumbersome deployment▪ Clumsy and poorly documented process to deploy on a regular Java-

based Web server.

+ Nonstandard approach to integrate JavaScript▪ You never put direct JavaScript in your HTML. Instead, you use JSNI to

wrap JavaScript in Java.– Very powerful in the long run, but hard to get used to at first.

+ Unusual approach▪ Fundamentally different strategy than all other Ajax environments

makes evaluation and management buyoff harder

Page 16: Building Rich Internet Applications Using  Google Web Toolkit

16 VeriSign Proprietary and Confidential Information

Agenda

+ RIA Technologies, Frameworks and GWT

+ GWT Quickstart

+ GWT Architecture

+ Key GWT Features

+ Summary

+ Q&A

Page 17: Building Rich Internet Applications Using  Google Web Toolkit

17 VeriSign Proprietary and Confidential Information

Downloading and Installing GWT

+ Official Site for GWT is http://code.google.com/webtoolkit/

+ Downloading GWT▪ You can download the latest version of software from

http://code.google.com/webtoolkit/download.html▪ Licensed under Apache 2.0 open source license scheme▪ Latest version of the software is GWT 1.5

+ Installing GWT▪ Extract the ZIP file into wherever you want to install the toolkit▪ That’s it!

+ Setting up the development environment▪ Add {INSTALL-DIR}\gwt-windows-1.5.2 to your PATH▪ This is so that the many of the toolkit commands are available

+ Since GWT is java based tool ensure that you have JDK 1.5 orabove and JAVA_HOME is set

Page 18: Building Rich Internet Applications Using  Google Web Toolkit

18 VeriSign Proprietary and Confidential Information

Application Development Steps

+ Create an Eclipse application▪ Use projectCreator and applicationCreator scripts▪ You can make non-Eclipse projects also, but the tutorial examples

assume Eclipse. I use MyEclipse, but it is similar in both versions.

+ Edit auto-generated HTML file▪ Called AppName.html

– Under src/package.../public folder in Eclipse▪ Give ids to regions where controls will be placed

+ Edit auto-generated Java application class▪ Class: package...client.AppName

– Under src folder in Eclipse▪ Method: onModuleLoad▪ Create controls and give them event handlers▪ Insert controls into HTML page

– RootPanel.get("htmlID").add(control);

Page 19: Building Rich Internet Applications Using  Google Web Toolkit

19 VeriSign Proprietary and Confidential Information

Application Development Steps

1. Make sure PATH includes GWT install directory▪ Or specify full path for scripts

2. Make a temporary directory for your project▪ Directory name is arbitrary

3. Make a blank Eclipse project▪ DOS> projectCreator –eclipse GwtTestProject

4. Make a starting-point application▪ DOS> applicationCreator –eclipse GwtTestProject

myPackage.client.GwtTestApplication

5. Start Eclipse and import project▪ File > Import > Existing Projects into Workspace

– Browse to directory from (2) above and click "Finish"– If you specify "copy files" (usual approach), then delete the

temporary directory from (2) above

Names must match

Name of driver classthat will be created.Rightmost packagename must be "client".

Page 20: Building Rich Internet Applications Using  Google Web Toolkit

20 VeriSign Proprietary and Confidential Information

Application Development Steps

Starting point client-side code. You will edit this extensively.

When you make server-side code, register servlet in here.

Starting-point HTML file. You will edit this extensively.

Client-side code must be in "client" package. Server-side code can also import and call classes in thispackage (other than main app). All code in thispackage will eventually get translated into JavaScript.

After you have finished testing and debugging, you candouble-click this to generate www directory containing HTMLand JavaScript that can run in a regular browser. But aneasier way to build these files is to run in hosted mode andthen click Compile/Browse (see later slides).

Not needed if you run within an IDE.

Page 21: Building Rich Internet Applications Using  Google Web Toolkit

21 VeriSign Proprietary and Confidential Information

Agenda

+ RIA Technologies, Frameworks and GWT

+ GWT Quickstart

+ GWT Architecture

+ Key GWT Features

+ Summary

+ Q&A

Page 22: Building Rich Internet Applications Using  Google Web Toolkit

22 VeriSign Proprietary and Confidential Information

GWT Architecture

Page 23: Building Rich Internet Applications Using  Google Web Toolkit

VeriSign Proprietary and Confidential Information

Google Web Toolkit - Architecture

Web/ApplicationServer

Server Side .java

JavaCompiler

.class .html.html

DE

PL

OY

(AJAX Runtime Engine)

HTTP/REST/Web ServicesXML/JSON/RPC

.html. js

Client Side .java

GWTCompiler

Page 24: Building Rich Internet Applications Using  Google Web Toolkit

24 VeriSign Proprietary and Confidential Information

Running GWT Applications

Hosted Mode▪ Application is run as Java byte

code within the JVM▪ Developers spend most of their

time in hosted mode to takeadvantage of Java's debuggingfacilities and other features

+ Web mode▪ Application is run as pure

JavaScript and HTML, compiledfrom your original Java sourcecode with the GWT Java-to-JavaScript compiler

▪ You deploy this JavaScript andHTML to production, so end userssees web version of your app

Page 25: Building Rich Internet Applications Using  Google Web Toolkit

25 VeriSign Proprietary and Confidential Information

Agenda

+ RIA Technologies, Frameworks and GWT

+ GWT Quickstart

+ GWT Architecture

+ Key GWT Features

+ Summary

+ Q&A

Page 26: Building Rich Internet Applications Using  Google Web Toolkit

26 VeriSign Proprietary and Confidential Information

What browsers does GWT Support?

+ Officially as of mid 2008, GWT supports the following browsers:

▪ Firefox 1.0, 1.5, 2.0 and 3.0

▪ Internet Explorer 6 and 7

▪ Safari 2 and 3

▪ Opera 9.0

Page 27: Building Rich Internet Applications Using  Google Web Toolkit

27 VeriSign Proprietary and Confidential Information

GWT Widgets and Layout

Page 28: Building Rich Internet Applications Using  Google Web Toolkit

28 VeriSign Proprietary and Confidential Information

UI components & Event Programming Model

+ Programming model similar UI frameworks such as Swing

+ Primary difference between Swing and GWT is here widgets aredynamically transformed to HTML rather than pixel-oriented graphics

+ Using widgets makes it much easier to quickly build interfaces that willwork correctly on all browsers

Button btnOk = new Button(“OK”);CheckBox married= new CheckBox(“Married”);

+ Events in GWT use the "listener interface" model similar to other userinterface frameworks (like Swing)

btnOk.addClickListener(new MyClickListener());\

+ Possible to manipulate the browser's DOM directly using the DOMinterface, but better to use Java classes from Widget library

Page 29: Building Rich Internet Applications Using  Google Web Toolkit

29 VeriSign Proprietary and Confidential Information

Style with CSS

+ Each widget class has an associated style name that binds it to aCSS rule▪ For example GWT Button has a style called “gwt-Button”

+ A widget’s style name can be set using▪ setStyleName(String)

+ Also possible to assign an id to a particular component to create aCSS rule that applies to just one component▪ <div id=“my-button-id”/>

+ To set the id for a GWT widget, retrieve its DOM Element and then setthe id attribute as follows▪ Button b = new Button();▪ DOM.setElementAttribute(b.getElement(), "id", "my-button-id")

+ Allows you to reference a specific widget in a stylesheet as follows#my-button-id { font-size: 100%; }

Page 30: Building Rich Internet Applications Using  Google Web Toolkit

30 VeriSign Proprietary and Confidential Information

Style with CSS (Contd.)

+ Including Stylesheets in the HTML Host Page▪ Stylesheets are placed in the module's public path▪ Refer to them them by simply using a <link> tag in the page:

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

+ GWT comes with 3 default visual themes that you can choose from▪ Standard, Chrome, and Dark

+ By default new applications use standard theme

+ Other themes can be selected by adding inherits tag in theMain.gwt.xml file<inherits name='com.google.gwt.user.theme.standard.Standard'/><inherits name="com.google.gwt.user.theme.chrome.Chrome"/><inherits name="com.google.gwt.user.theme.dark.Dark"/>

Page 31: Building Rich Internet Applications Using  Google Web Toolkit

31 VeriSign Proprietary and Confidential Information

Third Party Visual Builder - Instantiations

+ Instantiations, a software company in Portland Oregon, USA

+ Has a product called GWT Designer which is a powerfulbi0directional WYSIWYG tool that may be worth looking into

Page 32: Building Rich Internet Applications Using  Google Web Toolkit

32 VeriSign Proprietary and Confidential Information

RPC

+ RPCs give you the opportunity to move all UI logic to the client, thus▪ Geatly improving performance▪ Reducing bandwidth▪ Reducing web server load, and a pleasantly fluid user experience

+ Creating a Service1. Define an service interface that extends RemoteService with methods2. Implement the service by extending RemoteServiceServlet and

implementing the business methods in the service3. Define an asynchronous interface for the service to be called by the

client-side

+ GWT RPC makes it easy for the client and server to pass Javaobjects back and forth over HTTP

Page 33: Building Rich Internet Applications Using  Google Web Toolkit

33 VeriSign Proprietary and Confidential Information

RPC (Contd.)

package com.example.foo.client;

interface MyServiceAsync {

public void myMethod(String s, AsyncCallback<String> callback);

}

package com.example.foo.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import com.example.client.MyService;

public class MyServiceImpl extends RemoteServiceServlet implements MyService{

public String myMethod(String s) {

// Do something interesting with 's' here on the server.

return s;

}

}

package com.example.foo.client;

import com.google.gwt.user.client.rpc.RemoteService;

public interface MyService extends RemoteService {

public String myMethod(String s);

}

Page 34: Building Rich Internet Applications Using  Google Web Toolkit

34 VeriSign Proprietary and Confidential Information

RPC (Contd.)

+ GWT RPC Plumbing

Page 35: Building Rich Internet Applications Using  Google Web Toolkit

35 VeriSign Proprietary and Confidential Information

RPC (Contd.)

+ Asynchronously making the call involves the following steps//(1) Instantiate the service

MyEmailServiceAsync myService = (MyService) GWT.create(MyService.class);

// (3) Make the call.

myService.mymethod(“abc”);

//(2) Create an asynchronous callback to handle the result.

AsyncCallback callback = new AsyncCallback() {

public void onSuccess(Object result) {

// do some UI stuff to show success

}

public void onFailure(Throwable caught) {

// do some UI stuff to show failure

}

};

Page 36: Building Rich Internet Applications Using  Google Web Toolkit

36 VeriSign Proprietary and Confidential Information

Image Bundle

+ Images in AJAX and Web applications▪ Typically applications use a lot of images▪ Each image is a separate file▪ Browser fetches each separately

+ Studies have shown the following▪ Large overhead:

– Web applications have icons which are typically smaller than size of therequest

– Hence most of the traffic is overhead and very little of it actual content▪ Useless freshness checks :

– Even when the images have been cached by the client, a 304 ("Not Modified")request is still sent to check and see if the image has change

– Since images change infrequently, these freshness checks are also wasteful▪ Blocking HTTP connections :

– HTTP 1.1 requires browsers to limit the number of outgoing HTTPconnections to two per domain/port

– A multitude of image requests will tie up the browser's available connections,thus preventing real RPC requests that do the real work

Page 37: Building Rich Internet Applications Using  Google Web Toolkit

37 VeriSign Proprietary and Confidential Information

Image Bundle (Contd.)

+ GWT solves performance problems by introducing a construct calledImage Bundle

+ GWT Image Bundle bundles a bunch of image files into a single largefile and manages as a single Java Object

+ Since filename is based on the hash of the file's contents, thefilename will change only if the composite image is changed▪ Hence, it is safe for clients to cache the composite image permanently,

which avoids the unnecessary freshness checks for unchanged images▪ To make this work, the server configuration needs to specify that

composite images never expire.

Page 38: Building Rich Internet Applications Using  Google Web Toolkit

38 VeriSign Proprietary and Confidential Information

Image Bundle (Contd.)

+ To define an image bundle, the developer needs to extend theImageBundle interface▪ The ImageBundle interface is a marker interface▪ The derived interface can have zero or more methods, where each

method must have the following characteristics– The method takes no parameters– The method has a a return type of AbstractImagePrototype– The method may have an optional gwt.resource metadata tag which

specifies the name of the image file in the module's classpath

+ If the gwt.resource metadata tag is not specified, then the followingassumptions are made▪ The image filename is assumed to match the method name▪ The extension is assumed to be either .png, .gif, or .jpg▪ The file is assumed to be in the same package as the derived interface

Page 39: Building Rich Internet Applications Using  Google Web Toolkit

39 VeriSign Proprietary and Confidential Information

Image Bundle (Contd.)public interface WordProcessorImageBundle extends ImageBundle { /**

* Would match file 'new_file_icon.png', 'new_file_icon.gif', or

* 'new_file_icon.png' located in the same package as this type.

*/

public AbstractImagePrototype new_file_icon();

/** * Would match the file 'open_file_icon.gif' located in the same

* package as this type.

* @gwt.resource open_file_icon.gif */

public AbstractImagePrototype openFileIcon();

/** * Would match the file 'savefile.gif' located in the package

* 'com.mycompany.mygwtapp.icons', provided that this package is

* part of the module's classpath.

* @gwt.resource com/mycompany/mygwtapp/icons/savefile.gif */ public AbstractImagePrototype saveFileIcon();}

Page 40: Building Rich Internet Applications Using  Google Web Toolkit

40 VeriSign Proprietary and Confidential Information

Image Bundle (Contd.)

+ Using Image bundle in the applicationpublic void useImageBundle() { WordProcessorImageBundle wpImageBundle =

(WordProcessorImageBundle)GWT.create(WordProcessorImageBundle.class);

HorizontalPanel tbPanel = new HorizontalPanel(); tbPanel.add(wpImageBundle.new_file_icon().createImage()); tbPanel.add(wpImageBundle.openFileIcon().createImage()); tbPanel.add(wpImageBundle.saveFileIcon().createImage());}

+ Image bundles are immutable, so you can keep a reference to a singletoninstance of an image bundle instead of creating a new instance every timethe image bundle is needed

Page 41: Building Rich Internet Applications Using  Google Web Toolkit

41 VeriSign Proprietary and Confidential Information

History

+ Ajax apps sometimes fail to meet user's expectations because theydo not interact with the browser in the same way as static web pages▪ Back button, forward button, bookmarking

+ The basic premise is to keep track of the application's "internal state"in the url fragment identifier

+ For each page that is to be navigable in the history, the applicationshould generate a unique history token

+ For example, a history token named "page1" would be encoded in aURL as follows▪ http://www.example.com/com.example.gwt.HistoryExample/

HistoryExample.html#page1

Page 42: Building Rich Internet Applications Using  Google Web Toolkit

42 VeriSign Proprietary and Confidential Information

History (Contd.)

+ When the application wants to push a placeholder onto the browser'shistory stack, it simply invokes History.newItem(token)

+ When the user uses the back button, a callback will be passed to anyobject that was added as a listener to History.addHistoryListener()▪ It is up to the app to restore the state according to the value of the token

+ To use GWT History support, you must first embed an iframe into yourhost HTML page

<iframe src="javascript:''" id="__gwt_historyFrame" style="width:0;height:0;border:0"></iframe>

+ When the onHistoryChanged() method is invoked, your application musthandle two cases:▪ The application was just started and was passed a history token.▪ The application is already running and was passed a history token.

Page 43: Building Rich Internet Applications Using  Google Web Toolkit

43 VeriSign Proprietary and Confidential Information

Internationalization and Configuration

+ GWT provides several techniques that can aid in Internationalizationand configuration of your AJAX application

+ GWT provides 2 mechanisms▪ Static String inclusion at compile time

– Accomplished by GWT Constants interface which has pure messages– Accomplished by GWT Messages interface which allows parameterization

▪ Dynamic String inclusion at run time– Accomplished by GWT Dictionary class

+ Static Inclusionpublic interface MySettings extends Constants {

String welcomeMessage();String logoImage();}

public interface MySettings extends Messages {

String welcomeMessage(String fname, String lname);String logoImage();

}

Page 44: Building Rich Internet Applications Using  Google Web Toolkit

44 VeriSign Proprietary and Confidential Information

Internationalization and Configuration (Contd.)

+ In the static approach, you define a default properties file of the formatFilename.properties where Filename is the static property interfacename such as MySettings.properties

+ For locale specific, you can also specific FileName_xx_YY.propertiesfile where xx would be ISO Language code and YY ISO country code

+ Referencing constants from a resource file▪ MySettings mySettings =(MySettings)GWT.create(MySettings.class);▪ Label newLabel = new Label(Constants.labelText());

+ Static initialization are advantageous because▪ Properties are statically included in compiled JavaScript, hence the

performance is really good, same as hard coded string▪ Compiler only includes properties that are refernces

+ Modules that use this interface should inherit com.google.gwt.i18n.I18N.<inherits name="com.google.gwt.i18n.I18N"/>

Page 45: Building Rich Internet Applications Using  Google Web Toolkit

45 VeriSign Proprietary and Confidential Information

Internationalization and Configuration (Contd.)

+ Dynamic String Inclusion for Internationalization▪ Allows existing i18n apps to be quickly incorporated into GWT applications▪ Helpful if existing apps used JavaScript associate array objects for i18n

var userInterfaceEN = { var userInterfaceSV {

hello: Hello, hello: Hejsan,yes: Yes, yes: Ja,no: No no: Nej

} }

+ Referencing constants from a resource fileDisctionary uiText = Dictionary.getDictionary(“userInterfaceSV”);uiText.get(hello);

+ Advantage of Dynamic String initialization▪ You can quickly incorporate existing i18n approach into the application

+ Disadvantage▪ GWT provides no help whether constants you are referring to exist▪ Compiler cannot perform any optimization

Page 46: Building Rich Internet Applications Using  Google Web Toolkit

46 VeriSign Proprietary and Confidential Information

JavaScript Native Interface

+ GWT code is written in Java which gets translated into JavaScript, butsometimes there is a need to make JavaScript calls▪ May need to call browser’s API for which no GWT equivalent exists▪ May want to use some super-cool JavaScript lib

+ JavaScript Native Interface lets you execute JavaScript from Java aswell as execute Java from JavaScript

+ Made possible because of the GWT compiler which can merge nativeJavaScript code with the JavaScript code generated from Java

+ Calling JavaScript from javapublic native int addTwoNumbers(int x, int y) {/*-{

var result result = x+ y;return result;}-*/;

Page 47: Building Rich Internet Applications Using  Google Web Toolkit

47 VeriSign Proprietary and Confidential Information

JavaScript Native Interface (Contd.)

+ Calling JavaScript from java

public static native void alert(String msg) /*-{ $wnd.alert(msg);}-*/

public static native int badExample() /*-{ throw("Not A Number“);

}-*/;

public void onClick () { try { int myValue = badExample(); GWT.log("Got value " + myValue, null); } catch (Exception e) { GWT.log("JSNI method badExample() threw an exception:", e); }}

Page 48: Building Rich Internet Applications Using  Google Web Toolkit

48 VeriSign Proprietary and Confidential Information

JavaScript Native Interface (Contd.)

+ Accessing Java from JavaScript▪ [instance-expr.]@class-name::[field-name|method-name{}]

▪ instance-expr could be this or blank for staticpackage mypackage;public MyUtilityClass { public static int calcLoanInterest(int amt, float intRate, int term) { ... } public static native void exportStaticMethod() /*-{ $wnd.computeLoanInterest = @mypackage.MyUtilityClass::calcLoanInterest(IFI); }-*/;}

+ Writing JSNI methods is powerful idea, but should be used sparingly▪ because writing bulletproof JavaScript code is tricky▪ JSNI code is potentially less portable across browsers▪ Less amenable to Java tools

Harder for the compiler to optimize

Page 49: Building Rich Internet Applications Using  Google Web Toolkit

49 VeriSign Proprietary and Confidential Information

Packaging and Deploying a GWT Application

+ Output of the GWT compiler is purely static content

+ All one has to do is copy the GET generated content files fromwww/<package>.<modulename> into WAR file folder

+ GWT generated files can be put anywhere in the war file as long as itis URL accessible

+ But special steps have to be taken if the application uses GWT RPC▪ Copy the gwt-servlet.jar from the GWT distribution to the WEB-

INF/lib folder▪ Compile all server side classes which are classes under server and copy

them into WEB-INF/classes folder

Page 50: Building Rich Internet Applications Using  Google Web Toolkit

50 VeriSign Proprietary and Confidential Information

JavaScript Obfuscation and Minimization

+ By default, GWT obfuscates the JavaScript it produces

+ Obfuscation done by the compiler partly▪ To protect the intellectual property of the application you develop▪ To reduce the size of the generated JavaScript files, thus making them faster to

download and parse

+ If you prefer not to have GWT obfuscate its output, then you can usethe "-style" flag on the GWT Compile▪ -style OBFUSCATED (small, efficient, and fast) – default style▪ -style PRETTY (Human readable output)▪ -style DETAILED (Similar to PRETTY with even more details – verbose

variable names etc.)

+ If you are curious about what GWT's generated JavaScript is doing,then you can use "-style PRETTY“

+ On If you are debugging GWT's output, then "-style DETAILED" mightbe helpful

Page 51: Building Rich Internet Applications Using  Google Web Toolkit

51 VeriSign Proprietary and Confidential Information

GWT and JUnit Integration

+ Best practice in software engineering is to write automated tests

+ JUnit is best of breed Java Test Framework

+ GWT has integrated with JUnit

+ In order to write a new Test case, yo write a class that inherits fromGWTTestCase which extends JUnit’s TestCase

+ You also need to implement one methods called“getModuleName()” at a minimum and then any number of testmethods

Page 52: Building Rich Internet Applications Using  Google Web Toolkit

52 VeriSign Proprietary and Confidential Information

Agenda

+ RIA Technologies, Frameworks and GWT

+ GWT Quickstart

+ GWT Architecture

+ Key GWT Features

+ Summary

+ Q&A

Page 53: Building Rich Internet Applications Using  Google Web Toolkit

53 VeriSign Proprietary and Confidential Information

Summary

+ Paradigm shift in AJAX web development

+ Turn AJAX development into software engineering

+ Ph.D. in browser quirks is no longer a hiring pre requisite

+ Reusable UI components

+ Ease of development, debugging and maintenance

+ High performant

+ Developed, Backed by Google!

Page 54: Building Rich Internet Applications Using  Google Web Toolkit

54 VeriSign Proprietary and Confidential Information

Agenda

+ RIA Technologies, Frameworks and GWT

+ GWT Quickstart

+ GWT Architecture

+ Key GWT Features

+ Summary

+ Q&A

Page 55: Building Rich Internet Applications Using  Google Web Toolkit

55 VeriSign Proprietary and Confidential Information

Questions + Answers

Page 56: Building Rich Internet Applications Using  Google Web Toolkit

Karthik Shyamsunder

Thank You