<<

PROGRAMMING Web Toolkit www.fotolia.de, Timothy Large

Creating dynamic web applications with the GOOGLE TOOLS

The Google Web Toolkit lets you develop complex web applications and Javascript implementations of in Java and automatically converts them to apps. standard classes such as java.lang, and java.util. Besides this, the framework BY RAMON WARTALA modifies the Javascript code to suit pop- ular web browsers like Mozilla, , Internet Explorer, , and . oogle is more than just a search with some help from Javascript and engine. This vast and rapidly ex- XML, are currently the buzzwords Getting Started Gpanding company is also a major among web developers. AJAX toolkits The 22 Mbyte gwt--1.0.21.tar.gz center for development. Be- for programming languages such as package includes documentation and sides programs such as Google Desktop [3], Ruby, and PHP are becoming ever- five sample applications, ranging from a and , the company also re- more popular. But Google has ventured trivial Hello program, through a widget leases other web-based products once a into new territory with their Java-based overview, to a small email application quarter. While Google Mail is enjoying framework. Java simply serves as a gen- the limelight, new applications such as erator and test language, as AJAX uses Listing 1: Postgresql Table , , or Javascript client-side. for MyAddress Google Spreadsheet have attracted very But why Java? The main reason is sim- 01 CREATE TABLE myaddress."names" little attention. These lesser known ap- ple bug hunting. GWT gives developers plications share the of their the ability to run and test an AJAX appli- 02 ( more popular counterparts, and they use cation in what’s known as hosted mode. 03 id serial NOT NULL, AJAX for quick and easy client access. This means running a Java version of 04 firstname varchar(50) NOT Although many suspected Google had the application within a standard Java NULL, its own framework running under the Virtual Machine. can use 05 lastname varchar(100) NOT hood, there was no way of knowing for their preferred development environ- NULL, sure until recently. But Google finally ments and debuggers. confirmed the suspicions at the Java One After the application is finished, it is 06 email varchar(128) NOT NULL, Fair in May of this year by putting the compiled into Javascript. The HTML and 07 CONSTRAINT id PRIMARY KEY Google Web Toolkit (GWT) up for grabs Javascript code created by this process (id) as a free download [1]. can be installed on a web , where 08 ) it runs in web mode. The component ar- 09 WITHOUT OIDS; What’s in the Box? chitecture of the GWT framework com- 10 ALTER TABLE myaddress."names" AJAX [2], the asynchronous processing prises a special web browser, a widget OWNER TO myaddress; of HTTP requests and responses, along class library for AJAX-based interfaces,

68 ISSUE 74 JANUARY 2007 WWW.LINUX - MAGAZINE.COM Google Web Toolkit PROGRAMMING

- specifies that we will be creating the project for the Eclipse IDE:

projectCreator U -eclipse Myaddress_GWT -out U myaddress_gwt

The applicationCreator command line tool creates the required classes, scripts, and configuration :

applicationCreator U -eclipse MyAddress_GWT -out U myaddress_gwt U de.wartala.client.MyAddress

After making sure you have all the re- quired files, you can import the GWT project into Eclipse by selecting Import | Figure 1: This email program is one of the sample applications intended to demonstrate the Existing Projects into Workspace in the capabilities of the Google Web Toolkit. (Figure 3). Within the project structure, I will be using the XML (see Figure 1). The applications can be The data exchange relies on the JSON configuration of a module as the entry launched using the shell scripts in the format (JavaScript Object Notation) [4]. point. applicationCreator has already application directories. In contrast to XML, JSON does not use created a module configuration with an The sample GWT application we will tagging, and thus generates less over- entry point, based on the required target be discussing in this article uses an ex- head. To retrieve the address for a family package (Listing 3). It references the isting server to query a simple address name from the using Rails, and Java class, which the application will database. To keep things simple, the to package the address in the JSON for- call when launched in hosted mode, and server will be based on , mat, all we need is the 10 lines in Listing is also found in the HTML file, which as the implementation only takes a few 2. Line 6 reads the family name from an implements the framework for the client lines of code – this has no effect on the HTTP request and finds the matching GUI. The most important lines here are client, of course. The finished version address in the database in Line 7. Line 8 the references to the module class and to can be downloaded at [9]. The My- converts the address to JSON format. the GWT Framework’s Javascript library: Address service developed specially for The ruby script\server start command this purpose is a simple database (see calls the MyAddress service. The internal ily names, and email addresses. service to listen on port 3000 on local- Listing 2: NameController server by entering http://localhost:3000/ name/ in a browser. Another advantage When the application is launched, it first 01 class NameController < of Ruby On Rails is that you can manage calls the onModuleLoad() method, ApplicationController the database via a generated input which generates the widgets provided by 02 :name (Figure 2). After entering a few records, the GUI library, before instantiating 03 def find_names_to_json query them in your browser at the fol- more classes: MyAddressRequester in our 04 # make sure not to send lowing URL: http://localhost:3000/name/ example. The application then sends re- but text/plain find_names_to_json?lastname=Name. quests to the MyAddress service, re- Now let’s start 05 @headers["Content-Type"] = developing the "text/plain; charset=utf-8" GWT project that 06 search_name = uses the web ser- @params['lastname'] vice. We can type 07 names = Name.find(:all, : projectCreator on conditions => ['lastname like the command line ?', search_name]) to create the proj- 08 render_text names.to_json ect frame for an 09 end application. The -out specifies the Figure 2: The in our example can provide records directly 10 end target directory; to the browser.

WWW.LINUX - MAGAZINE.COM ISSUE 74 JANUARY 2007 69 PROGRAMMING Google Web Toolkit

asynchronous HTTP request to the ser- vice, which passes the result to a matching response handler. JSONRe- sponseTextHandler, another inner class, implements the onCompletion() method, which is called when the Figure 3: The Google Web Toolkit can option- asynchronous HTTP ally create Eclipse project files, giving pro- request returns any grammers the ability to import them into results. the IDE as a project. As the service re- Figure 4: Ajax applications can be debugged using a special web turns a JSON object, browser in hosted mode. ceives the responses, and fills the GUI we first need to de- elements with them. code the object and break it down into a family name, the data returned by the The initializeMainForm() method gen- its component parts. JSONParser.parse service appears in the table. erates the interface, which is comprised (responseText) handles the task of of a search button, an input box, and decoding the object, and the method Hunting Bugs aFlexTable. initializeMainForm() then displayJSONObject() handles the latter The advantage of hosted mode becomes sets attributes and events, just like an step, delegating the chore to the method apparent if a program error occurs; it is AWT or the Swing interface. updateAddressTable(). The method easier to find a bug in the Java code than Our example only requires a single updateAddressTable() renders the results in the compiled Javascript. Setting the ClickEvent to trigger a click on Search. as a table, entering the values from the -eclipse parameter when calling project- The response for this event is imple- JSON response in the corresponding Creator creates a file with a .launch mented by the inner class, SearchButton- rows and columns. suffix besides the project-specific data. ClickListener. Now for the MyAddress-shell.sh com- Thanks to the parameters configured An onClick() event triggers the AJAX mand line script. Figure 4 shows the here, the application can be executed in part of the application and sends an front-end in hosted mode. After entering Eclipse and debugged with a little help from breakpoints and other techniques Listing 3: Client Entry Point Class (Figure 5). 01 import com.google.gwt.core.client.EntryPoint; 02 import com.google.gwt.user.client.ui.RootPanel; INFO 03 import com.google.gwt.user.client.ui.TabPanel; [1] Google Web Toolkit: http:// code. google. com/ webtoolkit 04 [2] AJAX: http:// en. wikipedia. org/ wiki/ 05 /** Ajax_%28programming%29 06 * Entry point classes define onModuleLoad(). [3] AJAX and Perl: http:// www. linux-mag- 07 */ azine. com/ issue/ 62/ Perl_AJAX. pdf 08 public class MyAddress implements EntryPoint { [4] JSON: http:// www. . org [5] GWT Widget Gallery: 09 http:// code. google. com/ webtoolkit/ 10 /** documentation/ com. google. gwt. doc. 11 * This is the entry point method. DeveloperGuide. UserInterface. WidgetGallery. html 12 */ [6] GWT Widget Library: 13 public void onModuleLoad() { http:// gwt-widget. sourceforge. net 14 TabPanel tp = new TabPanel(); [7] gwtPowered.org: 15 MyAddressRequester myJson = new MyAddressRequester(); http:// gwtpowered. org 16 tp.add(myJson.initializeMainForm() ,"Lastname"); [8] GWT group on : http:// groups. google. com/ group/ 17 tp.selectTab(0); Google-Web-Toolkit 18 RootPanel.get().add(tp); [9] Sample server and client from this ar- 19 } ticle: http:// www. linux-magazine. com/ 20 } Magazine/ Downloads/ 74/ gwt

70 ISSUE 74 JANUARY 2007 WWW.LINUX - MAGAZINE.COM Google Web Toolkit PROGRAMMING

In addition to supporting Eclipse- based debugging, the GWT framework also supports unit tests of its own classes. The GWTTestCase class is the entry point that implements JUnit inte- gration. The junitCreator command line tool generates all the required files, including the test class proper:

junitCreator.cmd -junit U eclipse/plugins/org.junit_3.8.1U /junit.jar -eclipse U myaddress_gwt2 -out U myaddress_gwt2 U de.wartala.myaddress.test.U MyAddressTest Figure 5: Eclipse Debug Mode speeds up bug hunting.

The files created here are used for test directory when you call junitCreator. and radio buttons, Layout Managers purposes in both hosted and web mode, cmd. (Panels) are particularly useful. Vertical- both in Eclipse and on the command Panel can help you aligning buttons line. If the application runs without an GWT and More vertically, for example. error, you can run the Project-compile.sh Of course, the Google Web Toolkit has GWT also gives developers the ability script to create a Javascript version of more potential than a simple example to design their own widgets; surf to [6] the Java application. can demonstrate. It has a total of 20 wid- and [7] for examples and howtos. The The script performs the tasks of copy- gets; the documentation gives you an framework has already attracted a lively ing and generating all required files to overview in the Widget Gallery [5]. Be- community that uses Google Groups [8] and in a www subfolder of the working sides HTML equivalents of checkboxes to discuss questions on the subject. ■

ADVERTISEMENT

WWW.LINUX - MAGAZINE.COM ISSUE 74 JANUARY 2007 71