Building a Tag-Cloud Using the Google Web Toolkit

Difficulty:IntermediateLength:LongLanguages:

A while back, I read a tutorial by Dan Wellman, which described the steps required to produce a neat Tag-Cloud. Dan's example largely relied on the jQuery framework to request data and construct the user interface elements. I decided to write his tutorial all over again with the two exceptions of using GWT instead of jQuery, and a different method of choosing font size variations.

In case you don't know what Tag-Clouds are and what purpose they serve, briefly, a Tag-Cloud is a form of visualizing the difference in importance or activeness of some
predefined categories based on how large they appear in the cloud.

We are going to use the latest version of GWT (currently 1.5) and work with MySQL and
PHP as our back-end to request the JSON data. Similar to Dan's tutorial, I too, assume that you already
are familiar with inserting into a database. The PHP code in this article will merely
cover how to query data from the database and send back the result in JSON format. You
should expect to learn:

• how GWT can request data from a PHP back-end and handle the response using callbacks
• how to use PHP to send JSON data back to the GWT client
• how to parse JSON data in GWT
• how to create and place a couple of GWT user interface widgets
• how to stylize GWT widgets using CSS
• how to choose a good font size variation for the tag-cloud

I used the Cypal Studio GWT plug-in for Eclipse to create this project. If you are already using
this combination, you should be able to download and open this project in Eclipse.

Although GWT debugger doesn't exactly debug JavaScript, using Eclipse with Cypal Studio plug-in allows for debugging GWT code inside the Eclipse IDE, which is better than many other JavaScript debuggers out there.

Let's Get Started

By default, as part of the script that generates a blank GWT project, you will get an HTML file
which, more or less, looks like the code below. You may need to correct the path of the JavaScript file

Our tag cloud is going to appear in the center of the browser. Since center-aligning pages using CSS doesn't work properly in IE, we add a new DIV element and set its id to "wrapper". This is all we need to get started. As we move further in this tutorial, we will re-visit this document to add more, but for now let's move on.

Requesting JSON Data

We will start by modifying the onModuleLoad() method of the MainEntryPoint class,
as it's the method that GWT uses to begin executing our code. We want to start by
requesting data (tag names and their frequencies) from the PHP and MySQL back-end.

We have defined a new method called getTagData() in which the RequestBuilder
type is instantiated to call the wmGetTags PHP script in the back-end. Note how the
sendRequest() method takes in a callback parameter that handles the response once it
arrives back.

When creating a new RequestCallback, we must implement the
onResponseReceived() and onError() methods to handle each case. Notice how in the
onResponseReceived() method, we check the response status code. This is because
during the life cycle of a request, this method could be invoked multiple times by the
browser even though it may not be completely fulfilled. A request is complete only when
the status code is equal to 200. We check the status code using the getStatusCode()
method.

Next we will create a FlowPanel widget and insert it inside the "wrapper" DIV. The
GWT widget library provides many different kinds of panels for different use; however, a
FlowPanel is the kind of widget that allows for holding more than one child widget in itself. This
property makes it a suitable widget for a Tag-Cloud. What we are doing here is creating a
holding container for all the tags that we must show.

Constructing a Response Using PHP

This part is fairly simple. Let's create a new PHP script and call it wmGetTags.php.
First, we must create a connection to the database using the mysql_connect() function,
then perform a SELECT query on the table that holds both tag names and their occurrences.
Finally when the query is done, we use a "For Loop" to generate a JSON formatted response.

When executed, the script above will generate a response similar to that shown below:

Above is an example of a JSON response. To be precise, this will be parsed into an array with
each of its four indexes holding an object with two fields. The first field "tag" holds the
name of the tag, while the second field "frequency" holds the occurrences count. Running what we've coded so far will produce a blank page, however inspecting browser communications using the "Net" tab in Firebug should show us the output of the PHP script above like shown in the image below.

Parsing JSON Data

At this point we must define the routine that will parse the response received from the back-end and construct the UI further to show the tags in the cloud. Since the HTTP and JSON types are contained within separate GWT modules, we must add the following <inherits> tags to our <module name>.gwt.xml to ensure the code needed to parse JSON is included for runtime:

You can find more about GWT modules here.

We now must call the handleGetTags() when the status code of the Response instance is equal to 200 like shown in the above code. The handleGetTags() method will actually process the JSON data.

All XMLHTTPRequest communication between the client and the back-end happens through plain text. So even
though the back-end response is JSON formatted, it's yet to be converted/parsed into real
JavaScript objects that we can then interact with, as shown below.

The JSONParser class provides a static method called parse() that takes in a String
parameter and returns a JSONValue object that we can then interact with. As we
previously established, our PHP script will return an array structure holding a number of
objects encapsulating data related to the tags. To get a handle to that array we must use
the isArray() method.

The above code will access the embedded object within every index of the array to get to the
actual tag data. So in every iteration of the loop, content of the current index is returned as a JSONObject. Every extracted JSONObject should have two fields: tag, and frequency.
We use the get() method of JSONObject class to retrieve these fields.

Next we must inject the tag names into the cloud UI. Remember the FlowPanel that we
created earlier? We now want to create hyperlink widgets and insert them into our ﬂow
panel - that is what these two lines above are doing. If we run the project, our tag-cloud should
look like this:

Stylizing Widgets

At this point we have what appears to be a list of links - but nothing like a tag-cloud yet.
GWT lets the developer precisely control the way that each widget renders by allowing the
developer to provide his own CSS. That is what we must do to give our tag-cloud a
face lift. Let's go back to our HTML again.

The first CSS rule above resets the padding and margin values and then sets the font for our
tag-cloud. The latter rules define how each of the tags should be positioned so that they
appear one after another in a horizontal fashion with the line height, padding and so forth.

Now you might ask the question: "But how do we tell GWT which CSS class to use for
what widget?" Well, that's easy. Every widget from the GWT UI library provides a method
called setStylePrimaryName() that takes in the name of the CSS class that you want
to assign to the widget. Now, we must go back and assign the correct CSS classes to
our widgets. There are two places where we need to do this. The first is the FlowPanel that
holds the tags.

We now should have something that looks similar to this:

Setting the Font Size

As you can see, our tags have come through and it looks more like a tag-cloud. Next we
must set the size of each tag to appear according to its number of occurrences.

The simplest implementation is to use a linear function to map a tag's frequency of use to
its font size in the tag-cloud. The algorithm used for deciding the font size evaluates the
frequency of every tag against the smallest occurrence and the largest occurrence, and
then returns a font size within the range of the smallest and largest font size that we
define.

So first we must find the tags with the smallest and largest number of frequency and
remember them within the class variables minFrequency and maxFrequency. We have also
identified the smallest and largest font size by setting the MIN_FONT_SIZE and MAX_FONT_SIZE
final variables.

Next, we define a method called getLabelSize() which takes in the frequency for the
current tag and returns the CSS font-size for that tag.

Now we must individually assign the CSS font-size to each hyperlink widget that we add to
the FlowPanel. To do so, we must get a handle to the Style object of the hyperlink
element and set the fontSize property as shown below:

And our MainEntryPoint.java file should look like this:

Summary

This tutorial demonstrated the simple steps required to build a tag-cloud,
showing how GWT can connect to a PHP and MySQL back-end to retrieve data.
It also showed how to create GWT widgets and stylize them through the familiar CSS techniques. I hope you enjoyed it!

• Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.