Use the FusionCharts Free charting widget in the IBM Mashup Center

Using widgets with rich and highly customizable presentation in a mashup

Learn to build a charting widget with a very rich customizable presentation where both the charting data and presentation customization are specified in XML. Then learn how to use the data mashup editor from the IBM Mashup Center to generate the XML for such a widget. Finally, build a sample mashup in which the presentation elements vary dynamically with the data.

Louis Mau, Solution Architect, IBM

Louis Mau is part of the InfoSphere MashupHub development team. His current focus is to help customers build situational applications using the IBM Mashup Center. Prior to this role, he was the architect for DB2 Everyplace Sync Server, which helps synchronize data from enterprise databases onto a small-footprint database running on mobile devices.



09 December 2010

Also available in Japanese Portuguese

Introduction

Many forms of visualization have rich customizable presentations. Charting is one example. You might like to customize many visual aspects, such as color, label, caption, scale, and type. You might also like a map-based visualization where you can control the location and icon as well as display information when each marker is clicked. When the presentation information is complex and structured, XML is a good candidate for encoding the information.

This article describes how to do the following:

  1. Build a charting widget with a rich customizable presentation where you will specify both the charting data and the presentation customization in XML.
  2. Use the data mashup editor from the IBM Mashup Center to generate the XML for the widget.
  3. Build a sample mashup where the presentation elements vary dynamically with the data.

The IBM Mashup Center includes IBM InfoSphere® MashupHub and IBM Lotus® Mashups toolbox.

This article assumes that you are already familiar with building data mashups and with the basics of writing a widget. In particular, you need to know how to program in JavaScript and have experience using the IBM Mashup Center data mashup editor. The article IBM Mashup Center and the InfoSphere® MashupHub, Part 2: In-depth look at Feed Mashup Editor within IBM Mashup Center's InfoSphere MashupHub (see Resources) provides a good introduction to the data mashup editor. For an introduction to writing widgets, consult the article Mashups, beyond reporting (see Resources).

Building a charting widget

This section describes how to build a charting widget with a rich customizable presentation where you will specify both the charting data and the presentation customization in XML.

Understanding FusionCharts Free

The charting widget example used in this article is based on the FusionCharts Free charting package. FusionCharts provides numerous packages to chart and build maps. The article example uses the open-source FusionCharts Free version. It is a Flash charting component that supports the following chart types:

  • Common charts types, including pie, bar, and line
  • Combination charts that mix different types on a single chart by assigning different chart types to different series on the chart.
  • Special charts, such as Gantt charts for project management and candle-stick charts for stock prices.

To see examples of the supported chart types, visit the FusionCharts Free site in the Resources section and check out the Chart Gallery page. The site also contains product licensing, demos, and other information.

FusionCharts uses XML to specify both the data to be charted and the look and feel of the presentation. FusionCharts offers the perfect example of the power of using XML to specify data and presentation information.

The first part of the article describes how to build a thin widget wrapper around the FusionCharts Free package to turn it into a widget. The remainder of the article describes how to use the IBM Mashup Center to generate the XML. The IBM Mashup Center has feed generators to extract data from diverse data sources and convert them into feeds. A data mashup editor designed to augment and reformat the XML is included. The IBM Mashup Center offers an easy to way to generate XML in a format the FusionCharts Free package requires to create interactive and animated charts directly from data sources.

Creating a widget definition file

The FusionCharts Free (lightweight) widget package for this example should consist of a widget definition file, two JavaScript files, and swf files from the FusionCharts Free package. This section describes the widget definition file, iWidget.xml.

Listing 1 shows the root element of the XML file. The iScope attribute in the iwidget root element specifies the name of the JavaScript object that implements the iWidget callback functions. This widget is implemented using two JavaScript files. The FusionCharts.js comes from the FusionCharts Free package and the FCFWidget.js is our thin widget wrapper. They are loaded using two resource elements. For details on the attributes, consult the widget programming and API documentation link in the Resources section.

Listing 1. iWidget.xml header
<iw:iwidget name="FCFWidget" xmlns:iw="http://www.ibm.com/xmlns/prod/iWidget"
               iScope="FCFWidget"
               allowInstanceContent="true"
               supportedModes="view edit" mode="view" lang="en">

  <iw:resource uri="FusionCharts.js"/>
  <iw:resource uri="FCFWidget.js"/>

Listing 2 shows the definitions for the widget's receive and send events. The widget has one receive event for the input URL, which allows other widgets to change the charting XML. The widget also has one send event, which is fired when a chart element is selected. The receive event is indicated by the presence of the handled and onEvent attributes. The value of the onEvent attribute is the name of the function to call when the event is received. The published attribute indicates the send event.

Listing 2. iWidget.xml event specification
<iw:event id="Display from URL"
             handled="true" onEvent="graphURLChanged"
             eventDescName="desc_DataSourceURL"/>
<iw:eventDescription id="desc_DataSourceURL" 
                     payloadType="url"
                     description="Text representing a URL to a Fusion charts XML file"
                     lang="en"/>

<iw:event id="chartClicked" eventDescName="desc_chartClicked" published="true"/>
<iw:eventDescription id="desc_chartClicked"
                      payloadType="text"
                      description="A data element in the chart was clicked" lang="en"/>

The widget definition file also specifies what should appear in view and edit mode. The layout is specified by HTML markup included as CDATA in the iw:content element. Listing 3 shows the HTML markup for the view mode. There is a single div element with an id attribute that you can manipulate with JavaScript. The value of id uses _IWID_ as a prefix. The _IWID_ prefix will be replaced with the actual unique widget instance ID during widget creation. This ensures that all the IDs are unique, even if there are multiple instances of the widget on the same HTML page.

Listing 3. iWidget.xml view mode layout
<iw:content mode="view">
  <![CDATA[

  <div id="_IWID_chart"></div>

  ]]>
</iw:content>

This widget differs significantly from the existing charting widget shipped with FusionCharts Free. It takes the opposite approach of not providing an extensive configuration GUI. Instead, it exposes the underlying FusionCharts charting XML with all formatting controlled by XML. The edit mode section contains an HTML form with only two input elements: a textbox for entering the URL to the charting XML and a dropdown textbox for selecting the chart type. Listing 4 shows part of the HTML markup for the dropdown textbox. The dropdown options map the chart types to the underlying swf files implementing the corresponding charting logic. All swf files from the FusionCharts Free package are included in the widget zip file.

Listing 4. iWidget.xml edit mode layout
<iw:content mode="edit">
  <![CDATA[

  :::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  <select id="_IWID_chartType" >
        <option value='FCF_Area2D.swf'>2D Area</option>
        <option value='FCF_Bar2D.swf'>2D Bar</option>
            :::::::::::::::::::::::::::::::::::::::::::::::
  </select>

  :::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  ]]>
</iw:content>

See Resources for a link to download the complete widget package, which includes the complete iwidget.xml and all JavaScripts mentioned in this article.

Displaying the chart

The JavaScript implementation file is FCFWidget.js. The file is a dojo class that handles standard events, including load, unload, onview, onedit, and all other custom events and server communication. The onview function contains the logic to display the specified chart. See Resources for a description of the other standard events and their handling.

The onview function first determines the size of the widget and then calls the showChart function. Because the onview function is called after onedit or during initial load, you need to first retrieve the charting XML using an AJAX call. To indicate this, call the showChart function with the retrieveData parameter set to true. The onSizeChanged function can also call the showChart function, in which case set the retrieveData parameter to false to indicate that there is no change to the chart XML URL and that the data has already been loaded. In this case, you can call the showFusionChart function directly to instantiate the chart. Listing 5 shows the showChart function.

Listing 5. showChart function
    showChart: function( retrieveData )
    {
        this.debugTrace( "showChart w,h=" + this.width + ',' + this.height );  

        if ( retrieveData )
            this._loadDataUsingDojo( this.url
                                   , dojo.hitch( this, this._cbProcessReturnedXML ) );
        else if ( this.FCFgraphXML != null )
            this.showFusionChart( this.FCFgraphXML );
        // else ignore
    },

The JavaScript object FusionCharts contained in the file FusionCharts.js displays the chart. You need to instantiate an instance of FusionCharts by passing the following parameters:

  • A URL that points to the swf file for the user's chosen chart type. Remember that all the swf files are included in the widget zip file. To get the fully qualified URL to where all the zip file content is located, call the rewriteURI method from the iContext function.
  • A unique value to be used as the ID for the FusionCharts-generated HTML element.
  • The width of the chart.
  • The height of the chart.

The charting XML data is passed to the FusionCharts object using the setDataXML function. Then the render function is used to instantiate the chart, as shown in Listing 6.

Listing 6. Show Fusion Chart function
    //The following is mostly from Fusion Chart
    showFusionChart: function( strXML )
    {
        var swfUrl = this.iContext.io.rewriteURI( this.charttype );
        var chart1 = new FusionCharts(swfUrl, "FC"+this.domID
                                     , this.width, this.height, "0", "0");
        chart1.setDataXML(strXML);
        chart1.render( this.domID + "chart" );		
    },

Note that two small changes are made to the FusionCharts.js file from the FusionCharts Free package. The wmode parameter needs to be set to opaque in two places to ensure that the chart doesn't interfere with the dropdown menu. Both changes are marked with // zPOSCHANGE.

Handling the click event

All the charts in the FusionCharts suite support drill down. In each chart type, the display elements (columns in column charts, pie slices in pie charts, and so on) can act as hotspots for the chart. In FusionCharts Free, you can define the following types of actions for the hotspots:

  • Simple links that open in the same page
  • Simple links that open in a new page
  • Existing JavaScript functions (on the same page) to be invoked as links

FusionCharts uses set elements in the charting XML to specify the values to be displayed. To specify any hotspot actions, add the optional link attribute to the set elements. For the example, you want your widget to be able to generate an event when a hotspot is clicked. You can do that by providing a built-in JavaScript function MCClickEvent with a single parameter. The function fires an event when called. Listing 7 shows how to call the built-in function MCClickEvent, passing the string '2005,1020' as an argument in the link attribute.

Listing 7. Link attribute specifying MCClickEvent function
  <set  name="2005"
        value="1735.08"
        link="JavaScript: MCClickEvent( '2005,1020' );" />

In Listing 8, The MCClickEvent function is very simple. It takes a single argument and simply calls the fireEvent function from the iContext function.

Listing 8. Sending click event function
    MCClickEvent: function( arg ) {
        this.iContext.iEvents.fireEvent("chartClicked", null, arg );
    },

The MCClickEvent function is not global to the page, but it is an instance method. For the FusionCharts Free component to call it, you need to invoke it from a JavaScript instance that represents the widget. Because the JavaScript instance is not known until the widget is instantiated on a page, use the internal modifyLink function to rewrite the JavaScript function call, as shown in Listing 9. The function is called to preprocess the charting XML before it is passed to the FusionCharts object.

    modifyLink: function( strXML )
    {
        var temp   = this.domID + "iContext.iScope().MCClickEvent";
        var result = strXML.replace( /JavaScript: MCClickEvent/g, "JavaScript: "+temp );
        return result;
    },

This completes the description of the implementation of the widget. Some possible enhancements include support for changing the chart type in view mode or in-place drill down.

Now that you have a widget that uses XML for presentation information, use the IBM Mashup Center to generate the charting XML.


Using the data mashup editor to generate the XML

See Resources for online documentation about the charting XML that is available at the FusionCharts Free site. For the example, use the column 2D chart to generate the XML in Listing 10. The chart shows the yearly sales for the year from 2005 to 2008 for a given customer. Note that CUSTOMERNAME is just a placeholder in the sample, and it is generated dynamically. Each set element is represented by a column in the chart. The set elements correspond to yearly sales, and they are configured to be hotspots with the link attributes. When a column for a given year is clicked, you want to generate an event that provides the customer ID (1020 in the sample) and year as a comma-separated string. This information enables you to drill down into monthly sales for the given customer for the given year.

Listing 10. Yearly sale column 2D XML
<graph  caption="Sales to CUSTOMERNAME"
         xAxisName="Year" yAxisName="Sales" decimalPrecision="0">
  <set  name="2005"
        value="1735.08"
        link="JavaScript: MCClickEvent( '2005,1020' );" />
  <set  name="2006"
        value="1335.08"
        link="JavaScript: MCClickEvent( '2006,1020' );" />
  <set  name="2007"
        value="1582.08"
        link="JavaScript: MCClickEvent( '2007,1020' );" />
  <set  name="2008"
        value="1555.08"
        link="JavaScript: MCClickEvent( '2008,1020' );" />
</graph>

As input, start with a feed generated from the database shown in Listing 11. You can use the IBM Mashup Center data mashup editor to transform it to the FusionCharts format. You will also learn about some of the newer features in Version 3 of IBM Mashup Center.

Listing 11. Input database feed
<entry><content>
   <year>2005</year><totalAmt>1735.08</totalAmt>
</content></entry>
<entry><content>
   <year>2006</year><totalAmt>1335.08</totalAmt>
</content></entry>
<entry><content>
   year>2007</year><totalAmt>1582.08</totalAmt>
</content></entry>
<entry><content>
   <year>2008</year><totalAmt>1555.08</totalAmt>
</content></entry>

Consult the articles in Resources if you need to review the basics on using the IBM Mashup Center data mashup editor.

Generating the set element

The first step in creating a data mashup is to use a Source operator to specify the input feed (XML data). After specifying the feed, you need to override the Feed type on the Advanced tab of the property dialog. Choose the complete feed as a single repeating entry, as shown in Figure 1. The reason is explained in Using the FusionCharts widget using IBM Mashup Center v2.

Figure 1. Source operator Advanced tab
shows /atom:feed highlighted as repeating element

Next, connect the Source operator to the Transform operator and open its property dialog. To create a set element in the output (right side of the Transform operator), select New element from the popup menu when you right-click on the entry element. The set element should have three attributes:

  • name for the column label
  • value for the height of the column
  • link for generating the event

After creating a name attribute underneath the set element using the popup menu, expand the entry element on the input (left) side of the transform operator until the text node under the year element is visible. Right-click the text node, and select Copy to the output tree to copy the text 2005 to the name attribute on the output tree. There should be four entry elements, each containing a year on the input tree (the left side of the transform operator). This is indicated by a blue loop icon next to the entry element. The data mashup editor takes this into account and creates four new set elements: one for each year. Figure 2 shows the output tree.

Figure 2. Transform operator specifies name attribute value
Shows copy to the output tree selected

The value attribute can be created similarly. For the link attribute, its value is not a direct copy of any value from the input side. Instead, it has to be computed. To do that, after creating the link attribute, right-click to bring up the context menu, and select Edit Value, as shown in Figure 3.

Figure 3. Transform operator specify link attribute value
shows Edit Value selected in context menu

In IBM Mashup Center, Version 3, a dialog pops up that enables you to use a variable or a function and not just provide a hardcoded value. Here, select Specify a function value, as shown in Figure 4. (In IBM Mashup Center Version 2, you cannot specify a function directly as an attribute value. Instead, you need to create the function value for an element and then copy it to the attribute.)

Figure 4. Link attribute value dialog
shows specify a function value selected

To generate the JavaScript call described in Handling the click event, select the concat function. If you recall, the built-in MCClickEvent function takes only a single argument. When a year column is clicked, you want to drill down into the monthly sales for the selected year. To do this, pass two arguments: the customer ID and the year by generating a comma-separated string with the two values. Figure 5 shows the values for all the arguments.

shows entry values for the strings

Now you can generate the set element. Go to the Preview tab and verify that the output is what you expect before you generate the root element using the Publish operator.

Using a header template

All that remains now is to generate graph as the root element and add all the necessary global presentation attributes such as an x-axis label. In Version 3 of IBM Mashup Center, the publish operator has a new custom header option. Clicking the Custom radio button brings up the Header Template section with a single default root element. Similar to the transform operator, rename the root element to graph and use the popup menu New Attribute to generate the presentation attributes. However, there is an easier way. From the root element popup menu, select Set Template Tree, as shown in Figure 6.

Figure 6. Publish operator custom header
shows Set Template Tree selected

Click the Set Template Tree menu to bring up a dialog where you can enter an XML fragment and have it imported into the editor, as shown in Figure 7. When you are importing a large number of attributes, this could be a big time saver.

Figure 7. Publish operator set template
shows entry field for entering XML document

Note that the root element changed into graph with all the associated attributes in the template.

Now add the set element created earlier by selecting Attach repeating element from the graph element popup menu, as shown in Figure 8 and Figure 9.

Figure 8. Custom Header Attach menu
shows Attach repeating element selected in popup menu
Figure 9. Publish Operator Attach dialog
to attach a repeating element, you select an item from the tree structure

Creating a dynamic presentation

One of the advantages of configuring the presentation through input XML is the capability of having the presentation elements vary with the data. For the example, when displaying the yearly sales data for company X, you can easily change the caption to say Sales to Company X. Assume that there is a simple feed to retrieve the company name if given the company ID. Use the feed to add (using a merge) a company name element, and then use the concat function in the publish operator to construct the value of the caption attribute, as shown in Figure 10.

Figure 10. Caption with customer name
shows field where you enter customization string

The data mashup is now complete. Before leaving this section, note the following related usages:

  • Because the presentation elements are generated dynamically, you can use a similar technique to generate the presentation according to the browser accepted-language setting.
  • It is easy to include HTML markup in the presentation elements once the presentation is in an XML format. The inclusion of the logo for an RSS feed is a simple example. Figure 11 shows the IBM Mashup Center feed widget displaying the logo, which varies with the feed content.
Figure 11. Logo specified in RSS feeds
Examples shows Yahoo and CNN logos included in RSS feeds

Using the FusionCharts widget with the IBM Mashup Center, Version 2

Version 2 of the IBM Mashup Center does not allow attributes to be added to the root element. To compensate for this restriction, the widget also supports one format variation. The widget accepts any valid FusionCharts Free charting XML that is wrapped by a dummy root element mhubFusion. The steps described in Generating the set element work for Version 2 as well, because the steps result in a single repeating entry with four set elements. Listing 12 shows how Listing 10 is adapted for Version 2.

Listing 12. Special v2 format
<mhubFusion>
   <graph  caption="Sales to CUSTOMERNAME"
            xAxisName="Year" yAxisName="Sales" decimalPrecision="0">
     <set  name="2005"
           value="1735.08"
           link="JavaScript: MCClickEvent( '2005,1020' );" />
     <set  name="2006"
           value="1335.08"
           link="JavaScript: MCClickEvent( '2006,1020' );" />
     <set  name="2007"
           value="1582.08"
           link="JavaScript: MCClickEvent( '2007,1020' );" />
     <set  name="2008"
           value="1555.08"
           link="JavaScript: MCClickEvent( '2008,1020' );" />
   </graph>
</mhubFusion>

Putting the pieces together

Figure 12 shows a mashup application running on the IBM Mashup Center. The application has a list of customers at the top. The list is wired to the chart on the bottom left. The chart displays the yearly sales of the customer selected in the list. It uses the FusionCharts Free widget and the data mashup you created in this article. It is wired to the monthly sales FusionCharts Free widget on the bottom right. If you click the column representing sales for any given year, the customer ID and year is sent in the chartClicked event. This causes the monthly sales chart to display the sales data for the selected year and customer.

Figure 12. The complete mashup application
Mashup Center Drill Down shows table with customer IDs and info, plus bar charts with FusionCharts windows showing yearly and monthly sales

(View a larger version of Figure 12.)

See Resources for a working example of the mashup you created. Use the space manager, and search for Charting demo.

Conclusion

This article took you through the basic steps of constructing a data mashup to generate XML for column 2D charts. The FusionCharts Free package includes many other chart types. Try generating XML for the more complicated chart types and enhancing the widget. If you have the opportunity to create a widget, consider specifying presentation information with the data in an input XML file rather than creating an elaborate input form in which users enter hardcoded values.


Download

DescriptionNameSize
ExampleFusionCharts.zip447KB

Resources

Learn

Get products and technologies

  • Get hands-on experience with IBM Mashup Center bv visiting Lotus greenhouse.
  • Download a free trial version of IBM Mashup Center from developerWorks.
  • Build your next development project with IBM trial software, available for download directly from developerWorks.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Information management on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Information Management, Lotus, XML
ArticleID=594542
ArticleTitle=Use the FusionCharts Free charting widget in the IBM Mashup Center
publish-date=12092010