Using the Google Web Toolkit (GWT), a Java programmer can write rich Asynchronous JavaScript + XML (Ajax) applications completely in the Java™ programming language. Cypal Studio for GWT, designed for the Eclipse IDE, provides support for managing GWT constructs. Learn how Cypal Studio for GWT helps create new GWT modules, supports the creation of remote procedure calls, and makes it easy to view and deploy your Web applications.
Cypal Studio and the GWT
GWT is a set of tools that allows a Java programmer to write dynamic Ajax Web applications completely within the Java programming language, with no JavaScript required. A GWT application runs in all the major browsers, allows for rich interaction with the user, and can be fully tested and debugged within your Java development environment.
The GWT framework has four major components. A collection of widgets, implemented in the Java language, provides all the standard user interface (UI) functionality you would expect in a somewhat simpler application program interface (API) than, say, Swing. A remote procedure mechanism allows for communication between client and server, with GWT handling all the pipe and data translation. A fully integrated browser simulator allows GWT to run on its own during development, including niceties like being able to set breakpoints in your editor during a GWT debugging session. Finally, a compiler converts your Java code into the cross-browser JavaScript code that is actually executed in the client browser, managing browser incompatibilities so you don't have to.
While GWT simplifies the process by which you create an Ajax application, it still has several parts you must keep synchronized for it to work. As of this writing, advanced tool support for GWT is beginning to emerge in the major Java development environments.
Cypal Studio for GWT is a plug-in for Eclipse that simplifies many of the common tasks performed during GWT development. This article is not meant to be a full introduction to GWT. See Resources for in-depth documentation, including how GWT works and how to create simple applications.
Install Cypal Studio within the Eclipse Web Tools Platform
Before your can work with Cypal Studio for GWT, you must download it (see Resources). As of this writing, the current GWT version is 1.3, and it's available for Microsoft® Windows®, Mac OS X, and Linux®. Cypal may not support the GWT V1.4 release candidate that was available as this was written. Simply download the file for your operating system, extract it, and place the resulting folder someplace handy.
Next, you need a version of Eclipse with the Web Tools Platform (WTP) plug-ins. WTP is an omnibus collection of tools supporting Web application development. It includes editor support for Web standards, such as HTML and Cascading Style Sheets (CSS), JavaServer Pages (JSP) editor support, support for creating and maintaining the database you use in your Web application, and running the application on a Web server during development.
Those features are all very nice, but they're somewhat outside the scope of this article. At the moment, we are interested in WTP because Cypal Studio for GWT requires it to run; see Resources for further information about WTP.
The easiest way to get an Eclipse system that has WTP enabled is to download the whole thing in one shot. This is especially recommended if you are downloading Eclipse for the first time. The WTP download page offers an all-in-one download for all the WTP plug-ins, as well as a handful of prerequisite plug-ins. The page is a little on the confusing side: Look for Web Tools Platform; All-in-one. As of this writing, the current WTP version is 1.5.4. There are versions for Windows, Linux, and Mac OS X; download the one appropriate to your platform.
If downloading the whole thing at once strikes you as too straightforward or — more likely — you already have Eclipse and you don't want to download the whole thing all over again, you can download WTP as a plug-in. The download page lists a few requirement plug-ins. Download those, extract them, and place them in the plugins directory of your Eclipse installation. Then download Web Tools Platform (WTP, JST, and WST combined), with a file name something like wtp-R-1.5.4.zip. Extract that file to your plugins directory, as well.
Having done all that, you're finally ready to get the latest version of Cypal Studio for GWT. As of this writing, the current version appears with the name cypal.studio.for.gwt-beta.zip. Extracting that file to your Eclipse directory places files in the features and plugins directories.
Note: If you had installed the old Googlipse plug-in, you may need to remove that plug-in for the Cypal Studio for GWT plug-in to install cleanly.
Now that everything is downloaded, there's still one configuration option you must set before you can start. Fire up Eclipse and access the Preferences window, as shown in Figure 1. If everything has gone well, Cypal Studio should have an entry on the left-hand side. Simply set the GWT Home setting to the top-level directory of the GWT installation you created earlier.
Figure 1. The Cypal Studio Preferences window
The Cypal Studio Preferences window
That should install everything you need. Let's get going.
Back to top
Create your Cypal Studio project
To use Cypal Studio for GWT, you must create a new Dynamic Web Project or add Cypal Studio to an existing project. To start a new project, choose File > New. Choose the Dynamic Web Project Wizard, which you can find under the Web heading. You'll see the window shown below.
Figure 2. New Dynamic Web Project window
New Dynamic Web Project window
To create your project:
1. Type its name in the Project name box.
2. From the Configurations list, select Default Googlipse Project, then click Next. (It still says Googlipse as of this writing.) You'll see a list of Project Facets you should enable for the project. The default list, consisting of Dynamic Web Module, Googlipse, and Java, is fine.
3. Click Next. You'll have a chance to configure the names of some of the directories Cypal Studio is about to create. The rest of this article refers to the default names, but if you feel some strong need to change them, go right ahead.
4. Click Finish.
Cypal Studio for GWT starts creating a bunch of files, and you may be prompted to accept a license agreement for a document type definition (DTD) or two. When all is said and done, your Eclipse Project Explorer should look like Figure 3.
Figure 3. Cypal Studio Project Explorer
Cypal Studio Project Explorer
The Deployment Descriptor is a WTP thing, and I won't spend a lot of time there. Cypal Studio for GWT has created a directory for your source code, a directory for compiled Java code (when you have some of that), and a directory for WebContent, which so far consists largely of a rather lonely web.xml file.
At this point, you've created a new Cypal Studio project. Should you want to add Cypal Studio support to an existing Eclipse Dynamic Web Project, right-click the project in your Project Explorer, then click Properties. From there, choose Project Facets > Add/Remove Project Facets. You'll see a list of available facets; click Cypal's GWT Facet.
Back to top
Add your first project module
You have a lovely project skeleton, but no actual code. Let's fix that. The basic unit of GWT code is the module. A module roughly corresponds to a page users call up from their client browsers. A module generally consists of one or more Entry Point classes, which are loaded when the module itself loads. In addition, you can specify nonstandard locations for the module's source code, public Web files, and required JavaScript or CSS files, if any.
To create a module in Cypal Studio for GWT, choose File > New. If there's a listing for Module with the Cypal Studio toolbox icon, choose that. If not, choose Other > Cypal Studio > Module from the window that appears. Eventually, you wind up with the window shown below.
Figure 4. New GWT Module window
New GWT Module window
The Source folder, by default, is the source folder of your existing project. The Package folder, however, you must set for yourself. The normal convention is Your Top Level Package.Name of Module. You must also set the name of the module, the Superclass, and the Interfaces default, as shown.
After clicking Finish, Cypal Studio creates the following elements. (Those who have used GWT before will remember that this is roughly what you get from GWT's command-line tools, only with a nice easy-to-use graphical user interface [GUI].)
* The three packages — client, server, and public —below your top-level package in the specified source directory
* A file — FirstModule.java—in the client package to be the initial entry point of the module
* A file — FirstModule.html—in the public package for the HTML of the actual page to be rendered
Back to top
Create and run your code
Initially, the Java and HTML files contain the minimal stub code needed to compile. However, you can put something just a bit more interesting there: Insert the code shown in Listing 1 into the body section of the HTML file.
Listing 1. Create and run your code
Then put the Java code shown in Listing 2 in the Java file. You'll also need to have Eclipse generate the import statements for the imported classes.
Listing 2. Add Java code to Java file
int count = 0;
public void onModuleLoad() {
final Button button = new Button("Count Your Clicks!");
final Label label = new Label(String.valueOf(count));
button.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
count += 1;
label.setText(String.valueOf(count));
}
});
RootPanel.get("button").add(button);
RootPanel.get("count").add(label);
}
Because this code is in the onModuleLoad() method, it will run automatically when the module loads. Without getting too deeply into the details of the GWT widget set, this code creates a button and a label. It adds a listener to the button, then puts them both into HTML elements whose document object model (DOM) IDs match the strings passed to RootPanel.get().
To run your system, click Run. From the Run window, choose Gwt Hosted Mode Application > New_configuration. The window below appears. (You might have to right-click GWT Hosted Mode Application, then click New to see the new configuration.)
Figure 5. Creating a run configuration
Creating a run configuration
You must specify which project you have in mind and which module of that project. Luckily, Eclipse makes it easy to browse the existing project space. Click Apply to save your new configuration (give it a unique name first), then click Run to run it. Doing so invokes GWT hosted mode for your project. (After doing this once, clicking Run will work just like any other Eclipse run target.) Those of you who tried setting run targets up in Eclipse without Cypal Studio will appreciate the fact that Cypal Studio is about seven steps simpler.
When run, the page should look like Figure 6.
Figure 6. Your first Cypal Studio module
Your first Cypal Studio module
Back to top
Connecting to a remote service
Communication to the remote server is the key to any Web application, and GWT provides a framework by which your client-side GWT code can communicate with a Java remote server. The mechanism, more fully described in "Build an Ajax application using Google Web Toolkit, Apache Derby, and Eclipse, Part 3," is an Enterprise JavaBean (EJB) merger of multiple classes and interfaces. It's much easier than building each connection from scratch, but it still has a lot of parts to keep track of.
Cypal Studio for GWT has a couple of handy features to make it even easier for you to create and manage a remote connection. Start the process by choosing New > Remote Service. (If Remote Service is not in the menu, choose Other > Cypal Studio, just like you did to create the module.) You see the window shown below.
Figure 7. GWT Remote Service
GWT Remote Service
You must fill in the Name, which is the actual name of your Java server-side class, and the Extended interfaces service URI, which is the server-side URL your client will actually call. Then click Finish and let Cypal Studio do some work.
Cypal Studio creates three files for you. In your client package, it creates NumberGenerator.java, the main interface for this remote connection, shown in Listing 3.
Listing 3. NumberGenerator.java
public interface NumberGenerator extends RemoteService {
public static final String SERVICE_URI = "/numbergenerator";
public static class Util {
public static NumberGeneratorAsync getInstance() {
NumberGeneratorAsync instance = (NumberGeneratorAsync) GWT
.create(NumberGenerator.class);
ServiceDefTarget target = (ServiceDefTarget) instance;
target.setServiceEntryPoint(GWT.getModuleBaseURL() + SERVICE_URI);
return instance;
}
}
}
Notice that this file is an empty interface at the moment, but Cypal Studio has created a utility object for returning a fully GWT-certified instance suitable for your remote calls. "Build an Ajax application using Google Web Toolkit, Apache Derby, and Eclipse, Part 3" contains similar code, along with the suggestion that it might be useful to create a common method for the boilerplate code.
The return value of that utility is actually of type NumberGeneratorAsync, which is the asynchronous sibling of the main interface. Every method of the main interface has a matching entry in the asynchronous interface, but with a return type of void and an additional argument of class AsyncCallback. When you call this code from your client page, you actually use the async interface, and GWT converts it to the main interface, which is what the server side will see. Then, you use an AsyncCallback object to actually do something with the server response.
On the server side, Cypal Studio has created the implementation class NumberGeneratorImpl, which extends the GWT class RemoteServiceServlet and implements the NumberGenerator interface. In addition, GWT has modified the web.xml file to register the new remote server for use in deployed applications. The new lines look like Listing 4.
Listing 4. Additional lines for NumberGenerator.java
com.ibm.firstmodule.server.NumberGeneratorImpl
To actually create a remote call, start by adding the method signature to NumberGenerator. The method you'll implement will play the game "I'm thinking of a number." The method signature is:
public Integer getNumber(int maxNumber);
Save that signature in the NumberGenerator interface, and something interesting happens: Cypal Studio has added the matching method to NumberGeneratorAsync:
public void getNumber(int maxNumber, AsyncCallback callback);
This is very handy because keeping these two interfaces in sync manually is a bit of a burden. Now, you must also go to your NumberGeneratorImpl class. Eclipse flags this class in red because the NumberGenerator interface is no longer fully implemented. Fortunately, you can fix that by adding the following code, which — before you ask — I realize is on the simplistic side.
public Integer getNumber(int maxNumber) {
return new Integer((new Random()).nextInt());
}
To make the call, I've added it to the module, as shown in Listing 5. Note that to get this to work, I added another row to the HTML body with two cells, the first with the ID sender and the second with the ID response. The module now has a button that retrieves the random number from the server and compares it to your click count.
Listing 5. Module with call added
public class FirstModule implements EntryPoint {
int count = 0;
private Button button;
private Button sender;
private Label label;
private Label response;
public void onModuleLoad() {
button = new Button("Count Your Clicks!");
sender = new Button("Send Your Count!");
label = new Label(String.valueOf(count));
response = new Label("No Guess Yet");
button.addClickListener(new CountButtonClickListener());
sender.addClickListener(new SendClickListener());
RootPanel.get("button").add(button);
RootPanel.get("count").add(label);
RootPanel.get("sender").add(sender);
RootPanel.get("response").add(response);
}
public class CountButtonClickListener implements ClickListener {
public void onClick(Widget sender) {
count += 1;
label.setText(String.valueOf(count));
}
}
public class SendClickListener implements ClickListener {
public void onClick(Widget sender) {
NumberGeneratorAsync async =
NumberGenerator.Util.getInstance();
async.getNumber(10, new NumberCallback());
}
}
public class NumberCallback implements AsyncCallback {
public void onFailure(Throwable error) {
response.setText("Oops");
}
public void onSuccess(Object resp) {
int intResp = ((Integer) resp).intValue();
if (intResp == count) {
response.setText("Got It!");
} else if (intResp < count) {
response.setText("Too Low");
} else if (intResp > count) {
response.setText("Too High");
}
}
}
}
The key parts of the code are the SendClickListener and the NumberCallback. In SendClickListener, you use the Cypal Studio-generated Util class to get an instance of your async interface and call the getNumber() method from that interface.
The second argument to the call, which is an instance of NumberCallback, GWT invokes automatically when the server completes its response. The callback has two branches: onFailure() and onSuccess() — depending on whether the server completed the request without an exception. In this case, if the server succeeds, you compare the result to your count and set text in one of your labels. (You could have designed this so that the call sends the current count value to the server and the comparison is done server-side; it's just a question of where you want the complexity.)
When this code is in place, fire up GWT hosted mode, and everything should work.
Back to top
Deploy your GWT application
One area in which Cypal Studio is perhaps not yet fully mature is in using your Web application with an external server. It's certainly possible to do so, both inside and outside of Eclipse, but the process is probably a step or two longer than necessary.
To run your Web application inside Eclipse, you need an Eclipse WTP-approved servlet engine. Apache Tomcat is always a fine choice. Next, compile your GWT application. The easiest way to do this is to run the application in hosted mode as shown above, then click Compile/Browse. Doing so compiles all your GWT code to JavaScript files and probably opens an external browser on your machine, which you can ignore.
Next, you can trigger the process of running on your external server by right-clicking the project name in the Project Explorer. Choose Run As > Run On Server. A window to define a new server appears. Keep the host name as localhost. Select whatever server type you plan to use. If you haven't previously set up a server of that type, you'll also be prompted for the runtime directory of the server.
After setting up the runtime directory, Eclipse opens an HTML page in your workspace. Don't panic if Eclipse tries to hit the root directory of the system, which is an error in this case because you haven't specified anything like an index.html file. Simply point the browser at the HTML file you've created (in this case, http://localhost:8080/GooglipseProject/FirstModule.html), and you'll see something like Figure 8.
Figure 8. Project on an external server
Project on an external server
If you want to deploy your GWT project to an external browser, you can do so easily by right-clicking the project in the Project Explorer and choosing Export > WAR. You're prompted where to place the Web Archive (WAR) file. (You must also compile the GWT code as described above.) You can then drop the WAR file in the appropriate place on the server of your choice, and you're all set.
Back to top
The future of GWT and Cypal Studio
Share this...
digg Digg this story
del.icio.us Post to del.icio.us
Slashdot Slashdot it!
As of this writing, the exciting GWT news is the V1.3 release of a fully open source GWT. The V1.4 release is expected to add a rich text widget, splitters, and date and number formatters as well as improvements to the development tools and performance. Cypal Studio is still under active development, so visit the Cypal Studio for GWT Web site for new information.
Resources
Learn
* Read all the articles in the "Build an Ajax application using Google Web Toolkit, Apache Derby, and Eclipse" series.
* Visit the Google Groups forum for GWT.
* Check out the official GWT blog.
* Eclipse Foundation is the home for the Eclipse Web Tools Platform (WTP) Project.
* Learn more about the Eclipse Foundation and its many projects.
* Get more information about Cypal Studio for GWT.
* Check out the "Recommended Eclipse reading list."
* Browse all the Eclipse content on developerWorks.
* Users new to Eclipse should check out Eclipse project resources' Start Here.
* Expand your Eclipse skills by checking out IBM developerWorks' Eclipse project resources.
* To listen to interesting interviews and discussions for software developers, check out check out developerWorks podcasts.
* For an introduction to the Eclipse platform, see "Getting started with the Eclipse Platform."
* Stay current with developerWorks' Technical events and webcasts.
* Watch and learn about IBM and open source technologies and product functions with the no-cost developerWorks On demand demos.
* Check out upcoming conferences, trade shows, webcasts, and other Events around the world that are of interest to IBM open source developers.
* Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products.
Get products and technologies
* Where to find the Eclipse Web Tools Platform (WTP) Project.
* Download Cypal Studio for GWT.
* Visit Apache Tomcat at Apache.org.
* Download Eclipse, the open source, freely available, and extensible integrated development environment (IDE).
* Check out the latest Eclipse technology downloads at IBM alphaWorks.
* Download IBM product evaluation versions, and get your hands on application development tools and middleware products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.
* Innovate your next open source development project with IBM trial software, available for download or on DVD.
Discuss
* The Eclipse Platform newsgroups should be your first stop to discuss questions regarding Eclipse. (Selecting this will launch your default Usenet news reader application and open eclipse.platform.)
* The Eclipse newsgroups has many resources for people interested in using and extending Eclipse.
* Participate in developerWorks blogs and get involved in the developerWorks community.
About the author
Noel Rappin, a Ph.D. from the Graphics, Visualization, and Usability Center at the Georgia Institute of Technology, is a senior software engineer at Motorola. He is also the coauthor of wxPython in Action and Jython Essentials. You can check out Noel's blog at 10printhello.blogspot.com.