Friday, August 10, 2007

Working with XmlSocket

Adobe's LifeCycle Data Services ES is great, and while they offer an "express" edition for free, that only gives you a single CPU production license. Does anyone put a single-CPU server into production today??. We don't where I work, and we were too cheap to pay out gobs of money to Adobe when we could build something that accomplishes Data Push on our own in mere days. That's what this post is about :-) today.

Flex 2 offers up the flash.net.XmlSocket class. This wonderful little class can give your Flex application asynch communication capabilities with your server, or Data Push. The general logic is quite simple (on the client), actually:


  1. Instantiate a new XmlSocket class.

  2. Add your event listeners so you can hear when data comes in

  3. Code your listeners to do what it is you need done



Seriously folks- that's all there is to it on the client. That said, you do have to design your wire-level protocol and you do have to write the server to process the logic. I've always believed (and still do) that it would be possible to write a nice little Tomcat Host entry to handle your proprietary file format. I just haven't found the time to do it, so we took the 'easy' way out and just wrote our own multi-threaded server from scratch. Strangely, there was consensus that this approach would be easier, quicker, and ultimately more flexible then writing a Host implementation for Tomcat to handle our wire-level protocol. Deploying our server as a service was a cake walk- like so many others, we just used the Java Service Wrapper and in minutes we were down with that task. So the real work lies in designing the protocol. In this post the term protocol is defined to mean "the handshaking and message exchange format betweent the client and the server." Our format stuck to an XML document, though the format doesn't have to be XML as Wikipedia correctly eludes to.

Authentication
The first design challenge was authentication. Since we're communicating with a proprietary server and the user had already (presumably) logged into an authenticated Tomcat session, how did we re-establish authentication without forcing the user to login again and without forcing the client-side to cache the login credentials with some hack. The solution we devised was actually pretty novel and very effective, if I do say so myself. We wrote a class that implements HttpSessionListener and properly registered it in our web.xml file. When the user establishes a session, we drop their session ID as an entry into a session table. Since we control the entire authentication process on Tomcat (see Tomcat docs on JAAS), we actually update the record in the database once we determine and consider the session to be fully authenticated. This includes auditing, password expiration checks, etc. Thus, for our application, the session record in the database contains a flag to indicate if we consider the session authenticated or not. We make this available using a simple Web Service lookup that the client makes. Once the client has been told their authenticated session ID, we use that as the key to establish an authenticated (effectively a single sign-on) session with our proprietary server. The first wire-level exchange then is a really simple XML document that request an authenticated session with the server, something like this:

<Authenticate session="CAE321DDF922E6199999999992BF338"/>

The server looks in the database to verify that a) the session is valid and b) the session is considered authenticated. In fact, for added security the server verifies this information before any response back to the client with data. In this way, even if Tomcat expires the session between the time the client sent us a request and when we received it, we would report an exception back to the client. This is needed because once you download a Flex app to the client, it theorhetically might not make any calls to its server for an extended period of time, and thus the session on the server would have timed out even though the user might have been clicking away in the browser.

NOTE: One little obvious gotcha that is easy to overlook. You need to remember to include a line feed character so that the server knows how to delineate between one request's end and the start of another. Simply put, don't forget to include a \n at the end of your line of xml! If you're doing a block of XML across multiple lines you could steal a design trick from the HTTP Message specification and require back-to-back CRLF/CRLF or something similar. They use a CRLF from the last header to a blank line, and then another CRLF before the start of the message body.

Data Subscriptions
Once authenticated, it's then time to tell the server what kind of data we (the web client) are interested in receiving. To accomplish this, we us a pub-sub metaphor. We simply drop over a couple of XML requests to tell the server what data event we want to know about, like this:

<EventSubscription topic="MyDesiredTopicName"/>

to which the server responds:

<Response result="success"/>

Then, the server does "it's job" and listens, looks, finds, etc. -- how you implement your server is up to you-- data and sends them over the wire:

<MyDesiredTopicName>
     <property name="eventId" value="4131"/>
     <property name="serverMillis" value="1186760571218"/>
     <property name="personId" value="500"/>
     <property name="firstName" value="Joe"/>
     <property name="lastName" value="User"/>
     <property name="data" value="key=value,key=value,key=value"/>
</MyDesiredTopicName>

This XML would be received by the DataEvent.DATA event- we added a listener to this event published from the XmlSocket. Since we know the format coming into the event is XML, all we have to do is parse it. The XML is easily accessible via event.data in the DataEvent. Working with XML in Flex is really easy- there are tons of examples, just do a Google on Flex E4X and you'll find resources. Here is a snippet of code that shows how we parsed our key-value results:

var result:String = "Unknown";
var nodeXml:XMLList = xml.property.(@name == propertyName);
if(nodeXml.length() == 1)
{
result = nodeXml[0].@value;
} else if (nodeXml.length() == 0)
{
result = "-";
} else
{
result = "Too many elements matched " + propertyName;
}
return result;


When to Push Data
This is probably the biggest challenge. If your team doesn't have a skilled Java programmer fluent in Java concurrency programming practices, writing the multi-threaded server could be a steep uphill climb. I'm not going to get into it here in this post; it's a bit too deep and way off topic for a Flex-oriented post.

Assuming you have someone (or can hire someone for this piece), the design focus turns to determining how the server gathers data and when it should push it out over the socket.

NOTE: I say "can hire someone" because the reality is that Adobe's licensing fees aren't cheap. You may actually be surprised with a quote from an experience contractor- even if they charged $100 an hour, if they completed the work in 2 weeks, that's only a cost of $8K. (It took us literally a couple of days for our server - a total of 11 different classes, and we even implemented JMX so we could easily monitor our server from afar!). Spending $8K and having full control, unlimited licensing as you see fit, etc. in constrast to paying $20K, $40K, or more to Adobe for a clusterable solution can be very appealing if your project is on a fixed-budget (what project isn't?!!?).

So how do we know when to push data? In our case, we turned to ActiveMQ and JMS. Effectively, each thread in our proprietary server acts as a proxy for its affiliated browser client. The subscription requests are processed by the thread when it subscribes to the ActiveMQ JMS topic the client is interested in. Then, when messages are dispatched by ActiveMQ, the dedicated thread is notified. Upon notification, it serializes the notification into an XML format that the Flex client knows how to identify and parse.

Where do the JMS message in ActiveMQ come from? Whereever they need to! Messages could be sales booked by an SAP system, they could be work orders that are transitioned from "open" to a "completed" state. You get the idea- look at the entire landscape of the enterprise and start dropping messages into the JMS provider!

So let's recap before we wrap this up.


  • The Flex client creates an instance of XmlSocket and points to the server

  • The authentication mechanims (in this example) required the Flex client to make a quick call via Web Service to ask the server what its authenticated session ID was. Using this ID, an XML request was then dispached over the wire to the server to establish an authenticated session with it.

  • The Flex client can send 1 or more XML messages over to the server to indicate what types of data it wants to have pushed to it.

  • The server-side arcchitecture can be built in many different ways, but perhaps the easiest way is to let each dedicated client thread act as a JMS proxy for the Flex client. The thread subscribes to JMS topics and when it receives notification from the JMS server on a topic, it serializes the data into an XML format that the client knows how to handle



In all fairness, there are a number of discussion points here I didn't fully discuss. For example, what happens if the session times out? How are communications re-established? How does the Flex client know how to process the XML? We actually used a factory design pattern based on the root node name such that every distinct message can have its own ActionScript deserializer. And finally, what about clustering? Yes, failover configuration is important too. There are a number of different techniques that can be employed here too.

Happy Coding!

3 comments:

Vengu said...

Man, You are surely gona save me some money :-)

Thanks a lot for this wonderful post.

Vengu said...

Hi ,

I had tried to implement a little chat program with the concepts explained in this tutorial.
However when I upload it to a server say xyz.com and have the java server running on port 5974 of the same machine,
I get this error:2031 Socket error

I find no reason for this to be happening. The swf connects to the
same server and dont see therefore it cant be a security violation too..

I am left clueless here :-(
Do you have any idea why?

narup said...

This is a very late response but is i don't see the policy request file being handled?? Not required or what.
but it really saved my day.
thanks