Building a Tag-Cloud using GWT

Building a Tag-Cloud Using the Google Web Toolkit

Mar 31st in JavaScript & AJAX by Arman Mirkazemi

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.

PG

Author: Arman Mirkazemi

This is a NETTUTS contributor who has published 1 tutorial(s) so far here. Their bio is coming soon!

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

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Devin March 31st

    very nice tut

    ( Reply )
  2. PG

    Kyle March 31st

    Great stuff!!

    ( Reply )
  3. PG

    Diogok March 31st

    useful :-)

    ( Reply )
  4. PG

    Abdul Akbar March 31st

    Good Stuff

    ( Reply )
  5. PG

    iPad March 31st

    Simple steps? hahaha are you kidding me?

    ( Reply )
  6. PG

    henry March 31st

    great tut a bit advanced for me right now have to do some catch up! lol

    ( Reply )
  7. PG

    Dimitry Z March 31st

    Nice tutorial. I’ve never imagined using GWT: it’s very word-y. But for the sake of learning, this is pretty cool.

    Also, I understand that it’s for the sake of brevity, but ‘frequency’ should probably not be a stored column, rather a field calculated using the number of times a tag appears associated to an entity :)

    ( Reply )
  8. PG

    insic March 31st

    cool, first tut about GWT. nice start

    ( Reply )
    1. PG

      Marco March 31st

      Indeed – GWT is pretty awesome. Would love to see more GWT tuts over here.

      Well done!

      ( Reply )
  9. PG

    crysfel March 31st

    Well done!! i like this tut!!

    ( Reply )
  10. PG

    Rahul Chowdhury April 1st

    Wow, a great use of Google Web Toolkit, nice tutorial. But may not be required for the ones already using Wordpress or any advanced blogging platform. Still a good effort.

    ( Reply )
  11. PG

    Franco April 1st

    Thanks! More GWT/Java Tutorials please!

    ( Reply )
  12. PG

    Sirwan April 1st

    looks abit long for such a small task… i could do this in normal php and mysql… and what is JSON?

    ( Reply )
    1. PG

      Anton Agestam April 1st

      JSON is a way of parsing arrays, I think. The step named Constructing a Response Using PHP is all about that. I agree fully with you, as I wrote below.

      ( Reply )
  13. PG

    Weer Vergelijker April 1st

    Thank you for this tut, nice use of the google tools!

    ( Reply )
  14. PG

    Mary April 1st

    thank you for new knowledge!

    ( Reply )
  15. PG

    Anton Agestam April 1st

    I think you are making it more complicated than it really is. This effect could be achieved very easy without playing around with JSON.

    ( Reply )
  16. PG

    Yoosuf April 1st

    java in Nettuts its cool

    ( Reply )
  17. PG

    Evan Byrne April 1st

    Hm, well I could have simplified this a lot by just using a little jQuery…

    ( Reply )
    1. PG

      Melissa April 4th

      But would you have had GWT’s impressive automatic optimization and cross-browser compatibility?

      ( Reply )
  18. PG

    Matt April 1st

    Yum! Java!

    ( Reply )
  19. PG

    Liam McCabe April 1st

    Interesting! Great tutorial and well written :)

    ( Reply )
  20. PG

    Carl Pritchett April 1st

    Quote: “using Eclipse with Cypal Studio plug-in allows for debugging GWT code inside the Eclipse IDE”

    GWT supports debugging in Eclipse without Cypal Studio.

    Cypal Studio gives you two main advantages:
    - Provides functions to automatically generate the standard RPC handling code
    - Helps in creating and deploying web application archive (WAR) files
    – Note that GWT 1.6 is going to project structure natively

    ( Reply )
  21. PG

    MAik April 3rd

    Can this cross browser support?
    It can be different server for the gwt Aplication and for the php+mysql?

    ( Reply )
  22. PG

    bangus April 14th

    Great!! This is awesome! I will try on this

    ( Reply )
  23. PG

    daniel April 16th

    that’s pretty cool staff.

    But It works only after uploading to real working php server.

    Has anyone got an idea how to debug php scripts and use mysql in eclipse environment.

    or at least how to force eclipse to use any local websever apart of gwt built in.

    personally I run denver( similar to xamp or winmp) I have all php templated backend there. But it looks like it’s impossible to use it under gwt eclipse in hosted mode.

    any solutions welcome

    ilovesushi[ at ] rambler[ dot ]ru

    ( Reply )
  24. PG

    michael April 22nd

    Thanks for the article

    ( Reply )
  25. PG

    mychannelnews May 13th

    Wow! great Info. You must be an experienced webnaster. Bookmarked

    ( Reply )
  26. PG

    BillyG May 14th

    I was waiting to hear about performance differences, but nice JSON tut, even if it is with GWT :-)

    ( Reply )
  27. PG

    oyunlar June 4th

    I need and xml powered flash tag cloud, is there any way to do this.
    Regards

    ( Reply )
  28. PG

    A.N.Raghuveer June 30th

    see exactly when u r opening a php file using mysql database it will have one port number and the GWT browser is having another port number so the required output is not getting fired in the php file as the file is using a new port number with different from the GWT browser is using.

    plz see with the solution

    ( Reply )
  29. PG

    Kevin September 11th

    Nice tut – however, you may consider getting rid of the wordy JSON parsing part and replace it with JavaScript overlay objects http://googlewebtoolkit.blogspot.com/2008/08/getting-to-really-know-gwt-part-2.html

    ( Reply )
  30. PG

    kral oyun October 11th

    thanks for good posts for article

    ( Reply )
  31. PG

    Joe October 11th

    Kool

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    October 11th