Thursday, August 16, 2007

DisplayShelf Bug - Work Around

Over at Quietly Scheming Ely Greenfield has posted a really powerful DisplayShelf component. Since the license is commercial-software friendly, we decided to use the component in one location where the user is presented with a list of images that they needs to scroll through. Actually, we put the display shelf on the top 1/2 of the window, a data grid on the bottom half of the window and linked the scrolling between the two.

There is actually a nifty (read nasty) little bug that we (and apparently others) ran into. We kept getting the following error when we would reset our search listing:


TypeError: Error #1009: Cannot access a property or method of a null object reference.
at DisplayShelf/::calcPositionForIndexSelection()
at DisplayShelf/::calcPositionForSelection()
at DisplayShelf/DisplayShelf::updateDisplayList()
at mx.core::UIComponent/validateDisplayList()
at mx.managers::LayoutManager/::validateDisplayList()
at mx.managers::LayoutManager/::doPhasedInstantiation()
at Function/http://adobe.com/AS3/2006/builtin::apply()
at mx.core::UIComponent/::callLaterDispatcher2()
at mx.core::UIComponent/::callLaterDispatcher()


After pounding our heads on the wall for awhile, we figure out (indirectly) what the exact cause of the problem was. Effectively, here's the use case that consistently generates this error:


  1. Populate the display shelf data provider with say 10 rows of data

  2. Select row #8 in the display shelf

  3. Re-populate the display shelf's data provider with a new list of rows that has only 5 entries in it.

  4. BAM! Exception.



However, through hours of tenacious testing (read pure luck strikes within minutes of throwing in the towel), we discovered that the following scenario never crashed:


  1. Populate the display shelf data provider with say 10 rows of data

  2. Select row #3 in the display shelf

  3. Re-populate the display shelf's data provider with a new list of rows that has only 5 entries in it.

  4. No Exception- life is good!



So we quickly realized that there must be some internal flag that isn't being reset properly despite the dataProvider's documented approach of being dynamically linked to the underlying data provider (ArrayCollection in our case).

The Workaround
We simply didn't have time to trace through the components code and determine where the root bug was, but we did find a really easy workaround: reset the displayShelf.selectedIndex to 0 prior to re-populating the list. When we added this one line of code in, we could no longer reproduce the error. Problem solved!

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!

Wednesday, August 8, 2007

Servlet Audio Streaming

Ran into a great "feature" today in QuickTime today. It took the whole morning to resolve, so I figured I might as well share the solution with the blogosphere. Perhaps it is/was common knowledge, but darned if I could find the right Google to tell me this information!

Effectively, we have audio recordings in .amr format (Wikipedia) that were sent from a J2ME-enabled device to the database. We then needed to allow the users to play these recordings at will in their browser. We built a simple servlet and secured it behind a security constraint. Hitting the servlet results in the audio streamed down to the client; it properly set the MIME type to audio/amr as well.

We choose/standardized on QuickTime as the means to do this because QuickTime offers native .amr encoding support with no specialized encoding downloads required. However, when the QuickTime player would see the URL ending in ?recordingId=2 it would puke everytime and we'd get the infamous QuickTime logo with a question mark displayed. After literally nearly 2 hours of googling around, on a whim, I decided to add the following at the end of the query string:


&dummyFileName=dummy.amr




Low and behold, QuickTime properly recognized and played the audio! So the morale of the story here is simple- QuickTime apparently looks at the file extension even in a URL to determine the media type. This is even if the type= property is set in the embed tag in the HTML page... go figure.

For those curious, here is the <Object> tag that finally ended up working:



<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="150" height="16" codebase="http://www.apple.com/qtactivex/qtplugin.cab" >
<param name="src" value="/secure/PlayRecording?recordingId=<%=request.getParameter("recordingId")%>&dummyfilename=recording.amr" />
<param name="conroller" value="true" />
<param name="autoplay" value="false" />
<object data="/secure/PlayRecording?recordingId=<%=request.getParameter("recordingId")%>&dummyfilename=recording.amr" width="150" height="16" class="qt">
<param name="controller" value="true" />
<param name="autoplay" value="false" />No
</object>
</object>

Thursday, August 2, 2007

Logitech VXRevolution

After many years with my trusted companion, I regret to inform the blogosphere the Alex has died. Alex was my mouse for nearly 5 years, and despite the visual wear, he was an excellent mouse. So 2 days ago I set out to buy a new mouse- not a task I was particularly excited about doing since I'm very picky about my pointing devices. I patroned the local BestBuy and was shocked that they didn't offer any Bluetooth mice. EVERYTHING was with a small USB stick. I'm not sure what that actually means; but I had wanted a Bluetooth device because my MacBook Pro has Bluetooth built-in. So after much contemplating and checking out the games on their demo PS3, I finally decided to try the Logitech VX Revolution.

This mouse is amazing.. I've named him "Victor" after the "V" in his model name.

Logitech has created a mouse with what they desribe as a "MicroGear Precision Scroll Wheel." On the bottom of the mouse you can choose to engage the gear and get that "clicking" feedback when you scroll, or completely disengage the gear. When the gear is disengaged, the wheel is as close to frictionless as they could make it, meaning it just spins and spins until you put your finger back down to stop it. For coders like me who routinely open up an ActionScript class or Java class in Eclipse that could be a couple 1000 lines long, scrolling up and down is friggin' unbelievable now. You quickly learn how much velocity the wheel needs, and it just spins. Heading all the way toward the top? Give it a big spin and watch the page scroll up. Looking for something? Give it a gentle spin and its no different then clicking and holding the vert scroll bar. This mouse has changed the way I move around in my files!

Alex left some big shoes to fill, and so far Victor is stepping up and filling those shoes. If you need a new notebook mouse, you absolutely owe it to yourself to seriously consider this mouse!

Eclipse Configuration

I read an interesting post over at Marc Hughes' blog about sharing Flex projects. It struck me as odd that something as critical as a project's CLASSPATH wouldn't be considered "important enough" to include in version control. It means that if a new developer comes on the project, that developer would have to by-hand configure an entire classpath. In the case of the application I'm working on, we have a single <mx:Application/> and then literally over a dozen <mx:Module>/>'s that can be plugged-in based on what the customer orders. As a result, there are module dependencies that exist, and some of our CLASSPATHs are pretty long. Add in the pathing for the localization files and it could be a lot to configure.

For this reason, we use Eclipse's core features to properly buffer the project from the physical root directory of the project. The tips presented here are also used for our Java projects that run the backend (although it is worth noting those variables fall under Java...Build Path...Classpath Variables in the Preferences dialog). Of course our whole build and deployment is Apache Ant based, but the code completion and such in Eclipse needs a valid CLASSPATH to be useful. So here is the simple variable approach that you should use to setup Eclipse so that you can easily check-in your .project, .actionScriptProperties and .flexProperties files into your version control without enduring pathing headaches.

In Eclipse, go to Window...Preferences.
Expand the General branch, Workspace, and then finally click on Linked Resources.

Adobe itself uses this technique and there should already be a variable there named FRAMEWORKS that points to the Flex SDK.

We defined a single variable, we'll call it APPBASE for the purposes of this blog and it points to /projects/ourapplication. Now, defining the variable here is only half the equation. Close the Preferences window and bring up your individual Flex project properties. You can get there by right-clicking on your Flex project and choosing Properties. Then, click on the Flex Build Path in the tree, choose either Source Path or Library Path up at the top of the dialog as appropriate. Similar to Apache Ant, the Eclipse IDE allows you to reference your variables using a notation like this: ${VARIABLE-NAME}. Thus, in our case, we define 100% of our paths using ${APPBASE}. And voila- our .actionScriptProperties file can now be checked into svn, and if a developer is operating against a different path, all they have to do is modify (or if they are new to the project, define) a single variable. In fact, here is a sample line from the .actionScriptProperties file:

<compilerSourcePathEntry kind="1" linkType="1" path="${APPBASE}/common/common/as"/>

Now, there is no excuse not to capture your paths in version control, making life easier for developers across the project. As a concrete example, if an existing project requires a new SWC as a dependency, you don't have to rely on sneaker-mail or email to tell the team members to add abcd123.swc to their path- just add it, then commit your .actionScriptProperties file. On the next update that includes the new code, the classpath will be updated as well!

CLASSPATHs in Java were/are the worst part of the language. The mxmlc and compc compilers run against classpaths. A little bit of knowledge about your IDE can go along way! Otherwise, development in ActionScript can quickly become a pathing nightmere.

Wednesday, August 1, 2007

Working with Key-Value Pairs

The large application I work on uses an extensive plug-in architecture that allows us (or our clients) to radically change the behavior of the application quickly. In most of our situations, we know our concrete classes ahead of time because we extensively test them before releasing them into the wild. As a result, we use a Factory creational pattern that keeps the requestor class independent of the actual concrete class. Here's the classic example of this pattern (in Java):


public static final int IMAGE_JPG = 0;
public static final int IMAGE_GIF = 1;
public static final int IMAGE_PNG = 2;

Image createImage(int imageType) throws UnsupportedImageTypeException
{
Image newImage = null;
switch(imageType)
{
case IMAGE_JPG:
newImage = new JPGImage();
break;
case IMAGE_GIF:
newImage = new GIFImage();
break;
case IMAGE_PNG:
newImage = new PNGImage();
break;
}

if(null == newImage) throw new UnsupportedImageTypeException("Unknown type");

return newImage;
}


Nearly everyone of our plug-ins allows the customer to define their own parameters. For example, our application has the requirement to forward or relay data to the client's specified web server when certain events transpire. To get that information on a client-by-client basis, we rely on the client to define key-value pairs. In this arbitrary HTTP example, clients define:

  • authentication as {none, basic}

  • username

  • password

  • method as {POST, get}

  • url

  • etc.



Gathering these key-value pairs is simple, but early on we realized the value in creating a re-usable component to handle this situation. Since there isn't any real intellectual property in this component per se, I figured I'd share it with the blogosphere for all to use.

This component is driven by 3 classes:


  1. KeyValuePair.as - simple class that defines propertyName and propertyValue attributes.
  2. KeyValueCollection.as - class that extends the ArrayCollection class and implements a smart constructor and sorting routines that facilitate the easy management of key-value pairs.
  3. KeyValueScreen.mxml - this is the main UI for the component.


A functioning demo app and all the source code is available over here at my non-developed personal site (hey- there's only so many hours in the day, and blogging provides more value then me setting up an "I love me" web site, no??). As always, right click and choose "View Source" to see how things were written.

So here's a bit of an explanation of the components architecture. The KeyValuePair class should be self-explanatory. The KeyValueCollection class is responsible for managing the collection of key-value pairs. Its constructor is smart enough to iterate through the collection its provided and look for an either instance of KeyValuePair or instance of an Object that has the properties propertyName and propertyValue. In fact, the hasOwnProperty() method in ActionScript is a super easy way to do some basic reflection on unknown classes. This is a classic example of where a class may not be a concrete instance of KeyValuePair, yet the component utilizes reflection and can still make an informed decision as to the applicability of the object to participate in the collection. For those OO newbies, I'm describing effectively the difference between inclusional and operational polymorphism. Since a discussion on this would be off-topic, a quick google found this page here that quickly describes the differences.

The Flex manual is very explicit about how to effectively use the IViewCursor interface. First and foremost, the interface supports addition and removal of properties, but not updates per se. Next, the interface docs indicate that "the findAny() method can be somewhat more efficient than either the findFirst() or the findLast() method." By leveraging this knowledge, the class can quickly discern if the key already exists in the collection without having to manually iterate over what could be the whole collection.

Side Bar: I've not had the chance to really look at the sorting algorithm that ActionScript uses, but I can only assume that the gurus over at Adobe aren't implementing something that takes time proportional to N^2 to sort N randomly arranged items.

The collection is extended to include 2 new methods, insertOrUpate() and remove(). As the name implies, you can add or update an existing key-value pair with the first method, and altogether remove the key-value pair with the later method. By using the IViewCursor's findAny() method, we can quickly determine if an insert or update (delete-add, in this implementation) will take place.

The UI in the MXML file exposes a public property named propertyList that provides the requestor with access to the key-values that the user manipulated. The demo should be pretty clear as to how one can add or remove key-values from the UI. I've also skinned the add and remove buttons a la Mac OS X. The +/- metaphor is used extensively over here on my platform of choice, and it is fairly intuitive to pick up for newbies using the app.

I'm sure this component is suitable for many needs, but I actually had to strip a bunch of functionality out before posting it- so your mileage may vary (i.e. you may need to expand or add some more functionality). For example, our app is localized and so all of the labels and messages in my real-world component used ResourceBundle instances to manage those labels.

Enjoy!