A Simple Streaming AJAX App with OpenAjax Hub, TIBCO GI, and DWR 2.0

Follow along and implement the real-time streaming AJAX system in Figure 1 using two different AJAX toolkits and the OpenAjax Hub.

Requirements
The requirements for this solution are straightforward. For this application we need a ready-made data grid control that will display changes in prices to stocks when those changes occur. A nice-to-have would be visual indicators in the GUI that show when a cell value in the grid is increasing or decreasing...and, of course, we want to deploy this to just a standard Web browser, so we also must do this without any reliance on plug-ins, applets, or Active-X controls. (Thanks goodness this is an AJAX article!) Figure 1 shows the basic design that could be styled more at a later date. In addition we'll want to add more AJAX controls to this page that can tap the same streaming stock data for other calculations and visuals, such as charts or portfolio totals. For now, we'll keep it simple.

Architectural Design
We don't have to build the above system from scratch, and can instead leverage readily available, reusable AJAX parts to get the job done quickly; the architectural strategy is to use AJAX pieces and parts that can work together. At the core of the system in Figure 2 is the OpenAjax Hub (see the OpenAjax Hub for Interop sidebar). We'll use the OAA Hub as a central publish/subscribe bus to which we can publish the live stock data so that the data grid and the future visual controls and functions can listen for those events and messages.

Resources
Publish/Subscribe Core
For our publish/subscribe core we'll use the OpenAjax Hub, an open source project implementing the evolving OpenAjax Alliance Interoperability Working Group specifications. Start at HYPERLINK "http://www.openajax.org" http://www.openajax.org and follow the links to the sourceforge.net project from there.

Ready-Made GUI Controls
For the GUI controls we'll leverage those from TIBCO General Interface, an open source AJAX project that currently provides ready-made AJAX controls for GUI, data, and communications in addition to visual tools for rapid AJAX application development, unit and functional testing, and AJAX debugging.

Real-Time Communications
For our real-time data, we'll use DWR 2.0, the just-released next version of Direct Web Remoting (DWR), an open source project that enables you to remote Java objects through JavaScript in the browser and now vice versa through its "Reverse AJAX" capabilities for real-time remote control of JavaScript objects in the browser via Java objects on the server across a persistent HTTP connection (a.k.a "Comet").

Project Source Code
You can quickly grab a copy of this project and all its parts from the 2.x release of DWR at http://getahead.org/dwr. Once you've installed DWR, check out the General Interface demo. Those who want to extend the GUI and add more controls should also download TIBCO General Interface from http://developer.tibco.com/gi. Note that the OpenAjax.js file that ships with the project in the DWR download is an older, 46 kb version of the OpenAjax Hub. The latest version of the OpenAjax Hub, which now also implements a savvy topic-based event naming scheme over the basic pub/sub capability, is currently under 2 kb (yes two kilobytes - that's not a typo).

Implementation
The <dwr>/gi/index.html file loads up the OpenAjax.js file, the needed DWR libraries, and some application specific files in the head of the HTML page.

The body of the page includes a div that loads the TIBCO GI library.

<div style="width:100%; height:220px;">
    <script
       type="text/javascript"
       src="JSX/js/JSX30.js"
       jsxapppath="gidemo" jsxlt="true"> </script>
</div>

The jsxapppath="gidemo" loads the GI project in /gidemo and in turn renders the GUI component declaration: gidemo/components/appCanvas.xml. Once these are loaded, GI's project init function is called:

function giLoaded() {
    OpenAjax.subscribe("gidemo", "corporation", objectPublished);
    dwr.engine.setActiveReverseAjax(true);
}

This subscribes to the OpenAjax Hub listening for publications to the 'gidemo' + 'corporation' topic. When a publish happens, the objectPublished function is called. The last line turns DWR's Reverse AJAX on so that the data can flow from the server to the client without polling or waiting for the GI application running at the client to request an update from the server. The objectPublished function looks like this:

function objectPublished(prefix, name, handlerData, corporation) {
    var matrix = giApp.getJSXByName("matrix");
    var inserted = matrix.getRecordNode(corporation.jsxid);
    matrix.insertRecord(corporation, null, inserted == null);
    matrix.repaintData();
}

This simply takes the published data and inserts it into the GI matrix component. Each column of the matrix component is bound to a property of the corporation JavaScript object. The matrix control, its columns and bindings were configured using TIBCO GI's visual tools: TIBCO General Interface Builder.

There are a number of possible repaint strategies, including the simplest of them all: matrix.repaintData(); as shown above. However, to meet our requirements above, in the source below we've implemented a more sophisticated approach that enables both incremental painting of updated rows and cell highlighting.

Instead of matrix.repaintData(); we've used this:

...
// There are many ways to get a table to repaint.
// One easy way is to ask it to repaint:
// matrix.repaintData();

// But we are going for a fancy option that does highlighting
   for (var property in corporation) {
     if (property != "jsxid") {
       var ox = matrix.getContentElement(corporation.jsxid, property);
       if (ox) {
         var current = ox.innerHTML;
         if (current != "" + corporation[property]) {
           ox.style.backgroundColor = "#FDE4EB";
           var callback = function(ele) {
           return function() { ele.style.backgroundColor = "#FFFFFF"; };
         }(ox);
         setTimeout(callback, 1000);
         ox.innerHTML = corporation[property];
       }
     }
   }
}
...

Meanwhile, on the server the following Java code is running in a thread:

while (!Thread.currentThread().isInterrupted())
{
    Collection sessions = serverContext.getScriptSessionsByPage("/dwr/gi/index.html");
    ScriptProxy proxy = new ScriptProxy(sessions);

    Corporation corp = corporations.getNextChangedCorporation();
    proxy.addFunctionCall("OpenAjax.publish", "gidemo", "corporation", corp);

    int timeToSleep = random.nextInt(2500);
    Thread.sleep(timeToSleep);
}

This simply finds the people viewing this page and creates a ScriptProxy to allow us to push JavaScript to these users. The ScriptProxy is a feature of DWR 2.0 enabling DWR 2.0 to dynamically generate JavaScript from a Java API. This is done at runtime rather than compile time, so we can use it to remote control many browsers. This makes it very easy to write things like chat applications, or anything particularly dynamic. Messages are sent to clients across using DWR's "Reverse AJAX" capability.

We then ask the corporation's object for a Stock price change, and publish this to the Open Ajax Hub.

That's it. Pretty simple.

For the full source to all the files, including the TIBCO GI project files, see the source in the .war file download for DWR 2.0.

Other AJAX Controls
Changes to Java Objects are sent to DWR 2.0's Reverse AJAX connection, and converted to JavaScript by DWR. In this case, the converted objects are wrapped in the OpenAjax Hub's publish method so that when the pushed code arrives at the client, the OpenAjax Hub publishes the data to a message topic name. The JavaScript Objects, such as the TIBCO GI matrix GUI component, are coded to listen for new information on that topic and, in turn, handle the new information when it arrives.

Conclusion
The solution above demonstrates how easy it can be to implement powerful systems based on sound publish and subscribe architectural principles. Further, the decoupled nature of the publish and subscribe style implementation enables one piece of a system to be added or replaced without effecting other parts. Accordingly, this approach is highly applicable to mashup and AJAX portal scenarios. As shown, beyond the basics of using the emerging publish and subscribe standards of the OAA Hub to connect reusable client-side components, technologies, such as DWR 2.0's Reverse AJAX and TIBCO's just released Ajax Message Service for highly scalable real-time data over HTTP, are enabling publish and subscribe events to occur across the network. Accordingly, one can begin to think not of an HTML page in a browser connected to a server across a network, but instead the AJAX application running in the browser being in the same event cloud as the server, publishing to and subscribing from streams of information mediated by event bus architectures on the client and on the server, and, accordingly, enable you to build more powerful AJAX solutions.

OpenAjax Hub for Interop
Two months ago in New York, immediately following AJAXWorld East 2007, the OpenAjax Alliance met and held its first InteropFest where a handful of the more than 75 industry members of the nascent AJAX standards organization demonstrated their technologies working in context of the first specification project of the alliance - the OpenAjax Hub (OAA Hub). If you haven't been watching the evolution of this specification targeted at enabling AJAX libraries and controls to be interoperable, it's rather interesting that at the core of the OAA Hub is a publish and subscribe event and message bus leveraging the tried and true interoperation approaches typical of server-side integration strategies, but instanced on the client side.

Why is a "pub/sub" system at the core of the standard interoperation strategy for AJAX? With increasingly sophisticated AJAX software, mashups, and composite applications being built today, the pub/sub strategy makes developing such things simpler. Consider that when you have a system consisting of more than one part, and especially in such systems that may grow and change over time like mashups, portals with AJAX portlets, or composite applications, instead of writing procedural code for each part of the system that needs to work with another (which as you CS majors know, leads to the classic "n-squared" integration complexity problem), it's far more efficient to implement a system for receiving, then dispatching events and messages so that one part can publish an event through the intermediary pub/sub hub, and then other parts that need information from that system can implement specific listeners that subscribe to, receive, and handle the events and messages.

As opposed to the more primitive DOM events such as onclick, onkeydown, onmouseover, and the like, typically these types of events and messages are associated with "application-level" concepts such as like "userLoggedIn", "newCustomerCreated", or "addNewStockSymbol".

Figure 3 compares a system with five parts directly linked to each other in a point-to-point fashion with a system implemented in a publish/subscribe message bus architecture.

Architecting your AJAX applications using publish and subscribe techniques enables each part of the system to be decoupled from the others, and thus to be built and managed as distinct units. This modularization not only facilitates greater reuse and more efficient team development, but also helps you to avoid creating the hairballs of code typical of point-to-point architectural approaches to application systems. The more elements in a system, the most complex and expensive adding to and maintaining the system becomes in point-to-point architectures when compared to publish/subscribe bus architectures.

© 2008 SYS-CON Media