Chinaunix首页 | 论坛 | 博客
  • 博客访问: 574852
  • 博文数量: 207
  • 博客积分: 10128
  • 博客等级: 上将
  • 技术积分: 2440
  • 用 户 组: 普通用户
  • 注册时间: 2004-10-10 21:40
文章分类

全部博文(207)

文章存档

2009年(200)

2008年(7)

我的朋友

分类: 系统运维

2009-04-05 20:17:08

A while back, I read a tutorial by , which described the steps required to . 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.

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

  1. <html>    
  2.     <head>    
  3.         <title>Maintitle>    
  4.     head>    
  5.     <body>    
  6.         <script language="javascript" src="in.cypal.studio.gwt.samples.TagCloud.nocache.js">script>    
  7.        
  8.           
  9.         <div id="wrapper" style="text-align:center">div>  
  10.     body>    
  11. 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.

  1. public void getTagData(){    
  2.        
  3.     // you may need to change the URL according to your server setup   
  4.     String url = "/wmGetTags.php";     
  5.        
  6.     RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,url);    
  7.     try{    
  8.         requestBuilder.sendRequest(nullnew RequestCallback() {    
  9.             public void onResponseReceived(Request request, Response response){    
  10.                 if (response.getStatusCode() == 200){    
  11.                     // handler code   
  12.                 }    
  13.             }    
  14.                
  15.             public void onError(Request request, Throwable exception){    
  16.                 throw new UnsupportedOperationException("Not supported yet.");    
  17.             }    
  18.         });    
  19.     } catch (Exception e){    
  20.         e.printStackTrace();    
  21.     }    
  22. }    
  23.   
  24. public void onModuleLoad() {    
  25.   
  26. }  

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.

  1. public void onModuleLoad() {    
  2.     getTagData();    
  3.     flowPanel = new FlowPanel();    
  4.     RootPanel.get("wrapper").add(flowPanel);    
  5. }  

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:

([{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 tags to our .gwt.xml to ensure the code needed to parse JSON is included for runtime:

 
 

You can find more about GWT modules .

  1. public void getTagData(){    
  2.   
  3.     // ...    
  4.   
  5.     try{    
  6.         requestBuilder.sendRequest(nullnew RequestCallback() {    
  7.             public void onResponseReceived(Request request, Response response){    
  8.                 if (response.getStatusCode() == 200){    
  9.                     handleGetTags(response.getText());    
  10.                 }    
  11.             }    
  12.            
  13.             public void onError(Request request, Throwable exception){    
  14.                 throw new UnsupportedOperationException("Not supported yet.");    
  15.             }    
  16.         });    
  17.     } catch (Exception e){    
  18.             e.printStackTrace();    
  19.     }    
  20. }  

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.

  1. public void handleGetTags(String jsonText){    
  2.     
  3.     JSONObject jsonObject;    
  4.     JSONString tagName;    
  5.     JSONNumber tagFreq;    
  6.     int frequency;    
  7.     String realTagName;    
  8.        
  9.     JSONValue jsonValue = JSONParser.parse(jsonText);    
  10.     JSONArray jsonArray = jsonValue.isArray();    
  11.        
  12.     if (jsonArray != null){    
  13.         for (int i = 0; i < jsonArray.size(); i++){    
  14.              jsonObject = (JSONObject)jsonArray.get(i);    
  15.              tagName = jsonObject.get("tag"      ).isString();    
  16.              tagFreq = jsonObject.get("frequency").isNumber();    
  17.              frequency = (int)tagFreq.doubleValue();    
  18.              Hyperlink tagLink = new Hyperlink(tagName.stringValue(),tagName.stringValue());    
  19.              flowPanel.add(tagLink);    
  20.         }    
  21.     }    
  22. }   

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.

  1. JSONValue jsonValue = JSONParser.parse(jsonText);   
  2. 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.

  1. for (int i = 0; i < jsonArray.size(); i++){    
  2.        
  3.     jsonObject = (JSONObject)jsonArray.get(i);    
  4.     tagName = jsonObject.get("tag"      ).isString();    
  5.     tagFreq = jsonObject.get("frequency").isNumber();    
  6.     frequency = (int)tagFreq.doubleValue();    
  7.     realTagName = tagName.stringValue();    
  8.     
  9.     //...   
  10.      
  11. }  

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.

  1. Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null);    
  2. 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.

  1. <html>    
  2.     <head>    
  3.         <title>Maintitle>    
  4.         <style>    
  5.             * {    
  6.                 padding : 0;    
  7.                 margin : 0;    
  8.                 font-family : "Lucida Grande","Lucida Sans Unicode",Arial,Verdana,sans-serif;    
  9.                 overflow : hidden;    
  10.             }    
  11.                
  12.             .cloudWrap {    
  13.                 text-align : center;    
  14.                 margin : 50px auto;    
  15.                 background-color : #333;    
  16.                 padding : 10px;    
  17.                 width : 400px;    
  18.                 line-height : 1.5em;    
  19.             }    
  20.                
  21.             .cloudTags {    
  22.                 float : left;    
  23.                 padding : 5px;    
  24.             }    
  25.                
  26.             .cloudTags a {    
  27.                 color : #FFFFFF;    
  28.                 text-decoration : none;    
  29.             }    
  30.         style>    
  31.     head>    
  32.     <body>    
  33.         <script language="javascript" src="in.cypal.studio.gwt.samples.TagCloud.nocache.js">script>    
  34.   
  35.           
  36.         <div id="wrapper" style="text-align:center">div>  
  37.     body>    
  38. 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.

  1. public void onModuleLoad() {    
  2.     getTagData();    
  3.     flowPanel = new FlowPanel();    
  4.     flowPanel.setStylePrimaryName("cloudWrap");    
  5.     RootPanel.get().add(flowPanel);   
  6. }  

The second is after adding a hyperlink to the FlowPanel.

  1. Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null);    
  2. flowPanel.add(tagLink);    
  3. 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.

  1. int maxFrequency = 0;    
  2. int minFrequency = 600000000;    
  3. final int MIN_FONT_SIZE = 5;    
  4. final int MAX_FONT_SIZE = 25;    
  5.   
  6. public void handleGetTags(String jsonText){    
  7.   
  8.     // ...    
  9.   
  10.     for (int i = 0; i < jsonArray.size(); i++){    
  11.         jsonObject = (JSONObject)jsonArray.get(i);    
  12.         tagFreq = jsonObject.get("frequency").isNumber();    
  13.         frequency = (int)tagFreq.doubleValue();    
  14.         if (minFrequency > frequency)    
  15.             minFrequency = frequency;    
  16.         if (maxFrequency < frequency)    
  17.             maxFrequency = frequency;    
  18.     }    
  19.        
  20.     // ...    
  21. }  

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.

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

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:

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

And our MainEntryPoint.java file should look like this:

  1. package org.yournamehere.client;   
  2.   
  3. import com.google.gwt.http.client.Response;   
  4. import com.google.gwt.http.client.Request;   
  5. import com.google.gwt.http.client.RequestBuilder;   
  6. import com.google.gwt.http.client.RequestCallback;   
  7.   
  8. import com.google.gwt.core.client.EntryPoint;   
  9. import com.google.gwt.core.client.GWT;   
  10. import com.google.gwt.dom.client.Style;   
  11. import com.google.gwt.json.client.*;   
  12.   
  13. import com.google.gwt.user.client.ui.FlowPanel;   
  14. import com.google.gwt.user.client.ui.Hyperlink;   
  15. import com.google.gwt.user.client.ui.RootPanel;   
  16.   
  17. public class MainEntryPoint implements EntryPoint {   
  18.   
  19.     FlowPanel flowPanel = null;   
  20.     int maxFrequency    = 0;   
  21.     int minFrequency    = 600000000;   
  22.   
  23.     final int MIN_FONT_SIZE = 5;   
  24.     final int MAX_FONT_SIZE = 25;   
  25.   
  26.     public void onModuleLoad() {   
  27.   
  28.         getTagData();   
  29.   
  30.         flowPanel = new FlowPanel();   
  31.         flowPanel.setStylePrimaryName("cloudWrap");   
  32.         RootPanel.get("wrapper").add(flowPanel);   
  33.     }   
  34.   
  35.     public void getTagData(){   
  36.   
  37.         String url = "/wmGetTags.php";   
  38.         RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url);   
  39.   
  40.         try{   
  41.             requestBuilder.sendRequest(nullnew RequestCallback() {   
  42.   
  43.                 public void onResponseReceived(Request request, Response response) {   
  44.   
  45.                     if (response.getStatusCode() == 200)   
  46.                         handleGetTags(response.getText());   
  47.                 }   
  48.   
  49.                 public void onError(Request request, Throwable exception) {   
  50.                     throw new UnsupportedOperationException("Not supported yet.");   
  51.                 }   
  52.             });   
  53.         } catch (Exception e){   
  54.             e.printStackTrace();   
  55.         }   
  56.     }   
  57.   
  58.   
  59.     public void handleGetTags(String jsonText){   
  60.   
  61.         JSONValue jsonValue = JSONParser.parse(jsonText);   
  62.         JSONArray jsonArray = jsonValue.isArray();   
  63.   
  64.         JSONObject jsonObject;   
  65.         JSONString tagName;   
  66.         JSONNumber tagFreq;   
  67.   
  68.         int frequency;   
  69.   
  70.         if (jsonArray != null){   
  71.   
  72.             for (int i = 0; i < jsonArray.size(); i++){   
  73.   
  74.                 jsonObject = (JSONObject)jsonArray.get(i);   
  75.                 tagFreq = jsonObject.get("frequency").isNumber();   
  76.   
  77.                 frequency = (int)tagFreq.doubleValue();   
  78.   
  79.                 if (minFrequency > frequency)   
  80.                     minFrequency = frequency;   
  81.   
  82.                 if (maxFrequency < frequency)   
  83.                     maxFrequency = frequency;   
  84.             }   
  85.   
  86.             for (int i = 0; i < jsonArray.size(); i++){   
  87.   
  88.                 jsonObject = (JSONObject)jsonArray.get(i);   
  89.   
  90.                 tagName = jsonObject.get("tag"      ).isString();   
  91.                 tagFreq = jsonObject.get("frequency").isNumber();   
  92.   
  93.                 frequency = (int)tagFreq.doubleValue();   
  94.   
  95.                 Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null);   
  96.                 tagLink.setStylePrimaryName("cloudTags");   
  97.   
  98.                 Style linkStyle = tagLink.getElement().getStyle();   
  99.                 linkStyle.setProperty("fontSize",getLabelSize(frequency));   
  100.   
  101.                 flowPanel.add(tagLink);   
  102.             }   
  103.         }   
  104.     }   
  105.   
  106.     public String getLabelSize(int frequency){   
  107.         double weight = (Math.log(frequency) - Math.log(minFrequency)) / (Math.log(maxFrequency) - Math.log(minFrequency));   
  108.         int fontSize = MIN_FONT_SIZE + (int)Math.round((MAX_FONT_SIZE - MIN_FONT_SIZE) * weight);   
  109.         return Integer.toString(fontSize) + "pt";   
  110.     }   
  111. }  

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 for more daily web development tuts and articles.
阅读(473) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~