Chapter 11. Developing a Stock Ticker with BlazeDS

IN THIS CHAPTER

  • Installing BlazeDS

  • Understanding messaging in Flex

  • Developing a stock ticker application

In this chapter, you learn how to install, configure, and develop applications by using Flex and BlazeDS. Once the BlazeDS service is properly working, you create a complete stock ticker with real-time capabilities.

You also learn how to work with the messaging components in Flex, which allow applications to be more responsive and stable.

Developing Flex applications can require many different tools and libraries, even when related to Java development specifically. As you have probably seen in previous chapters, Java offers various tools and libraries, each having a proper use. You often stick to the tools that work, but the goal of learning is to gain a well-rounded view of all the various options.

Once you have completed this chapter, you should have a firm understanding of what BlazeDS has to offer and how you can implement it into your existing development toolkit.

BlazeDS has been available from Adobe for only a very short time, but it has already been adopted by many of the leading development agencies. Customers are already using BlazeDS to develop complete enterprise-level applications. The name BlazeDS is short for Blaze Data Services.

Here's what BlazeDS has to offer:

  • Turnkey development options for rapid development and testing

  • Robust code libraries for integrated development

  • Testing suite with unit tests

Installing BlazeDS

BlazeDS allows you to deploy a turnkey Web server on your local machine, and all you need to have installed is the JDK (Java Development Kit). You can download a copy of BlazeDS from http://opensource.adobe.com/wiki/display/blazeds/Downloads. The installation process is very simple. You start off by unzipping the archive file you downloaded. Once the files are unpacked, you move them to the root of your machine: C:lazeds.

Now that the installation is complete, the next step is to start the database by using the following command:

$ lazedssampledbstartdb.bat

Now that the database is started, the final installation step is to start the Web server. Issue a command that matches the path you chose in the installation process.

The Web server and database are now ready to use. You can verify this by visiting the following URL: http://localhost:8400/. You should be presented with a simple welcome screen and links to some sample applications. For now, you can skip over the samples and dive in to create your own.

Understanding Messaging in Flex

Now that BlazeDS is properly installed, let's take a look at how this application functions before you dive right into coding. The stock ticker application uses messaging to send data to and receive data from the Java code located on the server.

Flex applications use a client-side messaging API to send and receive messages from a server-side destination. The messaging process is based primarily on two components: the Producer and the Consumer.

Producer and Consumer messaging components

The Producer component sends messaging to the server-side destination. The Consumer component subscribes to the server side and is a message receiver. The Producer is the message sender. Both of these components can be built by using pure ActionScript or an MXML and ActionScript mixture. For this application, you use the pure ActionScript option, but you also learn how the MXML alternative works.

Both the Producer and Consumer require a valid message destination, which is defined in the services-config.xml file, explained later in this chapter.

Creating the Producer

The Producer handles the sending of data to the server-side code. Start off by importing the necessary packages and classes:

<mx:Script>
<![CDATA[

   import mx.messaging.*;
   import mx.messaging.messages.*;
   import mx.messaging.events.*;

]]>
</mx:Script>

These classes are used to create event listeners, message objects, and handlers. Next, you want to create a variable that's the reference to the Producer instance. You need only one Producer for this application, so the name producer is perfectly okay for the variable name. In a larger application, you may want to name it something more specific, such as NameOfServiceProducer or MessageHandler:

import mx.messaging.*;
import mx.messaging.messages.*;
import mx.messaging.events.*;

private var producer:Producer;

The Producer component offers a few event listener options; two of those options are the fault and acknowledge handlers. The fault handler is dispatched whenever an error occurs during the process of sending to the server. A fault handler method looks something like this:

private function faultHandler(event:MessageFaultEvent):void
{

}

This would be the place to display proper error messages to users so that they don't think the application has locked up. The acknowledge handler is called whenever the Producer is notified that the sending process was successful:

private function ackHandler(event:MessageAckEvent):void
{

}

This is the place to display messages in the client, stating that the message was received by the server — similar to the fault handler. You could also use these events to place flood control on an application, such as chat. Basically, you create a timer in the sending process, and depending on whether the message was successful, you update or delete the timer. This is, of course, only one use of those event listeners.

Now that you have everything loaded and the proper event handlers created, the next step is to generate the Producer call. For this example, this code is placed within the init() method:

private function init():void
{
     producer = new Producer();
     producer.destination = "stockticker";
}

The destination property is a reference to the value defined in the services-config.xml file. This ensures that the proper messaging service is being used. This unique name is especially important if your application has more than one messaging service.

The event handlers you defined in the previous section need to be assigned to some listener, so the best place to do this is in the init() method to ensure that they're configured immediately:

private function init():void
{
     producer = new Producer();
     producer.destination = "stockticker";

     producer.addEventListener(MessageAckEvent.ACKNOWLEDGE, ackHandler);
     producer.addEventListener(MessageFaultEvent.FAULT, faultHandler);
}

Sending a message

You have completed the Producer setup, but you probably realized that nothing is being sent to it. Well, it's a pretty good guess that you would want to actually send something to the server. This is done by using the AsyncMessage class. You start off by creating a new AsyncMessage object, fill it with your data, and then call the Producer component's send() method, passing in the AsyncMessage object:

private function getStockData():void
{
     var msg:AsyncMessage = new AsyncMessage();
     msg.body = "adbe";
     producer.send(msg);
}

That code creates a new AsyncMessage object, assigns the stock ticker for Adobe ("adbe") to the body of the message, and finally makes a call to the Producer by using the send() method. Once this application is complete, that code alerts the server to load the stock data for Adobe or whichever stock ticker you request.

Creating the Consumer

The Consumer component has many similarities with the Producer. You start off by creating a variable to hold the instance of the Consumer, as you did in the previous code for the Producer:

<mx:Script>
<![CDATA[

  import mx.messaging.*;
  import mx.messaging.messages.*;
  import mx.messaging.events.*;

  private var producer:Producer;
  private var consumer:Consumer;

]]>
</mx:Script>

The Consumer also makes use of the fault and acknowledge handlers, but for this example, you can simply reuse the ones defined for the Producer:

private function init():void
{
   .
   .
   .

   consumer = new Consumer();
   consumer.destination = "stockticker";
   consumer.addEventListener(MessageAckEvent.ACKNOWLEDGE, ackHandler);
   consumer.addEventListener(MessageFaultEvent.FAULT, faultHandler);
}

The destination property is assigned to the same value as the Producer, as defined in the services-config.xml file.

Managing the destination service

The process of managing the destination service is where you set up the unsubscribe and subscribe methods. These are used to stop and start the service connection.

Subscribing to the destination service

In order to start the Consumer, you must make a call to the subscribe() method:

private function init():void
{
   .
   .
   .

   consumer = new Consumer();
   consumer.destination = "stockticker";
consumer.addEventListener(MessageAckEvent.ACKNOWLEDGE,
  ackHandler);
  consumer.addEventListener(MessageFaultEvent.FAULT, faultHandler);

  consumer.subscribe();
}

Unsubscribing from the destination service

You can unsubscribe a Consumer component at any time by calling the unsubscribe() method. If you unsubscribe for an active messaging process, you may get an error, which should be captured in the faultHandler handler function:

consumer.unsubscribe();

Developing a Stock Ticker Application

Now that you have an understanding of how the messaging service works in Flex, let's move on to the stock ticker application.

The stock ticker application consists of Java and Flex portions. A stock ticker application would normally use a live feed to the stock exchange, but for this example, fake stock data is used. If you want to create a live ticker, which means that it would update almost instantly, you would need to purchase a service.

When writing the application, you can develop the Flex or Java first, but it's a best practice to outline what the back-end and overall data processes are supposed to accomplish. On larger projects, you would probably have multiple developers and designers, but in this book, it's only you.

Setting up the messaging config file

You need to add the unique messaging object to the messaging-config.xml file located on the BlazeDS server. If you installed by using the default directions, the config file can be found by using the following path:

/blazeds/tomcat/webapps/blazeds/WEB-INF/flex/messaging-config.xml

Open that XML file in your favorite text editor and then add the unique service destination ticker, as shown below. Once you have added that line, save and quit the XML file:

<?xml version="1.0" encoding="UTF-8"?>
<service id="message_hyphen_service"
   class="flex.messaging.services.MessageService">

   <adapters>
      <adapter-definition id="actionscript"
      class="flex.messaging.services.messaging.adapters.ActionScriptAdapter"
              default="true" />
<!-- <adapter-definition id="jms" class="flex.messaging.
    services.messaging.adapters.JMSAdapter"/> -->
     </adapters>

     <default-channels>
         <channel ref="my-polling-amf"/>
     </default-channels>

     <destination id="stockticker"/>

</service>

Note

If for some reason the server throws a connection error, restart the server. That normally isn't needed, but at other times, restarting the server is needed when the service can't be properly reached.

Developing the Java back end

The Java portion of this application consists of two Java classes. The first returns the stock ticker information to the client. The second is a Java object containing properties for the stock ticker data that mirror the properties that are displayed in the Flex application. This example application uses randomized static data rather than fetching real financial data from an external service.

The first thing to do is set up an Eclipse project for the stock application. The Eclipse project includes only the two Java class files. Eclipse automatically builds the class files for you. For this application, you only need to copy the compiled class files to the BlazeDS Web application's WEB-INF/classes directory.

Open Eclipse by navigating to the Eclipse install directory in Windows Explorer and then double-click eclipse.exe. To create and configure the Eclipse project, follow these steps:

  1. Right-click in the Project Explorer view and then choose New

    Developing the Java back end
    Project from the popup menu. The New Project selection dialog box opens.

  2. Click the arrow next to Java to expand it, click the Java Project item below Java, and then click Next. The Create a Java Project wizard opens.

  3. Type jfib-ch11-p01 in the Name text field and then click Next. The Java Settings screen opens.

  4. Click the Libraries tab. The Library list is displayed.

  5. Click the Add External JARs button. The JAR Selection dialog box opens.

  6. Navigate to the folder where you unzipped BlazeDS, double-click the lib folder, choose flex-messaging-core.jar and flex-messaging-common.jar in that lib folder, and then click Open. These two JAR files are added to the Library list.

  7. Click Finish. The Create a Java Project wizard closes, and the newly created project appears in the Project Explorer view.

The Eclipse project is now set up, allowing you to start creating your Java classes. First, create the Java class that represents the stock ticker information. This class has three public properties: ticker, value, and change. These three property names also appear in the Flex DataGrid control that displays the stock ticker information.

To create the ticker information class, follow these steps:

  1. Right-click the src folder under the jfib-ch11-p01 project in the Project Explorer view and then choose New

    Developing the Java back end
    Class from the popup menu. The New Java Class dialog box opens.

  2. Type com.wiley.jfib.ch11 in the Package text field, type TickerValue in the Name text field, and then click the check box next to Generate comments.

  3. Click Finish. The New Java Class dialog box closes, and the newly created com.wiley.jfib.ch11 package and TickerValue class appear in the src folder under the jfib-ch11-p01 project. The TickerValue class opens in the editor.

Now edit the TickerValue class so that it matches this code listing:

/**
 *
 */
package com.wiley.jfib.ch11;

/**
 * A class representing a stock ticker value
 * @author Chuck
 *
 */
public class TickerValue {
   public String ticker = "";
   public String value = "";
   public String change = "";
}

Now you can create the Java class that will communicate with the Flex client and provide stock information. The Java class extends BlazeDS's ServiceAdapter class. The ServiceAdapter class is an abstract class that requires you to implement a single method called invoke(). The invoke() method receives messages from publishers in the Flex application and sends messages back to any subscribing Flex clients. In this case, the invoke method sends a TickerValue object back to the Flex client as the body of the message. The Flex client can then use this object in the data provider of its DataGrid control.

To create the Java stock ticker server class, follow these steps:

  1. Right-click the com.wiley.jfib.ch11 package under the jfib-ch11-p01 project in the Project Explorer view and then choose New

    Developing the Java back end
    Class from the popup menu. The New Java Class dialog box opens.

  2. Click the Browse button next to the Superclass text field. The Superclass Selection dialog box opens.

  3. Type ServiceAdapter in the Choose a type text field. The Matching items list box fills in with classes whose names match your entry.

  4. Choose ServiceAdapter – flex.messaging.services from the list and then click OK. The Superclass Selection dialog box closes, and the Superclass text field in the New Java Class dialog box is filled in with the ServiceAdapter class.

  5. Type StockTickerServer in the Name text field and then click the check box next to Generate comments.

  6. Click Finish. The New Java Class dialog box closes, and the newly created StockTickerServer class appears in the src folder under the com.wiley.jfib.ch11 package. The StockTickerServer class opens in the editor.

Now edit the StockTickerServer class so that it matches this code listing:

/**
 *
 */
package com.wiley.jfib.ch11;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;

import flex.messaging.messages.AsyncMessage;
import flex.messaging.messages.Message;
import flex.messaging.services.MessageService;
import flex.messaging.services.ServiceAdapter;

/**
 * @author Chuck
 * The StockTickerServer class creates some random stock ticker data and returns
 * it to a Flex consumer.
 */
public class StockTickerServer extends ServiceAdapter {
   @Override
   public Object invoke(Message arg0) {
           AsyncMessage stockMessage = (AsyncMessage)arg0;

           TickerValue tickerValue = new TickerValue();
           tickerValue.ticker = "abde";
           tickerValue.value = String.valueOf(
                                   new Random().nextDouble() * 100.0);
           tickerValue.change = "+" + String.valueOf(
                                   new Random().nextDouble() * 9.0);

           TickerValue tickerValue2 = new TickerValue();
tickerValue2.ticker = "siri";
           tickerValue2.value = String.valueOf(
                                   new Random().nextDouble() * 100.0);
           tickerValue2.change = "+" + String.valueOf(
                                   new Random().nextDouble() * 9.0);

           TickerValue tickerValue3 = new TickerValue();
           tickerValue3.ticker = "xmsr";
           tickerValue3.value = String.valueOf(
                                   new Random().nextDouble() * 100.0);
           tickerValue3.change = "+" + String.valueOf(
                                   new Random().nextDouble() * 9.0);

           Collection<TickerValue> tickerValues = new ArrayList<TickerValue>();
           tickerValues.add(tickerValue);
           tickerValues.add(tickerValue2);
           tickerValues.add(tickerValue3);
           stockMessage.setBody(tickerValues);
           MessageService messageService =
                   (MessageService)getDestination().getService();
           messageService.pushMessageToClients(stockMessage, false);
           return null;
     }
}

The import statements import some BlazeDS messaging classes necessary for the StockTickerServer class to receive and republish messages. In the invoke() method, a TickerValue object is created, and its properties are set using a string for the ticker property and random double-precision decimal values converted to strings for the value and change properties. This process is repeated three times, once for each stock to be displayed in the Flex client. Each of these TickerValue objects is added to a Java ArrayList collection, which is then set as the body of the message. Finally, the message is pushed out to any Flex clients subscribing to the stock ticker destination in the messaging configuration.

By default, Eclipse automatically compiles the Java files in this project. Once these files have been created, you can simply copy the compiled classes from the project directory into the BlazeDS Web application. Eclipse outputs the class files into a folder named bin inside the project directory. The project directory is located in the directory you specified for your Eclipse workspace. If you forget where that is, you can also find the location of the project directory by choosing Project

Developing the Java back end

Building the Flex user interface

Now that the Java back end is developed, the next step is to design and integrate the Flex user interface (UI). You can start with the provided sample files and then skip ahead to the ActionScript or create the application from scratch.

All Flex applications start at the same place: setting up the workspace and creating the project. Follow these steps:

  1. Choose File

    Building the Flex user interface
    New Flex Project. The New Flex Project dialog box, as shown in Figure 11.1, opens.

  2. Type a name for the application, such as BlazeDSStockTicker.

  3. Ensure that the Application type is set to Web Application and that the server technology is set to J2EE.

  4. Click Next.

Setting the J2EE Server options

The next screen is where you configure the Flex application to use the BlazeDS server that you installed. Start by clicking Browse to choose your root folder. The path is wherever you placed the blazeds directory; within that, choose tomcat/webapps/blazeds. If your BlazeDS installation was at /blazeds, the full Root folder path would become:

/blazeds/tomcat/webapps/blazeds/
The Configure J2EE Server screen

Figure 11.1. The Configure J2EE Server screen

The Root URL is the Web path to the BlazeDS server. A default installation would place the server at the following location:

http://localhost:8400/blazeds/

The Context root defines the root directory of the application, which in this case is blazeds/. Now that the server variables are configured, click Validate Configuration to ensure that everything was set up properly.

If the validation is successful, you can click Finish to complete the project creation process. You should now see your new project sitting in the Flex Navigator pane on the left side of the screen. If you don't, make sure you that created and loaded the new project properly.

Building the user interface

Now that the project is created, you can move on to creating the Flex UI. The UI consists of a DataGrid component and a label, which in the overall scheme of applications isn't big, but the idea is to learn about BlazeDS integration, not to develop an award-winning application — for the time being. Figure 11.2 shows a sample application in Flex.

A sample application shown in the Flex Design view

Figure 11.2. A sample application shown in the Flex Design view

Make sure that you're in the Design view and then drag out the components from the Components pane to build the application. Once the components are on the canvas, you can either add the unique IDs by selecting the components and editing them in the Property panel to the right or you can move into Source view to add them by using pure code.

Developing the ActionScript

Switch to Source view, if you're not already there, to begin developing the ActionScript necessary to request and update the stock tickers. All the code is located within the <mx:Script> tags. In most applications, the first part of the code is where your imports and variable definitions are located:

import mx.controls.dataGridClasses.DataGridColumn;
import mx.controls.DataGrid;
import mx.controls.Alert;
import mx.collections.ArrayCollection;
import mx.utils.ArrayUtil;
import mx.utils.ObjectUtil;

import mx.messaging.*;
import mx.messaging.messages.*;
import mx.messaging.events.*;

private var consumer:Consumer;
private var producer:Producer;

[Bindable]
private var tickers:ArrayCollection;

Bindable variables

The variables for this application are straightforward. First off, you have a Bindable ArrayCollection, which holds the stock ticker object data. A Bindable variable offers the ability to auto-update, which means that whenever the value changes, anything watching that variable is also updated and notified. When you're working in MXML code, anything within {} is a reference to a bindable expression.

You can also assign change watchers by using pure ActionScript, but that's beyond the scope of this book. You can check out the help material that ships with Flex for more information about Bindable variables.

Now that the packages are loaded and the variables are defined, the next step in the code is an event handler that's called once the Flex application is loaded. This is the preferred way to initialize code so that you can ensure the code is executed at startup:

creationComplete="init()"

Flex offers many different events that allow you to develop more solid code and ensure that your application acts the way you intended. Previous versions of ActionScript allowed you to use event handlers for some tasks, but ActionScript is the first to truly allow common application development practices and abilities.

The init() method in this example has been assigned to the creationComplete event, which is called once the application has fully loaded and has been drawn to the display list.

This init() method handles the data loading and events associated with this application. The init() method is also where you would initialize the ArrayCollection, which holds the ticker object data once it's been properly loaded:

private function init():void
{
     tickers = new ArrayCollection();
}

The next step is to initialize a new instance of the Consumer component, assign event listeners, and set the destination property:

private function init():void
{
     tickers = new ArrayCollection();

     consumer = new Consumer();
     consumer.destination = "stockticker";
     consumer.addEventListener(MessageAckEvent.ACKNOWLEDGE, ackHandler);
     consumer.addEventListener(MessageFaultEvent.FAULT, faultHandler);
}

Once the message is sent to the server, a response is returned. The ackHandler is set up to handle that response. This method basically takes the message response and converts it to an ArrayCollection object so that it can be placed in the DataGrid:

private function ackHandler(event:MessageAckEvent):void
{
     tickers = ArrayCollection(event.message);
}

Now that the data handler has been completed, the next step is to modify the default DataGrid that you added to the canvas. First off, as exemplified in Figure 11.3, here's the default code for the DataGrid:

<mx:DataGrid x="82" y="107">
     <mx:columns>
          <mx:DataGridColumn headerText="Column 1" dataField="col1"/>
          <mx:DataGridColumn headerText="Column 2" dataField="col2"/>
          <mx:DataGridColumn headerText="Column 3" dataField="col3"/>
     </mx:columns>
</mx:DataGrid>

Start by adding the Bindable string to automatically load the latest stock data as it's returned from the server. This is achieved by using the dataProvider property and assigning it to the ticker variable:

<mx:DataGrid ... dataProvider="{tickers}">
The default DataGrid

Figure 11.3. The default DataGrid

For this example, you can also change the default column names by modifying the headerText property, but that's purely for visual purposes. The dataField property, on the other hand, is the link to the ArrayCollection data and is also used when modifying the column data, which is covered later in this chapter:

<mx:DataGrid ...>
   <mx:columns>
          <mx:DataGridColumn headerText="Ticker" dataField="ticker"/>
          <mx:DataGridColumn headerText="Value" dataField="value"/>
          <mx:DataGridColumn headerText="Change" dataField="change"/>
     </mx:columns>
 </mx:DataGrid>

Using the labelFunction

The DataGrid component has a special property being used in this example. That property is labelFunction, which is called for each column in the grid as the dataProvider is looped through. In this example, this property is used to assign a method that's responsible for ensuring that the ticker name is in all caps. You can also perform many other actions, such as converting currency and adding values.

The labelFunction property is defined on the DataGridColumn item as follows:

<mx:DataGridColumn labelFunction="strToUpper" .../>

The labelFunction property accepts a method name as a value and automatically passes in two arguments. The structure of the method is as follows:

private function strToUpper(item:Object,column:DataGridColumn):String
{
}

The first argument is the object that's contained within the ArrayCollection. The second argument is a reference to the DataGridColumn. In order to get the proper value, you must use the following code, which grabs the object value based on the column name:

item[column.dataField]

That code returns 'ticker' in the above code. In a larger application, you would probably create a switch statement to handle various labelFunction actions, similar to the following example:

switch(String(item[column.dataField]))
{
     case 'ticker' :
           // handle ticker code
           break;
     case 'option-2' :
           // handle other option here
           break;
}

Now that the value has been discovered, you need to datatype it as a string, just as a precaution. Then, you convert the string to all uppercase characters and return it to the DataGrid column for display:

private function strToUpper(item:Object,column:DataGridColumn):String
{
   return String(item[column.dataField]).toUpperCase();
}

The remaining display process happens automatically at this point because Flex is able to bind to that ticker variable. You could certainly assign more labelFunction calls if you required more data modification.

Note

Even though you can modify the data on the Flex side, it's best to make all changes possible on the server side for memory and responsiveness concerns for the client.

You may be asking yourself whether it's possible to test the labelFunction and overall ArrayCollection process that was just developed. Well, the answer is yes, you can. You don't even need to involve the server to do so.

Start by commenting out the Consumer code in the init() function and then prefill the ArrayCollection with some fake data:

private function init():void
{
     tickers = new ArrayCollection();
//consumer = new Consumer();
     //consumer.destination = "stockticker";
     //consumer.addEventListener(MessageAckEvent.ACKNOWLEDGE,
     ackHandler);
     //consumer.addEventListener(MessageFaultEvent.FAULT,faultHandler);

     tickers.addItem({ticker:'adbe', value:'24.0', change:'+ 0.6'});
     tickers.addItem({ticker:'siri', value:'10.0', change:'- 0.8'});
     tickers.addItem({ticker:'xmsr', value:'12.0', change:'- 0.1'});
}

Now when you run the application, you see the DataGrid fill instantly, and the labelFunction has properly capitalized all the tickers. Figure 11.4 shows an application with DataGrid data.

The application with fake DataGrid data

Figure 11.4. The application with fake DataGrid data

At this point, you have completed both the Java and Flex portions of this stock ticker application. Feel free to expand upon it to dig deeper into the abilities of BlazeDS and messaging.

The complete Flex (MXML) code has been provided for easy viewing, but you can also find the original source on this book's Web site:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
   layout="absolute"
   width="500"
   height="300"
   creationComplete="init()">

<mx:Script>
<![CDATA[
import mx.controls.dataGridClasses.DataGridColumn;
   import mx.controls.DataGrid;
   import mx.collections.ArrayCollection;
   import mx.utils.ArrayUtil;
   import mx.controls.Alert;
   import mx.utils.ObjectUtil;

   import mx.messaging.*;
   import mx.messaging.messages.*;
   import mx.messaging.events.*;

   private var consumer:Consumer;

   [Bindable]
   private var tickers:ArrayCollection;

   private function init():void
   {
           tickers = new ArrayCollection();

           consumer = new Consumer();
           consumer.destination = "stockticker";
           consumer.addEventListener(MessageAckEvent.ACKNOWLEDGE, ackHandler);
           consumer.addEventListener(MessageFaultEvent.FAULT, faultHandler);
           consumer.subscribe();

           producer = new Producer();
           producer.destination = "stockticker";

           producer.addEventListener(MessageAckEvent.ACKNOWLEDGE, ackHandler);
           producer.addEventListener(MessageFaultEvent.FAULT, faultHandler);

   }

   private function getStockData():void
   {
           var msg:AsyncMessage = new AsyncMessage();
           msg.body = "adbe";
           producer.send(msg);
   }

   private function faultHandler(e:MessageFaultEvent):void
   {
           Alert.show(ObjectUtil.toString(e.message));
   }

   private function ackHandler(e:MessageAckEvent):void
   {
           tickers = ArrayCollection(e.message);
}

   private function strToUpper(item:Object,c:DataGridColumn):String
   {
           return String(item[c.dataField]).toUpperCase();
   }

]]>
</mx:Script>

    <mx:Label x="10" y="10" text="BlazeDS - Stock Ticker"/>
    <mx:DataGrid x="10" y="36" width="480" height="254" dataProvider="{tickers}">
            <mx:columns>
                    <mx:DataGridColumn labelFunction="strToUpper"
    headerText="Ticker" dataField="ticker"/>
                    <mx:DataGridColumn headerText="Value" dataField="value"/>
                    <mx:DataGridColumn headerText="Change" dataField="change"/>
            </mx:columns>
    </mx:DataGrid>

  </mx:Application>

Summary

In this chapter, you learned how to install and configure BlazeDS. Then, you learned about messaging in Flex and how it helps you develop more responsive applications by using less code. In the last part of the chapter, you built a complete messaging-based stock ticker application.

The complete application should have allowed you to grasp the concepts of BlazeDS and how you can use them in your own development. At this point, you can move on to developing much larger and more robust applications, which are covered in later chapters of this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.75.10