GWT Basics

1,605 views

Published on

Google Web Toolkit Basics

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,605
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
42
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

GWT Basics

  1. 1. Beginning our journey towards Google’snew tool.
  2. 2. Google Web Toolkit (GWT) is a Java to JavaScriptcross-compiler.It takes Java code and compiles it into JavaScriptversions for all the major browsers in a singlecompilation step.GWT is hence statically compiled strongly typedJava language.GWT includes debugging Java bytecode in asimulated browser environment, set of core UIand layout widgets, RPC system for handlingweb server communications andinternationalization support.
  3. 3. GWT allows the client to maintain state andeven perform computations locally, with a fulldata model, without requiring a trip to theserver for every update to the interface.GWT also provides a rich platform in terms of awide variety of UI elements and capabilities:sliders, reflections, drag-and-dropsupport, suggest boxes and data-bound tables.GWT is not a framework itself but basis for theapplication framework.GWT provides the components required for Ajaxapplications.
  4. 4. GWT Java compiler takes Java code andcompiles it into JavaScript.By defining GWT compile tasks into modules,the compiler can perform more analysis on thecode as it’s processed, and branch into multiplecompilation artifacts for different outputtargets.During compilation one can specify differingimplementations based on known parameters,such as user agent or client browser.
  5. 5. It enables to implement UI elements in Java andthen using a browser-specific implementation ofthe core DOM to build out the native browserelements as needed by the higher-level Javalayer.GWT UI layer provides a wide variety of layout-related panels, data representation constructssuch as Tree and Grid, and a set of user inputelements.It also provides new optimized UI elements thatdraw from the power of the plugin-capablecompiler, such as the ImageBundle.
  6. 6. The RPC system allows for serialization anddeserialization of Java objects from server-sideimplementations of remote services, which can thenbe called asynchronously from the client.The compiler generates code during the compilationstep to handle the serialization at a low level.Serialized objects are versioned and mapped atcompile time providing two major advantages:1) The client and server agreement can beguaranteed as new versions are deployed.2) The server implementation can compress thestate of Java objects down to arrays of JavaScriptprimitives.
  7. 7. Additional utilities include support foradditional ways to communicate with servers,internationalization (i18n) tools, a historymanagement system, and testing support.GWT provides several client-side libraries forgoing beyond the standard GWT RPC andinstead communicating with XML and JSON-based services.GWT includes compile-time-checkedinternationalization library, history managementsystem for bookmarking and deep linking, and aformal testing support.
  8. 8. The GWT shell allows developers to test theirapplication in a browser while executing thenative Java bytecode.It gives the ability to use all the other Java toolsto inspect the application, includingprofilers, step-through debugging, and JTI-based monitors.The hosted mode browser, with an embeddedApache Tomcat server makes possible to testthe compiled JavaScript with Junit.
  9. 9. GWT projects are defined in terms of modules,composed of resources, configuration, andsource.The module configuration defines compile-timeinformation about a project and specifiesresources needed at runtime.The modules also make possible a richinheritance mechanism.A module defines the starting point of theproject which is known as entry point.
  10. 10. Entry point classes are coded in Java and arereferenced by a module definition and compiledto JavaScript.Modules themselves and the entry points theydefine, are invoked through a <script> referenceon an HTML page, known as a host page.Host pages invoke GWT projects and also supporta few special <meta> tags that can be used totweak things.The three main components of a GWT projectare: a module configuration file, an entry pointclass, and an HTML host page.
  11. 11. The GWT module system allows applicationcomponents to package the client-side applicationcode, server-side service implementations, and assetssuch as graphics or CSS file into an easilyredistributable package.A module is defined by an XML file packaged with theJava source implementing the module.Typical XML file declares primary elements as:inherited modules, servlet deployments, compilerplugins, and entry points.The <inherits> tag tells GWT to inherit the core moduleInheriting a module brings in all the elements of themodule, not just source code.
  12. 12. The package folder (For example, com.manning)-> Module.gwt.xml (The module definition file)-> client: The client package containing codethat will be crosscompiled to JavaScript-> public: Folder containing assets used by themodule (images, CSS files, other resources)-> server: The package containing server-sideimplementation code-> rebind: The package containing compile-time code (generators)
  13. 13. The HTML host page contains a couple of specialelements needed to activate a GWT application.First is a reference to a bootstrap (nocache) JavaScript filegenerated for every module.The nocache file detects the appropriate version of theapplication module, based on the user agent and otherfactors, and loads up the monolithically compiledapplication.The *.nocache.js and *-xs.nocache.js are two files sendto the client without HTTP-level caching enabled.All other files generated by GWT are named based on ahash of the source code.The two nocache files determine which hashed version tobe loaded when the page is requested.
  14. 14. The cross-site xs version of the nocache file isused by other domains that includes theapplication.It allows remote domains (even from differenthost) to communicate with the server-sideresources.When a module nocache script (either standardor cross-site) is loaded from a host page, theremainder of the GWT bootstrap process isinvoked and an entry point class is loaded.
  15. 15. An entry point class is a simple client-side class thatimplements the com.google.gwt.core.client.EntryPointinterface, which defines a single method:onModuleLoad().The GWT’s RootPanel class enables application to accessthe HTML host page.Calling RootPanel.get() returns a default container thatis inserted just before the ending </body> tag in theHTML page.public class Calculator implements EntryPoint {public void onModuleLoad() {RootPanel.get().add(newCalWidget("calculator"));} }
  16. 16. The shell is composed of three main parts: alogging console, an embedded Tomcatserver, and the hosted mode browser.The GWT shell console provides an enhancedlogging interface and centralized GUI as a GWTdashboard.The hosted mode browser is capable of invokingJava classes directly on browser events, ratherthan requiring a compilation to JavaScript; thususing a standard Java debugger to work with theAjax code, instead of relying solely on compiledJavaScript for testing and interaction.
  17. 17. GWT Shell Description-port Runs an embedded Tomcat instance on the specified port (defaults to8888).-noserver Prevents the embedded Tomcat server from running, even if a port isspecified.-whitelist Allows the user to browse URLs that match the specified regularexpressions (comma or space separated).-blacklist Prevents the user from browsing URLs that match the specified regularexpressions (comma or space separated).-logLevel The logging level: ERROR, WARN, INFO, TRACE, DEBUG, SPAM, or ALL.-gen The directory into which generated files will be written for review.-out The directory to which output files will be written (defaults to current).-style Script output style: OBF[uscated], PRETTY, or DETAILED (defaults to OBF).url Launches the specified URL automatically.
  18. 18. The GWT shell console is a hierarchical logging display.Log Level DescriptionERROR Shows only critical errors in the GWT shell code.WARN Shows uncaught exceptions in user code. WARN and ERROR informationare displayed in red in the shell window.INFO Shows server startup info and invocations into specific GWT modules.This mode is displayed by default simply as“Starting HTTP on port 8888.”TRACE Shows each request logged, as well as module instantiations, theirlocations on the class path, and the time. Displayed in gray in the shell.DEBUG Shows the binding of classes inside the GWT shell for code invocationsand URL mapping. It is displayed in green in the shell window.SPAM Shows all ClassLoader events and invocations to native JavaScript. It isdisplayed in teal in the shell windowALL Shows all logging information.
  19. 19. It operates as a test browser harness that directlyinvokes Java binary code in response to the browserevents.It allows to view code changes immediately and toperform step-through debugging of code betweenthe client and server sides.The hosted mode browser also provides a shortcutfor executing the compiled JavaScript version of theapplication using the Compile/Browse button withGWT_EXTERNAL_BROWSER defined in environment.The hosted mode browser can be used apart fromthe GWT shell’s Tomcat instance with the -noserveroption.
  20. 20. The GWT compiler is a Java source to JavaScriptsource translator.The GWT compiler optimizes the application atcompile time by compressing javascript namingand pruning unused classes.GWT examines code and only providesserialization for the classes were explicitlyneeded.GWTCompiler [-logLevel level] [-gen dir] [-outdir] [-treeLogger] [-style style] module
  21. 21. Option Description-logLevel The logging level (during compliation): ERROR, WARN,INFO, TRACE, DEBUG, SPAM, or ALL.-gen The directory into which generated files will be writtenfor review.-out The directory to which output files will be written(defaults to the current directory).-treeLogger Logs output in a graphical tree view (hierarchical logginginformation).-style The script output style: OBF[uscated], PRETTY, orDETAILED (defaults to OBF).module The name of the module to compile.
  22. 22. The –style command-line option for the GWTcomplier is used to control the generatedJavaScript.OBF—Obfuscated mode. This is a non-human-readable, compressed version suitable forproduction use. Names are compressed andwhitespaces are cleaned.PRETTY—Pretty-printed JavaScript withmeaningful names, while collisions are resolvedwith suffixes.DETAILED—Pretty-printed JavaScript with fullyqualified names (for both class and methods).
  23. 23. GWT interacts with native JavaScript, through theJavaScript Native Interface (JSNI).The names of the classes and methods in their JavaScriptform aren’t guaranteed, even for different compilations ofthe same application.The special syntax with JSNI enables invocationof, Javascript objects from java code and compiled Javaclasses from within JavaScript, has following limitations.When JavaScript API is exposed for external use, thereferences should be created for calls into GWT code usingJSNI registrations.The Javascript naming in the object hash is unreliable sincethe method names are not reliable.Potential conflicts can occur with javascript libraries whilepublishing using PRETTY setting.
  24. 24. The GWT compiler is currently limited to J2SE1.4 syntactical structures.GWT JRE emulation library supports limitedsubset of Java classes.The GWT compiler helps by optimizing theJavaScript it emits to include only classes andmethods that are on the execution stack of themodule and by using native browser functionswherever possible.
  25. 25. The compiler identifies which combinations of GWTmodule definition files need to be built.GWT builds specific versions of theapplication, each exactly targeted to the needs ofthe client (user agent, locale, so on).A particular build combination is defined in theGWT module definition using a <defineproperty>tag.Each of the build combination is processed as abuild of the final JavaScript emitted by GWT.GWT can switch implementations of classes basedon properties using the <replace-with> tag in themodule definition.
  26. 26. The JavaScript snippet contained within the <property-provider> tag determines which of theimplementations defined will be used when GWTstarts.The basic DOM class is implemented with the sameinterface for each of the browsers, providing a core setof operations on which cross-platform code can easilybe written.The DOM object is a singleton exposing static methodsthat are called by applications, like GWT.create().The technique of identifying build combinations andthen spinning off into specific implementations duringthe compile process is known as deferred binding.
  27. 27. Each variation or axis added becomes acombinatory compile.GWT generates any client-side code using thegenerator metaprogramming model.GWT’s compiler includes a code generation ormetaprogramming facility that allows to generatecode based on module properties at compile time.The i18n (internationalization) module definesseveral no-method interfaces which can beextended to define Constants, Messages, orDictionary classes using the <extend-property>tag.
  28. 28. In order to integrate existing JavaScript or extend oradd lower-level components, GWT includes JSNI .It allows to define method implementations on a Javaclass using JavaScript.The javascript implementation lives right in the Javafile, surrounded by a special /*- -*/ comment syntax.GWT takes all the Java files, whether provided orgenerated, and the JSNI methodimplementations, and examines the call tree, pruningunused methods and attributes.Then it transforms all of this into a number of uniqueJavaScript files, targeted very specifically at eachneeded axis.
  29. 29. ApplicationCreator is provided by GWT to create thedefault starting points and layout for a GWT project.It supports command-line params as:ApplicationCreator [-eclipse projectName] [-out dir][-overwrite] [-ignore] classNameParameter Description-eclipse Creates a debug launch configuration for the named eclipse project.-out The directory to which output files will be written (defaults to thecurrent directory).-overwrite Overwrites any existing files.-ignore Ignores any existing files; does not overwrite.className The fully qualified name of the application class to be created.
  30. 30. The package name is represented in the structureas a series of subdirectories in the src tree, withseparate client and public subdirectories within.The client directory (source path) is intended forresources that will be compiled into JavaScript.The client items are translatable, orserializable, and will ultimately be downloaded to aclient browser.The public directory (public path) denotes files thatwill also be distributed to the client, but that do notrequire compilation and translation to JavaScriptwhich includes CSS, images, static HTML etc.
  31. 31. Along with the module definition, entrypoint, and host page, shortcut scripts listedbelow are also needed for a GWT project.File Name PurposeGWT module file ProjectName.gwt.xml Defines the project configurationEntry point class ProjectName.java Starting class invoked by themodule.Host page ProjectName.html Initial HTML page that loadsthe module.GWTShell shortcutinvoker scriptProjectName-shell.sh Invokes GWTShell for the project.GWTCompiler shortcutinvoker scriptProjectName-compile.sh Invokes GWTCompiler forthe project.
  32. 32. A host page is initial HTML page that invokes a GWT application.A host page contains a script tag that references a special GWTJavaScript file, Module.nocache.js which kicks off the GWTapplication loading process.Meta tag Syntax Purposegwt:module <meta name="gwt:module"content="_module-name_">Specifies the module to be loaded (preGWT 1.4).gwt:property <meta name="gwt:property"content="_name_=_value_">Statically defines a deferred bindingclient property.gwt:onPropertyErrorFn <metaname="gwt:onPropertyErrorFn" content="_fnName_">Specifies the name of a function to callif a client property is set to an invalidvalue (i.e. no matching compilation willbe found).Specifies the name of a function to callif an exception happens duringbootstrapping or if a module throws anexception out of onModuleLoad();function takes a message parameter.gwt:onLoadErrorFn <metaname="gwt:onLoadErrorFn"content="_fnName_">
  33. 33. Modules are execution units which enable to separatethe discreet areas of responsibility.Modules enable setting of configuration andproperties, provide resources for projects, enableinheritance, give the compiler hints, and play a centralrole in the bootstrapping process.The Module.gwt.xml is a module descriptor for theproject at the top-level and, provides a means todefine resource locations and structure.A default generated module file contains <inherits>element which includes the configuration for anothernamed GWT module in the current definition, and<entry-point> element which defines a class that kicksthings off and moves from configuration to code.
  34. 34. Module element Description<inherits> Identifies additional GWT modules that should be inherited into the currentmodule.<entry-point> Specifies which EntryPoint class should be invoked when starting a project.<source> Identifies where the source code that should be translated into JavaScript bythe GWT compiler is located.<public> Identifies where assets that are not translatable source code, such as imagesand CSS files, are located.<script> Injects a script element into a GWT module, ensuring it is presentwhen inherited.<stylesheet> Injects a stylesheet into a GWT module, ensuring it is present when inherited<servlet> Specifies the path to GWT RPC Service Servlet resources.<define-property> Initially defines properties.<set-property> Sets property values; for example, it is used in the UserAgent module todefine the set of supported browsers.<extend-property> Specifies property value extensions; often used to specify locale information.<replace-with> Replaces components at runtime based on a decision process, such asdifferent implementations for different browser versions.
  35. 35. An entry point class is the first project-specificcode invoked by the GWT application.Entry point is were the first browser-basedelement is accessed by the staticRootPanel.get() method.The RootPanel is a default container that isinserted directly after the HTML body tag.With the RootPanel as the reference, otherelements can be inserted into the project.
  36. 36. The model should be completely unaware of the viewand controller, and the pattern can be applied on manydifferent levels within an application.In MVC, the model can be equipped to alert observersof changes within it, using the Observer pattern.The model is reusable part and does not update orhave any direct knowledge of the view.The view typically has a reference to thecontroller, while the controller has no direct referencesback to the view, and simply updates the model.MVC can be applied with GWT, and it can happen onmany different levels, with individual widgets havingtheir own encapsulated MVC.
  37. 37. In MVC, widgets begin with the view elements,starting with the layout.Widgets are built from layout panels, inputelements, events, data objects, and variouscombinations.Widgets are capable of being inserted orremoved from the screen, in a single page, onthe client side.A ClickListener when attached to the button,gets the control when the buttons are clicked,and it invokes a controller method.
  38. 38. import com.google.gwt.user.client.ui.Button;import com.google.gwt.user.client.ui.ClickListener;import com.google.gwt.user.client.ui.Grid;import com.google.gwt.user.client.ui.TextBox;import com.google.gwt.user.client.ui.VerticalPanel;public class CalculatorWidget extends VerticalPanel {private TextBox display;public CalculatorWidget(final String title) {super();final CalculatorData data = new CalculatorData();final CalculatorController controller =new CalculatorController(data);}
  39. 39. VerticalPanel p = new VerticalPanel();p.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);p.setStyleName(CalculatorConstants.STYLE_PANEL);Grid g = new Grid(4, 5); // rows and columns gridg.setStyleName(CalculatorConstants.STYLE_GRID);final Button zero = new ButtonDigit(controller, "0"); // extends Button classg.setWidget(3, 0, zero); …. // more digit buttonsfinal Button divide = new ButtonOperator(controller, newOperatorDivide()); // ButtonOperator extends Button class and implements ClickListenerg.setWidget(0, 3, divide); …. // more operation buttonsfinal Button clear = new Button(CalculatorConstants.CLEAR);clear.addClickListener(new ClickListener() {public void onClick(Widget sender) { controller.processClear(); }});clear.setStyleName(CalculatorConstants.STYLE_BUTTON);g.setWidget(2, 4, clear);
  40. 40. // . . .display = new TextBox();data.addChangeListener(new CalculatorChangeListener() { // observer/observable relationshippublic void onChange(CalculatorData data) {display.setText(String.valueOf(data.getDisplay()));}});display.setText("0");display.setTextAlignment(TextBox.ALIGN_RIGHT);p.add(display); p.add(g); this.add(p);}}
  41. 41. public interface CalculatorChangeListener { public void onChange(CalculatorData data); }public interface CalculatorChangeNotifier {public void addChangeListener(final CalculatorChangeListener listener);}public class CalculatorData implements CalculatorChangeNotifier {private String display;private double buffer;private boolean initDisplay;private boolean lastOpEquals;private CalculatorChangeListener listener;public CalculatorData() { this.clear(); }public void addChangeListener(final CalculatorChangeListener listener) { this.listener = listener; }public void clear() {this.display = "0"; this.buffer = 0.0;this.initDisplay = true; this.lastOpEquals = false;if (listener != null) listener.onChange(this);}public double getBuffer() { return buffer; }public void setBuffer(double buffer) { this.buffer = buffer; listener.onChange(this); }public String getDisplay() { return display; }public void setDisplay(String display) { this.display = display; listener.onChange(this); }
  42. 42. ButtonDigit is extension of the GWT Button class and includes aCalculatorController object reference in its constructorIt invokes the controller’s processDigit() method each time aButtonDigit instance is clicked, achieved via a ClickListener.public class ButtonDigit extends Button {public ButtonDigit(final CalculatorController controller,final String label) {super(label);this.addClickListener(new ClickListener() {public void onClick(Widget sender) { controller.processDigit(label);}});this.setStyleName(CalculatorConstants.STYLE_BUTTON_DIGIT);}}
  43. 43. ButtonOperator has a model, represented by the label; aview, managed by the parent class of Button, and a controller layerrepresented by an AbstractOperator instance, which translates actionsup to the larger scope controller for the calculator widget.public class ButtonOperator extends Button {public ButtonOperator(final CalculatorController controller,final AbstractOperator op) {super(op.label);this.addClickListener(new ClickListener() {public void onClick(Widget sender) {controller.processOperator(op); }});this.setStyleName(CalculatorConstants.STYLE_BUTTON_OPERATOR);}}
  44. 44. The controller handles the interaction betweenvarious components.The controller is called upon by the variouscomponents (buttons) to perform actions suchas invoking an operation or manipulating themodel or internal state.GWT allows to create custome UI and classes forany logic and data representations, which endup in the client browser as completely non-view-related items.
  45. 45. public class CalculatorController {CalculatorData data;AbstractOperator lastOperator;Private double prevBuffer;public CalculatorController(final CalculatorData data) { this.data = data; }public void processClear() { data.clear(); lastOperator = null; }public void processEquals() { … } // set display data to CalculatorData Bufferpublic void processOperator(final AbstractOperator op) {if (op instanceof BinaryOperator) {if ((lastOperator == null) || (data.isLastOpEquals())) {data.setBuffer(Double.parseDouble(data.getDisplay()));data.setInitDisplay(true);} else { lastOperator.operate(data); }lastOperator = op;} else if (op instanceof UnaryOperator) { op.operate(data); }data.setLastOpEquals(false); }public void processDigit(final String s) { … } // operation when digit button is clicked}
  46. 46. CSS and other resources can be defined and injected throughGWT module configuration (i.e. Calculator.gwt.xml module file).<stylesheet src=com. gwtip.calculator.style.css/>The public path defaults to the public subdirectory of the sourcetree, and resources are copied to output folder of the projectwhen compiled and deployed.The setStyleName() (addStyleName()) method is used to connecta style name to a UI component.Also a limited individual style attributes can be set using methodslike setVisible(), setHeight(), and setWidth().Invoke com.google.gwt.dev.GWTShell with the followingcommand-line options, to force the GWT shell to delay startupuntil a debugger has connected:-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,address=8888,suspend=y
  47. 47. GWT enables client applications to communicate withserver resources through its own RPC and object-serialization mechanism.The communication process involves implementationof GWT service interface and sending/receiving specialGWT serialized data.GWT optimizes the translation of data from Java toJavaScript and vice versa during communication.The native mechanism for GWT client-servercommunication is GWT RPC, but it also supports plainXML over HTTP (POX), or JSON.
  48. 48. The GWT ProjectCreator utility is used to makeEclipse project files.ProjectCreator [-ant projectName] [-eclipseprojectName] [-out dir] [-overwrite] [-ignore]Parameter Description-ant Generates an Ant build file to compile source (.ant.xml will beappended).-eclipse Generates an Eclipse project.-out The directory to which output files will be written (defaults to thecurrent directory).-overwrite Overwrites any existing files.-ignore Ignores any existing files; does not overwrite them.
  49. 49. The Data class must be marked with either thecom.google.gwt.user.client.rpc.IsSerializable or thejava.io.Serializable interface.GWT honors the transient modifier on classproperties, allowing them to be omitted if they arenot themselves serializable.IsSerializable implementations should declare a no-arguments constructor.In GWT1.4, the Java serialization protocol isexplicitly not supported.Both IsSerializable or Serializable can be usedsynonymously.
  50. 50. 85

×