Leveraging pureXML in a Flex microblogging application, Part 2: Building the application user interface with Flex

Tap into Flex and ActionScript for a user interface that connects DB2-powered Web services

The pureXML® capabilities of IBM DB2® allow you to store XML natively in a database without modification, while Adobe® Flex® applications can read XML directly and populate Flex user interfaces. In this three-part article series, you will create a microblogging application that takes advantage of pureXML, Web services, and Adobe Flex; and even allows you to publish your microblogging updates on Twitter. In Part 1 of the series, you learned about Web Services and how they are enabled using DB2 pureXML as you created the microblog database and tested it. In this article, Part 2 of the series, you will tap into Adobe Flex and ActionScript® to create the user interface of the application.

Joe Lennon, Software developer, Freelance

Joe Lennon photoJoe Lennon is a 24-year-old software developer from Cork, Ireland. Joe is author of the forthcoming Apress book Beginning CouchDB, and has contributed several technical articles and tutorials to IBM developerWorks. In his spare time, Joe likes to play football (soccer), tinker with gadgets and work on his Xbox 360 gamer score.


developerWorks Contributing author
        level

03 November 2009 (First published 20 October 2009)

Also available in Chinese Russian Japanese Portuguese

Prerequisites

In this series, you will use the open source Flex SDK to build our sample application. See Resources for a link to the Adobe Flex product page. You need to install the DB2 database server—the Express-C edition of DB2. For information on how to download and install DB2 Express-C, see Resources. You will also use IBM® Data Studio and WebSphere® Application Server Community Edition (hereafter referred to as Community Edition) to deploy the services on a Web server. See Resources for download information.


Introduction to Flex

Frequently used acronyms

  • Ajax: Asynchronous JavaScript + XML
  • HTML: Hypertext Markup Language
  • HTTP: Hypertext Transfer Protocol
  • IDE: Integrated Development Environment
  • MXML: Minimal XML
  • REST: REpresentational State Transfer
  • RSS: Really Simple Syndication
  • SDK: Software Development Kit
  • UI: User interface
  • XML: Extensible Markup Language

Adobe Flex is an open-source application development framework that facilitates the development of Rich Internet Applications (RIAs), which you can deploy to any computer that supports Adobe Flash®. These applications can be Web-based, requiring the Adobe Flash Player plugin to be installed on the user's Web browser, or desktop-based, usually deployed using the Adobe AIR™ platform.

A primary benefit of using Flex for RIA development over Ajax-based development is that you don't need to be concerned about ensuring that your application will work consistently across all Web browsers and operating systems. A Flex application will appear the same no matter what environment you use it on—so long as Adobe Flash is installed.

To develop Flex applications, you have two primary options. You can download the freely available, open source Flex SDK, which contains tools that allow you to compile and debug your Flex apps. Alternatively, you can choose to purchase Adobe's Flex Builder IDE, which provides many tools that will aid in the development of your Flex applications, including drag-and-drop user interface design. This IDE is built on top of the open source Eclipse platform, and is also available as an Eclipse plugin.

Flex and XML

Flex application development is usually divided into two areas:

  • Defining the application user interface in MXML
  • Defining the application logic in ActionScript

Flex supports ActionScript 3.0, which is best known for its use in Flash development. This scripting language supports XML data through a group of classes that adhere to the ECMAScript for XML (E4X) specification. Using these classes, it is simple to develop Flex applications that work with XML data.

Rather than directly communicate with a database server, Flex applications typically work with data using Web services that are accessible using a RESTful HTTP or SOAP interface. You will see an example of this in action when you build the sample application later in this article.

The sample application

The sample application is a simple user interface for a microblogging application. This application allows you to:

  • Create a new status update
  • View your previous status updates

The first stage of developing the application is to create the user interface using MXML and define the logic for the application using ActionScript. You will then see how to store the data for the application in an XML file. Finally, you will configure the application to communicate with the Web service that you created in Part 1 of this series, so the data for the application is stored in and retrieved from a DB2 pureXML database.

The final application looks like the screen capture in Figure 1.

Figure 1. The Flex microblog application user interface
Screen capture of the Flex microblog application UI with status update and previous updates fields

Installing the Flex SDK

In this series, you will use the open source Flex SDK to build a sample application. Download and install the Flex SDK now. On the Adobe Flex product page (see Resources for a link), you'll find a link to "Get the Free Flex 3.x SDK" on the right hand side, as highlighted in Figure 2. You can download the SDK from the destination page of that link.

Figure 2. Adobe Flex product page
Screen capture of Adobe Flex product page with highlighted 'Get the Free Flex 3.x SDK' link

After you successfully download the zip archive (it may take a while; the file I downloaded was 120 megabytes in size), extract the contents to the folder C:\flex. There's no installer to run or anything like that. Before you move on however, add the directory that contains the Flex compiler to your system's path. This will allow you to compile Flex source code without having to specify the location of the Flex compiler each and every time.

In Control Panel, open System and then click the Advanced tab. Click Environment Variables, which is near the bottom of the window, as in Figure 3

Figure 3. Environment variables
Screen capture of the Advanced tab on the System Properties dialog with highlighted 'Environment Variables' button

From the System variables section in the bottom half of the Environment Variables dialog, scroll to find the Path variable, as in Figure 4.

Figure 4. Path environment variable
Screen capture of the highlighted Path environment variable on the Environment Variables dialog

Double-click the Path variable to open the Edit System Variable dialog. In the Variable value field, keep the existing value, and add the following to the end: ;c:\flex\bin. For an example, see Figure 5.

Figure 5. Edit Path Variable dialog
Screen capture of the updated Variable value field on the Edit Path Variable dialog

Press OK to close all the dialog boxes that are open. You are now ready to start developing some Flex applications! Let's test that the Flex compiler is on your Path and see what it is like to develop a Hello World Flex application. Create a new folder on your computer, c:\flexapps, where you will store the application source code. Now create a subfolder within it named hello: c:\flexapps\hello. Open a plain text editor (Notepad will do fine) and enter the code in Listing 1, saving the file as hello.mxml in your hello folder.

Tip: If you are using Notepad, when you go to save the file, wrap the filename in double-quotes (for example, "hello.mxml") to stop Notepad from appending the .txt extension to your file.

Listing 1. hello.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
  xmlns:mx="http://www.adobe.com/2006/mxml"
  horizontalAlign="center" verticalAlign="center"
  width="400" height="300">
    <mx:Script>
      <![CDATA[
        import flash.events.MouseEvent;

        private function helloHandler(event:MouseEvent):void {
          if(btnHello.label == "Hello!") {
            btnHello.label = "World!";
          } else {
            btnHello.label = "Hello!";
          }
        }
      ]]>
      </mx:Script>
      <mx:Button id="btnHello" label="Hello!"
        click="helloHandler(event);" />
</mx:Application>

I'll briefly walk through this source code. First off, the XML declaration tells the compiler that this file is an XML document that uses UTF-8 encoding. Next, open your main MXML Application tag (mx:Application), passing in properties such as width, height, and alignment to define the size and layout of your application. The next section, in Listing 1, is an MXML Script block (mx:Script), which contains ActionScript code. In this example, the ActionScript simply defines a function, which triggers when the user clicks a button. The function checks what text the button currently shows and changes it.

After the closing mx:Script tag, create an MXML Button tag (mx:Button), giving it an id attribute that will allow the ActionScript code to find it easily. Also create a label attribute, which defines the text to show on the button, and an event handler; in this instance, you ask the click event to call the helloHandler function.

Now compile your code using the Flex compiler. Open the command prompt (Start>Programs>Accessories>Command Prompt). To change to your hello project folder, issue the command: cd \flexapps\hello.

To compile your MXML file, issue the following command: mxmlc hello.mxml.

You should see a result similar to that in Figure 6. (View a text-only version of Figure 6.)

Figure 6. Compiling your first application
Screen capture of results from compiling the Hello World Flex application

This has created a new file in your hello folder named hello.swf. To open this at the command prompt, simply type the name, or alternatively, double-click on the file in Windows® Explorer.

Tip: If you don't have a standalone Adobe Flash player installed, you should be able to open the SWF file with your Web browser. Alternatively, you can download debug and release builds of a standalone Adobe Flash Player (the debug version is great for finding bugs in your Flex applications). See Resources for a link.

The application should look like the one in Figure 7.

Figure 7. Our first application
Screen capture of Hello World application in Adobe Flash Player window

To toggle the text on the button In the application in Figure 7, click Hello! to change the text of the button to "World!" and click World! to return the text back to "Hello!". In the next section, you will create the interface for your main sample application.


Developing the sample application

Let's go ahead and start to develop the microblog application. The first thing to do is create a new folder for the application: c:\flexapps\microblog. Now use your text editor to create a new file and save this file as microblog.mxml in the folder you just created. You will place your application's code in this file. Now let's get started on the user interface!

Creating the user interface

The first step in developing your Flex application is to create the user interface. While there are several ways to work with UIs in Flex, you will use MXML components to layout your application. By the end of this section, you should have an application that looks like Figure 8, complete with remaining character count functionality.

Figure 8. The microblog application UI
Screen capture of the microblog application with text in the status update field and remaining character count

To create this interface, put the code from Listing 2 into your microblog.mxml file.

Listing 2. microblog.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
  layout="absolute" width="600" height="400">
    <mx:Script>
    <![CDATA[
      import flash.events.Event;

      private function statusChangeHandler(event:Event):void {
        remaining.text = String(140 - status.length);
      }
    ]]>
    </mx:Script>
    <mx:Panel layout="absolute" left="10" right="10"
      top="10" bottom="10" title="Microblog">
        <mx:Label x="10" y="10" text="Update your status:"/>
        <mx:Label x="525" y="10" text="140" id="remaining"/>
        <mx:TextArea x="10" y="30" width="540" id="status"
            maxChars="140" change="statusChangeHandler(event);"/>
        <mx:Button x="499" y="80" label="Post" id="post"/>
        <mx:Label x="10" y="105" text="Previous updates:"/>
        <mx:VBox x="10" y="125" width="540" height="180"
          borderStyle="solid">

        </mx:VBox>
        <mx:Button x="480" y="312" label="Refresh" id="refresh"/>
    </mx:Panel>
</mx:Application>

Now open the command prompt and navigate to the microblog folder with the following command: cd \flexapps\microblog.

Issue the following command to compile the application source code: mxmlc microblog.mxml.

If the compilation succeeds, you should now have a microblog.swf file in your project folder. Open this file using Flash Player (or your Web browser with Flash Player plugin installed) and you should see a screen like the one you saw previously in Figure 8.

This file isn't much more complicated than the Hello World application you developed earlier in this article. You used absolute positioning to place the UI controls using x and y coordinates—and you introduced some other Flex controls—mx:Panel, mx:Label, mx:TextArea and mx:VBox. The mx:Panel control is a container control that is used for layout purposes. In this instance you use it as a window-style container for the application. The mx:Label control is simply a descriptive text label. One of the labels used here has an id remaining and you use it to denote how many more characters can be entered into the statusmx:TextArea control. On this control you have a change attribute which defines the function to call when the change event is fired.

The final new control introduced here is the mx:VBox control. Like mx:Panel, this is a container control and is used to layout controls. You will use this in the next section to house previous status updates.

With your application shell created, you can move on and populate your VBox control with some status updates from an XML file.

Storing updates in an XML file

First, create an XML file that will be used by your application to retrieve a list of status updates and populate your application's Previous updates section. In the same directory as the microblog.mxml and microblog.swf files, create a new file named updates.xml and add the code from Listing 3 to it.

Listing 3. updates.xml
<?xml version="1.0"?>
<updates>
    <update>
        <text>Flex and XML are an awesome combination!</text>
        <date_created>2009-09-02 23:45:01</date_created>
    </update>
    <update>
        <text>Finished a hard day of work, phew...</text>
        <date_created>2009-09-01 19:02:57</date_created>
    </update>
    <update>
        <text>I think I need some strong coffee right now.</text>
        <date_created>2009-09-01 11:14:51</date_created>
    </update>
    <update>
        <text>Less than an hour till lunch time! Mmmm food...</text>
        <date_created>2009-08-31 12:04:43</date_created>
    </update>
    <update>
        <text>Playing some Xbox 360!</text>
        <date_created>2009-08-22 09:44:27</date_created>
    </update>
    <update>
        <text>Creating a DB2 database</text>
        <date_created>2009-08-15 23:30:36</date_created>
    </update>
    <update>
        <text>Half-day today woohoo</text>
        <date_created>2009-08-06 01:28:19</date_created>
    </update>
    <update>
        <text>Looking forward to Snow Leopard being released</text>
        <date_created>2009-08-03 14:19:08</date_created>
    </update>
    <update>
        <text>Time to go home! Yipeeeee!</text>
        <date_created>2009-07-30 18:00:50</date_created>
    </update>
</updates>

Of course, feel free to use your imagination and change the text of these updates! Now let's make some modifications to your Flex application to load and present this XML data to the user. In addition, you'll add some code to make the Refresh button work.

The code in Listing 4 is the updated microblog.mxml file.

Listing 4. microblog.mxml (Updated)
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
  xmlns:mx="http://www.adobe.com/2006/mxml"
  layout="absolute" width="600" height="400"
  creationComplete="updateData.send()">
      <mx:HTTPService url="updates.xml" id="updateData"
  resultFormat="e4x"/>

      <mx:Script>
      <![CDATA[
        import flash.events.Event;
        import flash.events.MouseEvent;

        private function statusChangeHandler(event:Event):void {
            remaining.text = String(140 - status.length);
        }

        private function refreshClickHandler(event:MouseEvent):void {
            updateData.send();
        }
      ]]>
      </mx:Script>

      <mx:XMLListCollection id="xmlUpdates"
  source="{updateData.lastResult.update}"/>

    <mx:Panel layout="absolute" left="10"
      right="10" top="10" bottom="10"
      title="Microblog">
        <mx:Label x="10" y="10" text="Update your status:"/>
        <mx:Label x="525" y="10" text="140" id="remaining"/>
        <mx:TextArea x="10" y="30" width="540" id="status"
          maxChars="140" change="statusChangeHandler(event);"/>
        <mx:Button x="499" y="80" label="Post" id="post"/>
        <mx:Label x="10" y="105" text="Previous updates:"/>
        <mx:VBox x="10" y="125" width="540" height="180"
          borderStyle="solid">
            <mx:Repeater id="r" dataProvider="{xmlUpdates}">
                <mx:Text text="{r.currentItem.text} (Posted: 
{r.currentItem.date_created})"/>
            </mx:Repeater>
        </mx:VBox>
        <mx:Button x="480" y="312" label="Refresh" id="refresh"
            click="refreshClickHandler(event);"/>
    </mx:Panel>    
</mx:Application>

The most important new element to note here is the mx:HTTPService control, which you use to load in your XML file. You'll notice that you created a new attribute in the mx:Application tag called creationComplete, which calls the send method on your mx:HTTPService object. This basically tells the application to load the XML file as soon as the application has loaded.

As is often the case with Flex development, you can use many different techniques to take the data from your XML file and prepare it for use in your Flex application. In this example, you use an mx:XMLListCollection, which is then used by an mx:Repeater as a data provider. This mx:Repeater control basically takes the controls inside it and repeats them for every iteration in the data source it uses. Since your XML file has 9 records, the mx:Repeater control will output 9 mx:Text controls inside the mx:VBox control.

Finally, you added an event handler to the Refresh button, which basically reloads the data from XML file whenever the button is pressed.

Open your Command Prompt window and navigate to the project folder as you did previously. Now compile the application using the command: mxmlc microblog.mxml.

Open the microblog.swf file. Whoops, it didn't like that, did it? You should get an error message like the one shown in Figure 9. (View a text-only version of Figure 9.)

Figure 9. ActionScript error
Screen capture of ActionScript local file error in Adobe Flash Player window

A quick read of the error will tell you that Flash did not load the local file. This is a security feature that prevents applications being used maliciously over a network or the Internet. Because you are loading files from the file system, you need to tell the Flex compiler that you are not deploying the application on the network: mxmlc -use-network=false microblog.mxml.

This time when you run the resulting microblog.swf file you should see a much more satisfying result, like the one in Figure 10.

Figure 10. Your XML-enabled application in action
Screen capture of the XML-enabled application in action with items in 'Previous updaes' field

In the next section you'll tie your Flex application into the Web service you created in Part 1 of this article series.


Integrating with pureXML Web services

Up until now, you have always run your microblog SWF file locally from the file system. To meet security policies for accessing external Web services, for this example you will deploy your SWF file to the WebSphere Application Server where your Web services are deployed.

The first thing to do is modify your application and tell it which Web services to use for posting new updates and for retrieving the existing ones. Open microblog.mxml and change it so it matches the code in Listing 5.

Listing 5. microblog.mxml (Final Version)
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
  xmlns:mx="http://www.adobe.com/2006/mxml"
  layout="absolute" width="600" height="400"
  creationComplete="updateData.send()">
      <mx:HTTPService url="http://localhost:8080/MicroblogStatusUpdates
/rest/StatusUpdates/getAllUpdates" id="updateData"
  resultFormat="e4x"/>
    <mx:HTTPService url="http://localhost:8080/MicroblogStatusUpdates/
rest/StatusUpdates/insertUpdate" id="newUpdate"
  resultFormat="e4x"/>

      <mx:Script>
      <![CDATA[
        import flash.events.Event;
        import flash.events.MouseEvent;
       
        private function statusChangeHandler(event:Event):void {
            remaining.text = String(140 - status.length);
        }

      private function postClickHandler(event:MouseEvent):void {
        var params:Object = new Object();
        params.C_TEXT = status.text;
        params.C_DISPLAY = true;
        newUpdate.send(params);
        updateData.send();
  }

        private function refreshClickHandler(event:MouseEvent):void {
            updateData.send();
        }
      ]]>
      </mx:Script>

      <mx:XMLListCollection id="xmlUpdates"
  source="{updateData.lastResult.row}"/>

    <mx:Panel layout="absolute" left="10"
      right="10" top="10" bottom="10"
      title="Microblog">
        <mx:Label x="10" y="10" text="Update your status:"/>
        <mx:Label x="525" y="10" text="140" id="remaining"/>
        <mx:TextArea x="10" y="30" width="540" id="status"
          maxChars="140" change="statusChangeHandler(event);"/>
        <mx:Button x="499" y="80" label="Post" id="post"
  click="postClickHandler(event);"/>
        <mx:Label x="10" y="105" text="Previous updates:"/>
        <mx:VBox x="10" y="125" width="540" height="180"
          borderStyle="solid">
            <mx:Repeater id="r" dataProvider="{xmlUpdates}">
                <mx:Text text="{r.currentItem.DATA.update.text} (Posted:
 {r.currentItem.DATA.update.date_created})"/>
            </mx:Repeater>
        </mx:VBox>
        <mx:Button x="480" y="312" label="Refresh" id="refresh"
            click="refreshClickHandler(event);"/>
    </mx:Panel>    
</mx:Application>

The primary changes in this version of your application source code are that you removed the local XML mx:HTTPService control, and replaced it with two mx:HTTPService controls that are used to retrieve the existing status updates from the Web service, and to send new status updates to it. Only the mx:HTTPService that retrieves data will be called when the application is launched, as you need to accept user input in order to create any new data.

The next major change is the definition of a postClickHandler function in your ActionScript mx:Script block. In this function, you define a new object and assign the C_TEXT and C_DISPLAY fields of this object to values. It is important that you pass the correct case for these parameters or any requests to the Web service will fail. You then pass this object as an argument to the send method of the newUpdate mx:HTTPService control. Finally, to refresh the view of your data, ping the component that retrieves data from the Web service. You'll also notice further down the code that you set the Post button to class this function when the click event is fired.

Because of the way your Web service displays the XML stored in the pureXML database, you need to make some small changes to the source of the mx:XMLListCollection component. Each update is contained at the top level within a <row> tag, so you define the source as updateData.lastResult.row.

The final point to note is that you have also changed the fields used in the text attribute of your repeated mx:Text component. Once again, this has been changed to match the format of the XML produced by your Web service. Each row looks like Listing 6 in XML.

Listing 6. XML of each row
<row>
    <DATA>
        <update>
            <text>Update text</text>
            <date_created>Date/time value</text>
        </update>
    </DATA>
</row>

As a result, you need to tell your mx:Text component to look at r.currentItem.DATA.update.text and r.currentItem.DATA.update.date_created to get the correct values for each of these tags.

Now open your command prompt, navigate to the project folder, and compile the MXML source file once more. Because you are deploying the SWF file to an application server, and because your application is using network data rather than local data, you do not use the -use-network=false argument. In other words, the command for compiling the source code is once again: mxmlc microblog.mxml.

This time, if you try to run the microblog.swf file directly on your computer, you will get an error like the one in Figure 11. (View a text-only version of Figure 11.)

Figure 11. Security error
Screen capture of ActionScript security error in Adobe Flash Player window

You can spend a lot of time trying to configure cross-domain policies on your WebSphere application server, but it's much easier to simply deploy the SWF file itself to the application server. Locate the microblog.swf file in Windows Explorer, right-click on it and click the Copy option. Now open IBM Data Studio and connect to the MBLOG database. Open the Navigator view (Window>Show View>Navigator), where you should see three folders, the third of which should be called MicroblogStatusUpdatesWeb. Expand this folder, right-click the WebContent folder, and click Paste. If you did this correctly, microblog.swf will now be stored on the server as in Figure 12.

Figure 12. Deploying microblog.swf to Application Server
Screen capture of navigator view of Data Studio with microblog.swf deployed to Application Server

Now, start your Community Edition (WASCE) server instance. When the server is ready, open your Web browser and navigate to http://localhost:8080/MicroblogStatusUpdates/microblog.swf. Check out the microblog application and verify that it retrieves the status updates from the database. Also try to post a new update and check that it gets stored in the database and added to the list of previous updates. To check that the Refresh button works, create a new row in the database using DB2 Command Editor, and then click Refresh to see if the new row is retrieved.

The final product looks like the screen capture in Figure 13.

Figure 13. The final product
Screen capture of the final microblog product with status and previous updates fields

Summary

In this article, you learned how to use Adobe Flex to create a rich user interface that connects to the DB2-powered Web services that you created in the first part of the series.

In the final article in this series, Part 3, you will take the data from your Web services and pureXML and expose them in different formats—notably RSS and HTML—and integrate your application with the uber-popular microblogging Web site, Twitter.


Download

DescriptionNameSize
Article source codexmlflexpt2.source.zip3KB

Resources

Learn

Get products and technologies

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 XML on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Information Management, Open source, Web development
ArticleID=436559
ArticleTitle=Leveraging pureXML in a Flex microblogging application, Part 2: Building the application user interface with Flex
publish-date=11032009