• Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. GETTY IMAGES 36 BETTER SOFTWARE OCTOBER 2008 www.StickyMinds.com
  • 2. “W eb 2.0 is the future! guage and set of libraries, so there’s a I need you to build lot of context switching to be done. And us a new Web front we haven’t even considered the hardest end for our site. It part—the application’s real business should use all the slick animations, auto- logic! suggest, and desktop-like features that Ajax is short for asynchronous are the standard these days. It will need JavaScript with XML. Ajax applications to be fast, and it has to work with In- are highly responsive and feel more like ternet Explorer, Firefox, and Safari so desktop clients than traditional, form- we can support all our customers. How based Web pages. The fundamental dif- soon can you be done?” ference between standard Web sites and Rachel broke out into a sweat re- Ajax applications is that standard Web membering her boss’s request. She had sites deliver all their data in a single page a lot of experience programming in Java load, whereas Ajax applications may and was a whiz at refactoring using Java make several requests for data while the IDEs—but Ajax? She was pretty sure application is running and a single page that required knowing JavaScript and is displayed. Data is delivered asynchro- understanding the subtle quirks of all nously, which means the user may con- the popular browsers. How would she tinue to use an application while waiting get through this? for data from the server. This means Then Rachel remembered hearing the server components need only send about the Google Web Toolkit, which the raw data and let the Web browser promised that you could build Ajax handle all the formatting and presenta- applications using Java instead of tion logic. JavaScript and that it would handle all Google has created an innovative the complicated cross-browser issues au- tool to aid Ajax developers: the Google tomatically. She downloaded the Google Web Toolkit (GWT). GWT compiles Web Toolkit distribution, fired up her Java source code into browser-friendly Java IDE, and started writing ... JavaScript. This means you can use Building Ajax applications can be your favorite Java IDEs, design patterns, tricky—just as juggling chainsaws while and tools such as JUnit, FindBugs, and taming angry lions can be tricky. PMD to create Web 2.0 applications. Ajax application code is written in GWT includes a rich component library JavaScript, which then runs in a Web of user interface widgets, remote server browser. A public Web site must support communication protocols, and an emu- multiple versions of multiple browsers lated Java Runtime library, which maps (Internet Explorer 5, 6, and 7; Firefox; Java types to JavaScript types—all of Opera; and Safari), each with its own which work seamlessly across the major differences and idiosyncrasies. A de- browsers. Furthermore, you can debug veloper has the difficult task of writing GWT applications using a standard Java JavaScript that safely manipulates the IDE. These features let you focus on Document Object Model (DOM) in a writing your application instead of wor- way that behaves identically on all sup- rying about browser compatibility prob- ported browsers. Of course, code on the lems. Using GWT is like having a team- server side usually uses a different lan- mate who knows about all the different // This is a Java method public int add(int x, int y) { return x + y; } // This is a JavaScript method public native void alert(String msg) /*-{ $wnd.alert(msg); }-*/; Listing 1 www.StickyMinds.com OCTOBER 2008 BETTER SOFTWARE 37
  • 3. in hosted mode, the GWT development kit includes an embedded browser in- stance of Internet Explorer for Win- dows, Firefox for Linux, and Safari for Mac. Hosted mode is really useful, and you’ll probably end up using it for most of your development work with GWT. For example, you can run your appli- cation, change the source code, and hit the browser’s refresh button to see your changes immediately. Hosted mode also provides a console window that you can use to log debug messages during devel- opment. You can write unit tests with JUnit just as you would for server-side code. However, when you need to test applica- Figure 1: Hosted mode runs applications as Java bytecode and enables debugging using Java tions that manipulate the DOM or use IDEs. JavaScript, GWT can run your unit tests browser incompatibilities and handles generated JavaScript source file size. The inside the same hosted-mode browser them for you. GWT compiler can replace many levels you use for developing applications. If of delegation with inline method calls, you subclass GWTTestCase instead of Java to JavaScript Compiler which can yield code that’s as fast as the JUnit standard TestCase, your test What makes GWT unique is its code that has been hand-optimized. This will run in an invisible browser with Java-to-JavaScript compiler. You write means you can focus on writing well- access to the DOM. You can run these plain old Java code and invoke GWT’s factored, object-oriented code instead of tests as compiled Java bytecode or as compiler, which takes Java source files obsessing about performance tweaks. JavaScript to ensure your application be- and outputs JavaScript. This is a true Ajax applications should be fast and haves correctly after being compiled. compiler—not a simple text transfor- responsive, which means minimizing ini- mation step like Ruby on Rails’ RJS, tial page load time. One way to do this Component Libraries which provides Ruby objects that use is to simply send less JavaScript code GWT includes a rich set of class li- String manipulation to create JavaScript from the server to the client. The GWT braries and user interface widgets. A output. While Java is the preferred lan- compiler can create compact, obfuscated subset of the core Java SE libraries is guage for writing GWT applications, it JavaScript optimized for short download emulated by GWT, which means you doesn’t mean that you have to give up time or human-readable code, which is can use most of the core language data using JavaScript. You may mix Java useful when diagnosing problems. In types and collections. GWT also pro- and JavaScript code in the same class addition, GWT analyzes your entire vides a rich set of browser widgets as with GWT’s JavaScript Native Interface application and only includes the code well as utilities for supporting multiple (JSNI) [1] by using the native key- that is actually used. Practically, this languages and a way to handle the word. means that you can reuse existing Java browser’s back and forward buttons. Listing 1 demonstrates a Java class libraries and other modules, and GWT with a native JavaScript instance method. will compile only the routines you actu- Widgets and UI Components You can pass objects back and forth ally invoke. This optimization comes at As figure 2 shows, Google provides across the Java/JavaScript boundary a price; you can’t use reflection in your many widgets with GWT—from simple, and generally treat the code as if it were code since GWT can’t tell ahead of time standard HTML widgets like buttons all part of the same object. Using Java what methods are really invoked. and text fields to rich widgets com- as much as possible to ensure browser posed of simpler elements like a tree portability is a best practice, as it lever- Debugging and Testing view. Simple widgets such as Button, ages all the GWT safety features, such as Some problems are easiest to diag- Checkbox, Hyperlink, and TextField preventing memory leaks. However, if nose with a debugger, and GWT makes provide simple wrappers around basic you need it, you can always write JSNI debugging easy, as shown in figure 1. HTML-form elements and are used for methods. Simply start up your application in the majority of form-based data input. “hosted mode,” which runs your ap- For more dynamic interfaces, GWT of- Optimizations plication using Java bytecode instead of fers a rich set of widgets including: Tab- Another benefit of using a compiler JavaScript. This means you can use your Panel for navigating through a tabbed is that it allows for compiler optimiza- Java IDE’s debugger just as you would set of pages; SuggestBox for a text entry tions both in terms of performance and for server-side code. To run applications field, which lists possible completions 38 BETTER SOFTWARE OCTOBER 2008 www.StickyMinds.com
  • 4. formatted for display in a given locale by using the DateTimeFormat and Num- berFormat classes. Back Button and Browser History One of the most difficult issues in writing Ajax applications is handling the browser’s back button. An Ajax applica- tion is usually a single page that requests new data from the server without navi- gating to another page. Since browsers track navigation history by full-page loads, handling the back button is tricky. For example, consider working with the Ajax-heavy Google Maps site: A user navigates to Google Maps from the Google start page then searches for the closest pizzeria. The user finds several results and clicks through a few choices to view their details. When the user hits the back button, he expects to go to the previously viewed pizzeria—not back to the Google start page. GWT also provides a history mecha- nism for creating applications that re- spond predictably to the back and for- ward buttons. This mechanism relies on a common JavaScript trick that uses an IFRAME HTML element to generate page history. All you need to do for your application is add an IFRAME element to your page and let GWT handle all the Figure 2: GWT provides many widgets from simple buttons to tabbed menus and dialog boxes. JavaScript tricks for you. In your appli- cation, you tell GWT when to add an as you type (think Google Suggest); and have a problem where select boxes ap- entry into the browser history, such as DialogBox for dragable popup win- pear through any covering popup win- clicking a link or button. When the user dows. dows? GWT prevents this display glitch presses the back button, your applica- GWT applications use an event- by applying a well-used fix that cre- tion will be notified and you can change based programming model, where each ates IFRAMEs that sit directly between your page as needed. button, text field, and other user inter- the select box and the popup window. face element responds to a set of actions Did you know that Internet Explorer Remote Server such as clicks, content changes, and propagates events through the docu- Communication focus changes. This programming model ment model differently from all other Ajax applications wouldn’t be very will be familiar to developers who have browsers? By using GWT’s event classes, interesting if they didn’t have access written Swing desktop applications. In you never need to know about or deal to data. GWT provides a number of fact, GWT code looks similar to Swing with the differences. ways to access data on remote servers, code. You add behavior to your widgets including a custom protocol that lets by adding event listeners that respond to Internationalization Support you easily use your server-side objects user interactions. For example, listing GWT’s built-in internationalization directly in the browser. To access data 2 shows how you define a button that features can help you build a multi- services from other applications, GWT prints a message every time you click it. language site. Your application’s text also supports standard data interchange By building your applications using and messages can be extracted into a formats like JSON and XML. GWT widgets and the event-based separate property file for each supported programming model, you let GWT language. GWT will then compile these Using Server Objects on the handle the complex differences between property files and generate separate ver- Client with GWT RPC browsers. For example, did you know sions of your Web application for each If you’re building both the server side that Internet Explorer versions 5 and 6 language. Dates and currencies can be and the client side of a GWT application, www.StickyMinds.com OCTOBER 2008 BETTER SOFTWARE 39
  • 5. Button button = new Button(“Click Me”); Google also publishes additional libraries for GWT. It wouldn’t be a button.addClickListener(new ClickListener() { Google project if you couldn’t access the public void onClick(Widget sender) { Google online services, and the Google Window.alert(“I was clicked!”); API Libraries for GWT project does just } that: You get access to Maps, Search, of- }); fline functionality with Gears, and the multi-platform Google Gadgets library Listing 2 for desktop and Web widgets. In the then you’ll get a big productivity boost Web services and is easily read by hu- eating-their-own-dog-food category, the by using GWT’s Remote Procedure Call mans and browsers; in fact, it’s a valid gwt-api-interop library was used with (RPC) feature. This mechanism allows JavaScript object, as shown in listing 3. GWT to help build the iPhone Google you to use your server-side objects di- Reader application. It provides a way rectly on the client side. Consider what JavaScript and GWT Third- to bind JavaScript objects to Java ob- would be required to use a plain-text Party Libraries jects, which means you can bind JSON format: You’d fetch the required data on Successful development platforms to Java objects without writing a parser the server side, write code to turn your have a rich community of third-party by hand. objects into a text representation, send libraries, and GWT can use both this text to the client, then write code on JavaScript and other GWT libraries. The Real World the client that can parse and interpret the Since GWT applications are always The story at the beginning of this message. With GWT RPC you can skip deployed as JavaScript, you can easily article isn’t pure fiction; a similar situa- writing extra encoding and decoding use other JavaScript libraries. This means tion happened to me on a recent project. layers and start actually using the data.you can use any existing JavaScript code My team was hired to build the front To use the GWT RPC feature, you your company may have developed, as end to a new site, and we had used can use GWT’s servlet-based RPC well as popular third-party tools, such GWT previously. We had to support the framework for new applications or use as the animation framework Scriptacu- major browsers on Windows and Mac the RPC libraries directly with your ex- lous and other application frameworks and deal with requirements that were isting Web application frameworks, such like ExtJS. You’ll need to write native evolving throughout the four-month as Spring and Struts. JavaScript code, which acts as a bridge project. GWT allowed us to use our Java between your Java and experience with test-driven development {“widget”: { JavaScript code. How- and refactoring to keep our design clean “debug”: “on”, ever, many folks have al- and deliver on time. We started with two “window”: { ready done this work for full-time developers and scaled up to “title”: “Sample Widget”, you and published these four, then six—including two new hires. “name”: “main_window”, bridges as GWT libraries. GWT’s simple programming model “width”: 500, In addition to made this an ideal first project, as the “height”: 250 JavaScript library wrap- team spent more time focusing on the }, pers, there are many business rules than learning APIs. “flags”: [ 1, 8, 16 ] useful open source com- The next article in this series will }} ponents made specifically focus on testing and GWT, including for GWT. GWT-Maven how to build Ajax applications test-first Listing 3 provides support for the to help create simpler, defect-free de- Communicating with Other Back popular Maven build tool to build and signs. {end} Ends with HTTP, JSON, and XML package GWT applications. Gwittir of- reFerenceS: Just because GWT client-side code fers an alternative to reflection to pro- 1] “JavaScript Native Interface (JSNI)” in the is written in Java doesn’t mean that the vide simple JavaBean-style introspection Google Web Toolkit online documentation. code. server must be Java as well. The Re- that can be used for data binding and google.com/webtoolkit/documentation/. questBuilder class can be used to com- validation. Popular server-side frame- municate with any back end: Python, C#, works are made GWT-friendly through Sticky or any language that can speak HTTP. projects like Hibernate4gwt, which al- Notes If you aren’t using GWT RPC in Java lows you to use Hibernate objects easily or have a server back end in another in your client code, and GWT-SL, a For more on the following topics go to www.StickyMinds.com/bettersoftware. language, GWT supports the standard server-side library that provides Spring n More information XML and the JavaScript Object Nota- framework support. Check out the n Other Ajax framework options tion (JSON) data interchange formats. GWT Google Group for discussions and JSON has been gaining popularity in announcements of other tools. 40 BETTER SOFTWARE OCTOBER 2008 www.StickyMinds.com