Advertisement
JavaScript & AJAX

Building a Tag-Cloud Using the Google Web Toolkit

by

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.

Tag 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.
Otherwise here is a link to obtain more information.

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
according to your server setup.

<html> 
    <head> 
        <title>Main</title> 
    </head> 
    <body> 
        <script language="javascript" src="in.cypal.studio.gwt.samples.TagCloud.nocache.js"></script> 
    
        <!-- This div is added to allow center align the page even in IE  -->
        <div id="wrapper" style="text-align:center"></div>
    </body> 
</html>

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.

public void getTagData(){ 
    
    // you may need to change the URL according to your server setup
    String url = "/wmGetTags.php";  
    
    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,url); 
    try{ 
        requestBuilder.sendRequest(null, new RequestCallback() { 
            public void onResponseReceived(Request request, Response response){ 
                if (response.getStatusCode() == 200){ 
                    // handler code
                } 
            } 
            
            public void onError(Request request, Throwable exception){ 
                throw new UnsupportedOperationException("Not supported yet."); 
            } 
        }); 
    } catch (Exception e){ 
        e.printStackTrace(); 
    } 
} 

public void onModuleLoad() { 

}

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.

public void onModuleLoad() { 
    getTagData(); 
    flowPanel = new FlowPanel(); 
    RootPanel.get("wrapper").add(flowPanel); 
}

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.

<?php 
    
  //connection information 
  $host = "localhost"; 
  $user = "root"; 
  $password = "your_password_here"; 
  $database = "tagcloud"; 
 
  //make connection 
  $server = mysql_connect($host, $user, $password); 
  $connection = mysql_select_db($database, $server); 
 
  //query the database 
  $query = mysql_query("SELECT * FROM tags"); 
 
  //start json object 
  $json = "(["; 
 
  //loop through and return results 
  for ($x = 0; $x < mysql_num_rows($query); $x++) { 
    $row = mysql_fetch_assoc($query); 
  
    //continue json object 
    $json .= "{tag:'" . $row["tag"] . "',frequency:" . $row["frequency"] . "}"; 
  
    //add comma if not last row, closing brackets if is 
    if ($x < mysql_num_rows($query) -1) 
      $json .= ","; 
    else 
      $json .= "])"; 
  } 
 
  //return JSON with GET for JSONP callback 
  $response = $_GET["callback"] . $json; 
  echo $response; 
  //close connection 
  mysql_close($server); 

?>

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

([{tag:'Gmail',frequency:21},{tag:'Web',frequency:19},{tag:'Salesforce',frequency:66},{tag:'Amazon',frequency:17}])

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:

<inherits name="com.google.gwt.json.JSON" /> 
<inherits name="com.google.gwt.http.HTTP" />

You can find more about GWT modules here.

public void getTagData(){ 

    // ... 

    try{ 
        requestBuilder.sendRequest(null, new RequestCallback() { 
            public void onResponseReceived(Request request, Response response){ 
                if (response.getStatusCode() == 200){ 
                    handleGetTags(response.getText()); 
                } 
            } 
        
            public void onError(Request request, Throwable exception){ 
                throw new UnsupportedOperationException("Not supported yet."); 
            } 
        }); 
    } catch (Exception e){ 
            e.printStackTrace(); 
    } 
}

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.

public void handleGetTags(String jsonText){ 
 
    JSONObject jsonObject; 
    JSONString tagName; 
    JSONNumber tagFreq; 
    int frequency; 
    String realTagName; 
    
    JSONValue jsonValue = JSONParser.parse(jsonText); 
    JSONArray jsonArray = jsonValue.isArray(); 
    
    if (jsonArray != null){ 
        for (int i = 0; i < jsonArray.size(); i++){ 
             jsonObject = (JSONObject)jsonArray.get(i); 
             tagName = jsonObject.get("tag"      ).isString(); 
             tagFreq = jsonObject.get("frequency").isNumber(); 
             frequency = (int)tagFreq.doubleValue(); 
             Hyperlink tagLink = new Hyperlink(tagName.stringValue(),tagName.stringValue()); 
             flowPanel.add(tagLink); 
        } 
    } 
}

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.

JSONValue jsonValue = JSONParser.parse(jsonText);
JSONArray jsonArray = jsonValue.isArray();

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.

for (int i = 0; i < jsonArray.size(); i++){ 
    
    jsonObject = (JSONObject)jsonArray.get(i); 
    tagName = jsonObject.get("tag"      ).isString(); 
    tagFreq = jsonObject.get("frequency").isNumber(); 
    frequency = (int)tagFreq.doubleValue(); 
    realTagName = tagName.stringValue(); 
 
    //...
  
}

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.

Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null); 
flowPanel.add(tagLink);

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 flow
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.

<html> 
    <head> 
        <title>Main</title> 
        <style> 
            * { 
                padding : 0; 
                margin : 0; 
                font-family : "Lucida Grande","Lucida Sans Unicode",Arial,Verdana,sans-serif; 
                overflow : hidden; 
            } 
            
            .cloudWrap { 
                text-align : center; 
                margin : 50px auto; 
                background-color : #333; 
                padding : 10px; 
                width : 400px; 
                line-height : 1.5em; 
            } 
            
            .cloudTags { 
                float : left; 
                padding : 5px; 
            } 
            
            .cloudTags a { 
                color : #FFFFFF; 
                text-decoration : none; 
            } 
        </style> 
    </head> 
    <body> 
        <script language="javascript" src="in.cypal.studio.gwt.samples.TagCloud.nocache.js"></script> 

        <!-- This div is added to allow center align the page even in IE  -->
        <div id="wrapper" style="text-align:center"></div>
    </body> 
</html>

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.

public void onModuleLoad() { 
    getTagData(); 
    flowPanel = new FlowPanel(); 
    flowPanel.setStylePrimaryName("cloudWrap"); 
    RootPanel.get().add(flowPanel);
}

The second is after adding a hyperlink to the FlowPanel.

Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null); 
flowPanel.add(tagLink); 
tagLink.setStylePrimaryName("cloudTags");

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.

int maxFrequency = 0; 
int minFrequency = 600000000; 
final int MIN_FONT_SIZE = 5; 
final int MAX_FONT_SIZE = 25; 

public void handleGetTags(String jsonText){ 

    // ... 

    for (int i = 0; i < jsonArray.size(); i++){ 
        jsonObject = (JSONObject)jsonArray.get(i); 
        tagFreq = jsonObject.get("frequency").isNumber(); 
        frequency = (int)tagFreq.doubleValue(); 
        if (minFrequency > frequency) 
            minFrequency = frequency; 
        if (maxFrequency < frequency) 
            maxFrequency = frequency; 
    } 
    
    // ... 
}

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.

public String getLabelSize(int frequency){ 
    double weight = (Math.log(frequency) - Math.log(minFrequency)) / (Math.log(maxFrequency) - Math.log(minFrequency)); 
    int fontSize = MIN_FONT_SIZE + (int)Math.round((MAX_FONT_SIZE - MIN_FONT_SIZE) * weight); 
    return Integer.toString(fontSize) + "pt"; 
}

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:

Style linkStyle = tagLink.getElement().getStyle(); 
linkStyle.setProperty("fontSize",getLabelSize(frequency));

And our MainEntryPoint.java file should look like this:

package org.yournamehere.client;

import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style;
import com.google.gwt.json.client.*;

import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.RootPanel;

public class MainEntryPoint implements EntryPoint {

    FlowPanel flowPanel = null;
    int maxFrequency    = 0;
    int minFrequency    = 600000000;

    final int MIN_FONT_SIZE = 5;
    final int MAX_FONT_SIZE = 25;

    public void onModuleLoad() {

        getTagData();

        flowPanel = new FlowPanel();
        flowPanel.setStylePrimaryName("cloudWrap");
        RootPanel.get("wrapper").add(flowPanel);
    }

    public void getTagData(){

        String url = "/wmGetTags.php";
        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url);

        try{
            requestBuilder.sendRequest(null, new RequestCallback() {

                public void onResponseReceived(Request request, Response response) {

                    if (response.getStatusCode() == 200)
                        handleGetTags(response.getText());
                }

                public void onError(Request request, Throwable exception) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });
        } catch (Exception e){
            e.printStackTrace();
        }
    }


    public void handleGetTags(String jsonText){

        JSONValue jsonValue = JSONParser.parse(jsonText);
        JSONArray jsonArray = jsonValue.isArray();

        JSONObject jsonObject;
        JSONString tagName;
        JSONNumber tagFreq;

        int frequency;

        if (jsonArray != null){

            for (int i = 0; i < jsonArray.size(); i++){

                jsonObject = (JSONObject)jsonArray.get(i);
                tagFreq = jsonObject.get("frequency").isNumber();

                frequency = (int)tagFreq.doubleValue();

                if (minFrequency > frequency)
                    minFrequency = frequency;

                if (maxFrequency < frequency)
                    maxFrequency = frequency;
            }

            for (int i = 0; i < jsonArray.size(); i++){

                jsonObject = (JSONObject)jsonArray.get(i);

                tagName = jsonObject.get("tag"      ).isString();
                tagFreq = jsonObject.get("frequency").isNumber();

                frequency = (int)tagFreq.doubleValue();

                Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null);
                tagLink.setStylePrimaryName("cloudTags");

                Style linkStyle = tagLink.getElement().getStyle();
                linkStyle.setProperty("fontSize",getLabelSize(frequency));

                flowPanel.add(tagLink);
            }
        }
    }

    public String getLabelSize(int frequency){
        double weight = (Math.log(frequency) - Math.log(minFrequency)) / (Math.log(maxFrequency) - Math.log(minFrequency));
        int fontSize = MIN_FONT_SIZE + (int)Math.round((MAX_FONT_SIZE - MIN_FONT_SIZE) * weight);
        return Integer.toString(fontSize) + "pt";
    }
}

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.


Related Posts
  • Code
    Web Development
    Laravel Unwrapped: Session, Auth and CacheLaravel wide retina preview
    Join me as we learn how to use Laravel's component-based system, Illuminate. Additionally, we'll see how to utilize service providers, Laravel's manager system, the Session, Auth, and Cache components, and the Store, Guard, and Repository libraries.Read More…
  • Code
    Web Development
    The Linked ListData structures succinctly wide retina preview
    Learn about linked lists, the building blocks for creating solutions to business problems via algorithms and data structures.Read More…
  • Code
    Android SDK
    Consuming Web Services with kSOAPEd4e2 preview image@2x
    In this tutorial, you'll learn how to consume web services using the popular kSOAP library in an Android application. kSOAP is a reputable library loved by developers who have the need to parse WSDL (Web Service Definition Language) and SOAP (Simple Object Access Protocol) messages.Read More…
  • Code
    Tools & Tips
    Tips to Avoid Brittle UI TestsUi test retina preview
    In the last article I talked about a few ideas and patterns, like the Page Object pattern, that help write maintainable UI tests. In this article we are going to discuss a few advanced topics that could help you write more robust tests, and troubleshoot them when they fail:Read More…
  • Code
    PHP
    Building a CodeIgniter Web Application From Scratch - Part 1Web app retina preview
    In this series we're going to build a web billboard application from scratch, we're going to use CodeIgniter to handle the back-end service and BackboneJS for the web client. In the first two parts of the series we'll create the back-end service and then the client application in the last two.Read More…
  • Code
    Creative Coding
    A Look at the WordPress HTTP API: A Practical Example of wp_remote_getDiagram http api
    In the last article in this series, we took a look at the PHP functions that are available for making remote requests. Specifically, we reviewed: file_get_contents cURL And we also discussed the WordPress function wp_remote_get. In this article, we're going to put the wp_remote_get to work. This function is part of the HTTP API - to practical use by using it to retrieve the following two things: The number of followers we have on Twitter Our most recent Tweet The nice thing is that we won't need to use any OAuth or authentication mechanisms, and we'll only need to take advantage of Twitter responses and PHP's JSON functionality. So in this article, we're going to take a practical look at how to do exactly this, then we'll end the series reviewing all of the information that wp_remote_get returns so that we'll know how to properly handle it in future work.Read More…