Implementing the Standard Flash Widget
The standard implementation for the Flash widget creates the EMBED tag, as shown in Listing 15.129 by simply stringing together a number of Strings. In a real implementation, we would use the parameters passed in to set dimensions, etc., but, in our example, we just hard code all the parameters. Note that, in the URL, we set the title value to be the word Other, which is what we expect to be displayed on screen. Listing 15.129 Defining the Flash widget's implementation class for the majority of...
Encapsulating Remote Calls in a Faade
The Fa ade pattern is one of the software patterns described in the famed book Design Patterns Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides. This book defines the fa ade software pattern as a way of providing a higher-level interface to make a subsystem easier to use. In our case we want to encapsulate all of the RPC logic into a class that provides a simple interface in an effort to achieve the following Reduce complexity by reducing the number of...
Throwing Exceptions
Often it is desirable to allow a method to throw an exception that will be handled by the calling code. For example you may have a login function that returns a user data object on success, but, on failure, it throws an appropriate exception. 1.2351 UserData loginUser String username, String password 1.2352 throws FailedAuthenticationException When GWT calls your service method, and it throws an exception, it will serialize the exception and return it to the client browser. The only requirement...
Writing the Application Deployment Descriptor
When you are creating the deployment descriptor, you will need to map each individual GWT-RPC servlet to a URL. This can be done in the same manner as we saw previously when we looked at the deployment descriptor used by the GWT development environment. The easiest way to explain this is to provide an example, then explain it. In listing 16.8 we provide the deployment descriptor file that could be used to deploy the Server Status project from chapter 10. In most cases you can simply copy the...
Relocating the JavaScript Code
If you have been following along and removing the unused files from the sample project, you will see that there aren't many files left. Figure 16.5 shows the current file list for our project. What is left is the project HTML file HelloWorld.html , the gwt.js file, the one loader script ending in .nocache.html, and the four browser specific script files ending in .cache.html. We could deploy this lump of files as-is without any further organization, but if you are deploying your GWT project...
Summary Gtx
JSNI is an extremely powerful way of interfacing with existing JavaScript libraries and for filling in the gaps where GWT might not yet have the functionality you need. It allows us to apply some of the good control and typing aspects of Java to our JavaScript interfaces however, we should keep the use of JavaScript as a minimum. View using JSNI as you would writing assembly language code segments in a high-level language project it is for specialized tasks, not for every day use. Indeed, the...
Loading Images
In chapter 4 we saw how to use the load event listener when dealing with the Dashboard's Slideshow application, where we tried to load seven images and only six were available. The missing image caused the alert shown in Figure 6.91 to be displayed to the user through the onError method. orO Method in LoadListener works. Figure 6.91 Showing an error when an image in the Slideshow component application cannot find an image. Figure 6.91 Showing an error when an image in the Slideshow component...
Navigating Your Application with Hyperlinks
The Hyperlink widget acts as an internal hyperlink within your GWT application. To the user it appears exactly as a normal hyperlink on the web page and when clicked they would expect some navigation within the application to occur. In your code, this action is coded as manipulating the GWT History object to change the application state you can see how this works in the Dashboard's Slideshow application The application has two hyperlinks, as shown in Figure 4.38, placed at the bottom that...
Managing the View of Data Using Trees
We have now nearly completed our look at most of the basic widgets GWT, there are two left the first of these is the Tree widget. This widget provides our applications with a standard hierarchical tree widget comprising of Treeltem widgets. 1.1 A Walk Through GWT jl 2 GWT Versus Other Solutions This is a took about GWT in Action And yoj are looking at Chapter that is called 1.3 Building Your First GWT Application Figure 4.43 The Dashboard's Book application showing the Tree widget on the...
Comparing GET to the POST Method
The POST method is typically used for HTML forms, where there can be a lot of data that needs to be transmitted. The POST method differs from the GET method in how it sends data to the server. Instead of including the data as part of the URL query it uses the body of the HTTP message. In HTTP the command and headers are separated from the body with a single blank line. When we looked at GET we issued a simple query to a web server. This time we will look at the same query, but sent as a POST....
Creating a Custom Field Serializer Class
public class ServerStatusData_CustomFieldSerializer import import import public static ServerStatusData instantiate The first method, instantiate , is a static method that takes a SerializationStreamReader as an argument, which we will discuss shortly, and returns an object of the type which this class was built to serialize, namely the ServerStatusData class. The instantiate method is optional and is only required when the target class doesn't have a zero argument constructor. It must return...
Step Identifying the Components
The components we will choose need to support our stated functionality, and quite often the choice is pretty much determinable from what we write down as the functionality. A quick look at the existing GWT widgets provided with the GWT distribution is enough to satisfy ourselves that the GWT Label widget is sufficient to represent our initial text it displays text, can be word-wrapped, and is un-editable. Another option could have been to use an HTML element, since of course we want the label...
Implementing Blocking on the Server
Implementing the server portion of a blocking RPC server can be done the same way you block any Java thread, and that is to issue a sleep command. When you issue a sleep command to the Java Virtual Machine, it stops processing of that specific thread of execution for some amount of time. Once the sleep time is finished, it wakes-up the thread and continues processing. Issuing a sleep command involves a single statement. The method Thread.sleep takes a number of milliseconds to sleep for, so...
Peeking into How GWT Works
We have now arrived at the final chapter in our discussion on GWT, where we round off by taking a look at how GWT performs the magic that it does. When we started using GWT, we were first interested in building applications, and then, as our curiosity got the better of us, we started wondering just how GWT was working behind the scenes. We were asking ourselves questions like how does the compilation work, why do we get so many HTML and XML files produced, and just what do they do How does an...
Using Dynamic String Internationalization
Using the dynamic approach was originally designed to allow existing i18n approaches to be quickly incorporated into GWT applications. If your existing approach used JavaScript associative array objects containing sets of key-value pairs, like the two shown in Table 15.46 then dynamic string i18n is potentially for you. Table 15.46 Two JavaScript associative array objects containing English and Swedish user interface constants Table 15.46 Two JavaScript associative array objects containing...
Building the ToggleMenuItem
With the TwoComponentMenuItem widget built, we can extend it to provide the ToggleMenuItem as shown in Listing 4.32. The purpose of this widget is to show one of two different images depending upon an internal status. For the Dashboard, we wish to show a check image if a certain piece of functionality is enabled and a cross image if it is not though you could easily envisage this as showing a check and no image as the disabled view in other scenarios . Listing 4.32 The ToggleMenuItem class....
Introducing the JSONValue Object
At the top of the JSON stack is the JSONValue object. This class is the abstract super-class of all JSON value objects. It contains a test method for each JSON types and a toString method, which will return a JSON message string. Each of the test methods will either return an object of the specific type, or null of the object isn't of that type. For example, the isArray method returns the JSONArray object if the value is an array, or null if it isn't. isBoolean JSONBoolean isNullO JSONNull...
Considering Panels as DOM Elements
The DOM Element view of panels is the view that is displayed in the Web browser. When a panel is created using the Java constructor, that constructor is responsible for creating the necessary DOM element for the panel. For example, the FlowPanel we looked at in the previous section has a Java constructor defined as follows Therefore, when we create a FlowPanel Java object, we are also creating a DOM lt div gt element. If we were to look directly at the DOM element of this FlowPanel, we would...
Registering a Property Error Function
GWT also allows us to register JavaScript functions that will execute under two error conditions during the loading process. The first is the gwt onPropertyErrorFn meta tag which allows us to register a function to be executed if a defined property value does not appear in the list of valid properties. In the Dashboard example, we have the externalvisibility property, which can have values of internet and intranet. We set up an error handler that redirects the user to the book's web page if an...
Implementing the Service
With our service interface defined for our service, now we need to implement its methods. We do this by creating a servlet that extends GWT's RemoteServiceServlet, and implements our service interface. Below is our complete ServerService implementation. Listing 10.3 ServerStatus server-side implementation 1.2354 package org.gwtbook.server 1.2356 import 1.2357 import extends RemoteServiceServlet implements ServerStatusService public ServerStatusData getStatusData ThreadGroup parentThread 1 while...
Understanding the GWT Event Model
One of the first things that a GWT application does when it loads is to register a single global event handler at the browser's document level. It performs this through the init method of the DOM class, which has two implementations, one for Internet Explorer and one for all the other browsers GWT supports. For Internet Explorer this is performed in the DOMImplIE6 class as doc.body.onmousedown doc.body.onkeydown doc.body.onfocus wnd._dispatchEvent doc.body.onmouseup doc.body.onkeypress...
Chatting to the Browser via GWT Java
If you're thinking of using functionality normally associated with the JavaScript window variable, you should first double-check the GWT Window class which can be found in the com.google.gwt.user.client package in gwt-user.jar does not provide the access you are looking for. It does provide access to a number of functions normally accessed through the JavaScript window variable such as raising alert and confirmation windows, opening new browser windows, setting the browser title and enabling...
Implementing the deserialize Method
The deserialize method is passed the object instance created by instantiate and passed a reader so that it can continue reading from the serialized stream. The reader is an instance of SerializationStreamReader from the package com.google.gwt.user.client.rpc. It has a set of methods that allow you to read one object at a time from the serialized stream. The reader methods mirror the writer method that we looked at previously. It is important that you read the values in the same order as you...
Creating the Java Package Structure
GWT binds our hands slightly in our choice of package names and structure. When we used the creation tools in chapter 2, we saw that our application's entry point code had to be in a package with the sub-package client as the last name. Thus our Dashboard.java file must be found in that package. There are also some other conventions that GWT applications are beginning to adhere to mainly as a result of the example code shipped with GWT . Any server side code is generally placed in a sub-package...
Docking Components
The DockPanel is very reminiscent of the Swing BorderLayout. It allows multiple widgets to be added to the North, West, East and South, but only one widget can be added to the center space, which is allowed to take up any remaining space on the widget. They layout of the DockPanel can be seen in Figure 5.72. Figure 5.72 Schematic of the DockPanel showing the five areas where widgets can be placed within it. Figure 5.72 Schematic of the DockPanel showing the five areas where widgets can be...
Using an AsyncCallback SuperClass
As we have seen already, we have applied the Command software pattern by creating a class that implements the AsyncCallback interface. One of the original reasons for doing so was so that we could extend our command class, which is something we couldn't do if we had used an anonymous class for our callback. Again, our goal goes back to the need for separating out the logging for all RPC commands into a single class that can be reused and maintained in a single place. There are two ways in which...
Sending JSON Data to the Server
When you use JSON to communicate with the server, you do so with the RequestBuilder class that we looked at in chapter 12. JSON by itself is not a transport mechanism, it is just a message format, so we need to use RequestBuilder to actually transmit the message. In the discussion that follows, we will no doubt repeat some of what we stated in the section on RequestBuilder, but this is not a substitute for our earlier explanation. So, if you find that you do not quite understand something about...
Overview of JUnit for GWT Developers
If you haven't seen or heard of JUnit before, the best place to start is the JUnit project site at www.junit.org. The site contains links to dozens of articles about the framework dating back to 1999. This overview in no way means to replaces the hundreds if not thousands of pages written on the subject, but it will provide enough detail to allow you to write some simple tests even if this is your first experience with JUnit. Unless you already have JUnit ready to go, you will need to visit the...
Preparing for Hosted Mode
In Hosted mode, our application is executed through a managed environment that is provided by the GWT distribution. Our client side code executes in a managed web browser, where the Java code is effectively interpreted and any errors or issues are captured and reported in a controller window. Hosted mode also includes an embedded version of the Tomcat Servlet engine into which any server side Java code is deployed automatically. When we executed the application creation tool in chapter 2, it...
Cleaning Up the TreeItem Images
The next set of files to prune are the three image files tree_closed,gif, tree_open.gif, and tree_white.gif. These images are used by the TreeItem widget that comes with GWT. If you aren't using the Tree widget, as in our sample project, you should remove these three images. On the other hand, if you are using a tree in your application, this becomes unfortunate because it isn't the best idea to have images intermingled with your HTML files. Fortunately the GWT tree widget allows you to move...
Processing the Meta Tags
The next step that GWT performs 3 in Listing 17.144 is to process any meta-data tags that it can find in the HTML file. There is always at least one meta-tag defining a GWT module where the name of the meta-tag is gwt module. It is possible for there to be more than one module identified that are to be loaded into the page, in which case there is more than one gwt module meta-tag. GWT also allows us to define meta-tags covering the situations shown in Table 3.11. Table 17.49 Describing the...
Reacting to Closing Popups
We can register an event handler for when popups are closed. The Dashboard's Tooltip, which is a sub-class of the PopupPanel sets up a timer that will auto-close the popup after a delay. If we close the tool tip in another way, e.g. clicking on another part of the application, then we wish to cancel that timed hide event to avoid having surplus timers running around we're not exactly sure of the impact of this, but doubt that it is good, so it is best to avoid if we can . We have only attached...
Making the Choice
The final widget we look at that is provided by the GWT distribution is the RadioButton widget, which provides the implementation of a set of mutually exclusive selections. As with the CheckBox it is common to see this either in a form or standing alone. Unlike CheckBox, we need a way to indicate which set of RadioButtons are included within a particular group and we do this in the constructor, which has three forms, all of which require the definition of a group name. Listing 4.27 shows the...
Using JSON with Java on the Server
As we stated, we need to implement a proxy service for our Yahoo-based search component. For this project we will implement this as a Java servlet, and use third-party libraries to allow us to parse JSON data, and to hit an external web address. There is no requirement that this be implemented as a servlet, but we have done so because we feel that, as a stand-alone application, this it the best fit. To begin, we need to first address the source of external libraries that will be required to...
Writing Custom Field Serializers
Writing a custom field serializer is fairly easy to do. In this section we take the ServerStatusData class that we used as our data object for the ServerStatusComponent example, and we write a custom serializer for it. To begin, let us look at the original implementation of the ServerStatusData class. import public class ServerStatusData implements IsSerializable Our data object is fairly simple, including only five fields, so our custom field serializer will also be fairly simple, but it will...
Dissecting the HTTP GET Method
The GET command sends all of its data as part of the URL. Before we get into the specifics, let's take a look at an example URL, which is the URL used to perform a Google search for GWT. When your browser sends this URL request to google.com, it sends the following GET message using HTTP. You can see that the URL is still intact, except for the host name that has been added as a header. For clarity, we have only included the Host header, but there could be any number of additional name-value...
Sinking Events
The first way of a widget registering interest in events is to use the sinkEvents method. Using this method we can tell the GWT application and Browser what types of events the widget is interested in. A widget can sink all browser events shown in Table 6.24, and when it does so, it registers the wnd._dispatchEvent method for those events that the widget should sink. It also updates the DOM element representation of the widget to show which events it is interested in. In the Dashboard we want...
Navigating Your Application Using Menus
The menu system provided by GWT is based on the MenuBar and Menultem widgets. Menultems are added into MenuBars and MenuBars are added to other MenuBars in order to create your applications menu system. Figure 4.40 shows this system in place for the Dashboard menu system, where Clock, Calculator and Slideshow Menultems are added to a Create MenuBar, this Create MenuBar and a Help MenuBar are then added to another MenuBar, which is then displayed on the browser page. Figure 4.40 MenuBar and...
Parsing and Validating a JSON Server Response
1.3361 class SearchResultsHandler implements RequestCallback 1.3364 public void onError Request request, Throwable exception 1.3366 GWT.log Search request failed, exception 1.33 67 Window.alert Sorry, the search request could not be sent. 1.3370 public void onResponseReceived Request request, Response response 1.3372 if response.getStatusCode 200 there was an error 1.3378 results 1.3382 private JSONArray extractYahooResults String responseText 1.3384 private void updateResultsArea JSONArray...
Moving Events Further into Our GWT Code
Once our widgets have captured events then we will often feed that information back into our code as a hooker moves the ball back in a rugby scrum. The following code gives an example as to what we mean 1.1020 Button theButton new Button Click Me ClickListener 1 1.1022 public void onClick Widget sender 2 was Clicked 3 Annotation lt 1 Adding a ClickListener to a Button gt Annotation lt 2 Defining the onClick method gt Annotation lt 3 Providing the onClick functionality gt In this code we are...
Stage Creating a GWTApplication
Looking into the GWT distribution you downloaded in chapter 1, you should be able to see four command line applications, all ending with the word Creator. The functionality of these tools is summarized in Table 2.2. They help us create the directory and file structure of a GWT application, and they additionally create a set of default files that go together to make the default application. In this stage, we will take each of the creation tools described in Table 2.2 in turn, and look at how...
Creating a Method That Uses Introspection
When it comes to manipulating the input class, we briefly mentioned earlier that GWT provides a set of classes that allow us to introspect an existing Java class these are depicted in Figure 14.152. It is only possible to introspect a Java class at compile time and that introspection has to use the GWT classes in Figure 14.5 rather than the normal Java way. It is only possible to introspect a Java class at compile time and that introspection has to use the GWT classes in Figure 14.5 rather than...
junitCreator junit Path To J Unit [eclipse PiojMam[modjle MotMameout
The options that are available to the command are listed in Table 2.9. Table 2.9 Listing the arguments for the GWT jUnitCreator command. Table 2.9 Listing the arguments for the GWT jUnitCreator command. Name of the Eclipse project optional The GWT module of the application you wish to test. The directory to write output files into defaults to current Overwrite any existing files optional Ignore any existing files do not overwrite optional The flags -eclipse, -out, -overwrite, and -ignore are...
Wrapping a Complex JavaScript Library
The previous section wrapped a simple JavaScript library where there was only one JavaScript object. As we saw, this is a real life example, but nowadays it is often the case that the JavaScript libraries we might wish to wrap contain more than one object that we need to manage. Let's look at the Google Ajax Search API, which we use to present the user a Dashboard search component similar to that shown in action in Figure 8.136. And it's a. first --it's the first book to cover the al Protocol,...
Step Implementing the Right GWT Java Interfaces
GWT provides a number of interfaces that widgets can claim that they implement. A GWT Label, for instance, implements the HasText interface which means it provides setText and getText methods. When we use widgets within a composite widget these interfaces become buried it is possible to make the widgets your composite uses public and then a user can call the interface methods on those widgets, but then the user needs to know the structure of your composite. To improve on that and maintain...
Injecting Resources into an Application at Run Time
GWT provides the ability to inject into applications JavaScript and CSS resources at run time as opposed to defining them in the applications HTML file . You may wish to do this, for example, if you are embedding a GWT application into an existing web page and you wish to keep the application's CSS separate from the web page HTML. We will look at both types of injection in turn first, injecting JavaScript resources into applications and second, injecting style sheet resources into applications...
Setting Up and Cleaning Up the Test
Because there is often a need to perform some setup prior to a test, and cleanup after, JUnit provides two methods for this purpose. The setUp method is called before executing each test in the test case class, and tearDown after each test. The following is an example of using the setUp method to create a connection pool using the Jakarta commons-dbcp library before each test, and shutting it down after the test has completed. Listing 16.2 - An example of overriding the TestCase setUp method...
Callback Routine Using the Command Pattern
Early in our discussion on RPC, we addressed the fact that calls to the server are done in an asynchronous fashion, where the call to the server is as a separate thread of execution. We then went on to examine how you can pass an anonymous instance of the AsyncCallback interface to receive the result from the server. Below is the example we had provided earlier in the chapter. 1.2543 AsyncCallback callback new AsyncCallback public void onFailure Throwable caught GWT.log RPC error, caught public...
Using PasswordTextBox to Hide Text
The PasswordTextBox is the same as TextBox with one small difference. Any text typed into the box will appear as a star or round circle to obscure the contents of the field. As the name implies, this input component is typically only used for password fields. The idea being that someone looking over your shoulder won't be able to read what you have typed. 1.3103 PasswordTextBox pass new PasswordTextBox Like the TextBox, you must explicitly set the name property of the component if you plan on...
Defining and Extending Properties
Properties are defined using the simple define-property tag. 1.2046 lt define-property name name For example, the user agent property that defines the browsers GWT can create JavaScript for is given in as 1.2049 lt define-property name user.agent 1.2 We can see this in the UserAgent module XML in the com.google.gwt.user package. Similarly, the I18n module XML defines one value for locale as 1.2053 lt define-property name locale values default gt If we wish to define our own properties then we...










