Upcoming Training
January 2010
| M |
T |
W |
T |
F |
S |
S |
| « Dec |
|
Feb » |
| | 1 | 2 | 3 |
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
|
|
Archive for January, 2010

Flex RSLs are notoriously naive in regards to dynamic object instantiation. Consider the following code snippet when the actual class descends Panel or it is a remoting DTO with the [RemoteClass] annotation:
var className:String = "some.flex.class";
var clazz : Class = loaderInfo.applicationDomain.getDefinition(className) as Class;
var instance: Object = new clazz();
In either case, well being of the class is based on mixins – decorator classes generated by Flex compiler. Mixins carry obligatory init(o:Object/*systemManager or moduleFactory*/) method and get called to decorate startup class of the application (SystemManager) or the module (ModuleFactory). For instance, a class with [RemoteClass("foo.Bar")] annotation contributes a similar looking fragment to the mixin class _YourApplicationName_FlexInit:
try {
if (flash.net.getClassByAlias("foo.Bar") == null){
flash.net.registerClassAlias("foo.Bar", flex.class.with.RemoteClassAnnotation);}
} catch (e:Error) {
flash.net.registerClassAlias("foo.Bar", flex.class.with.RemoteClassAnnotation); } |
Similarly, a class that descends from a Panel depends on mixin [_YourApplicationName]_Styles to carry the following:
. . .
// spark.components.Panel
selector = new CSSSelector("spark.components.Panel", conditions, selector);
mergedStyle = styleManager.getMergedStyleDeclaration("spark.components.Panel");
style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null);
. . . |
Now, here is the problem. If you hide your class behind getDefinition() Flex compiler does not contribute to either _FlexInit or _Styles mixins. In other words, your RSL may contain 100 classes, all of them will be loaded, but they will be lacking proper initialization if you did not explicitly reference them in the application.
Problem Illustration
Let’s illustrate. On the left is the application that on button click … fails to dynamically instantiate a custom panel from standard Flex RSL. On the right we show working application AFTER the solution has been applied (Patience, reader, patience!)

Here is the application code:
<![CDATA[
import mx.core.IVisualElement;
private var visualElement:IVisualElement;
//import spark.components.Panel;Panel; // That would be too simple :)
private function createComponent(componentName:String) : void {
var clazz : Class = loaderInfo.applicationDomain.getDefinition(componentName) as Class;
visualElement = IVisualElement(new clazz() );
addElement(visualElement);
}
]]> |
The very custom panel is hosted by a separate Flex Library Project – ComponentLibrary:
public static var count:int;
[Bindable] private var instanceNumber:int; |
Make sure the link type of the ComponentLibrary is set to “RSL”. Run the application, click on the Button – you won’t see any panels. Better yet, Debug (instead of Run) and you will notice console trace statements of the panels actually being created. However, custom panel is not shown, because _Styles mixin lacks section for ancestor – Spark Panel.
Solution
So what is the solution? Obviously, the Adobe RSL SWF has to be replaced by something else. By default, ComponentLibrary.swf get extracted from ComponentLibrary.swc on every build of the application. But, if we turn off the “AutoExtract” checkbox, we are free to replace it with the SWF of our own making. Which one? A sub-application SWF. Instead of a headless, single framed RSL SWF, we will use double framed application SWF adding a descendant of the mx.core.SimpleApplication as a head class. Within such head class we can statically reference all library classes. As a result, compiler will generate required mixins within the “library” SWF. That is why in Farata we coined the term self-initialized library, meaning that classes in our library do not need external initialization by the Flex compiler:
package {
import mx.core.SimpleApplication;
public class LibraryHead extends SimpleApplication {
// List all library classes here, so Flex compiler will take care of them
import com.farata.samples.CustomPanel;com.farata.samples.CustomPanel;
public function LibraryHead() {
// Custom library initialization code may go here
trace("Self-initialized library has been loaded");
}
}
} |
As a matter of fact, the last drop required to force Flex compiler into mixin generation is to use a MXML extension of the LibraryHead as the compilation target:
Importantly, we use Ant scripts to build self-initialized libraries, since out of the box Flex library project is not positioned to produce SWFs:
Wait! There is more. In Flex 3 making and using self-initialized library would be enough. In Flex 4, however, we have to replace single line of code that applies the mixins in the mx.core.FlexModuleFactory, ancestor of the SimpleApplication. In place of
c["init"](this);
we should put more sophisticated code that instead of decorating the factory class of the loaded library decorates the factory class of the entire application, i.e. SystemManager:
var mixinTarget:Object;
if (this is FlexApplicationBootstrap) //aka self initialized library
mixinTarget = SystemManagerGlobals.topLevelSystemManagers[
SystemManagerGlobals.topLevelSystemManagers.length-1
];
else
mixinTarget = this;
c["init"](mixinTarget); |
Add this class to the application sources and … it won’t be considered by the SWF. For one thing, if you did not explicitly reference a variable of this class (or use -includes compiler switch) it will not make into SWF at all. Even if you did, however, remember that Flex SWF links the minimal number of classes to the first frame (FlexModuleFactory is NOT among them) and all the rest – to the second. In between (actually – under the control of the first frame’s code) Flex dynamically loads classes from RSLs, starting from signed RSLs and ending with your custom ones. By the time ComponentLibrary.swf get loaded, class definition of the mx.core.FlexModuleFactory will already be grabbed from “earlier” framework.swc. That’s a known challenge of Flex “monkey patching”. The simplest way to overcome it is to overlap application sources with one of the classes that Flex must put in the first frame. It can be custom preloader or mx.core.SystemManager itself, however, in this context we prefer mx.core.RSLListLoader. Simply, add import mx.core.FlexModuleLoader;mx.core.FlexModuleLoader; anywhere in the modified mx.core.RSLListLoader and add it to the source path of your main application along with the modified FlexModuleFactory. Again, we use it to our advantage that all dependancies of SystemManager, including RSLListLoader get linked to the first frame:
import mx.core.FlexModuleFactory; mx.core.FlexModuleFactory; // WE ADDED THIS
public function RSLListLoader(rslList:Array)
{
super();
this.rslList = rslList;
} |
Believe it or not, that’s it.
Here is the summary of the steps:
1. Turn-off “autoextract” of the SWC
2. Create self-initialized library SWF and place it into bin or bin-debug
3. Add monkey-patched FlexModuleFactory and RSLListLoader into Flex sources
4. Say good-bye to plain old Flex RSLs.
I’d like to use this opportunity and invite Flex developers living in Europe to attend our Advanced Flex Master Class in Brussels, Belgium on March 1 and 2, 2010.
Victor Rasputnis
Permalink

A month ago I wrote a blog titled “The RoadMap for Adobe LCDS 3”. I was so naïve suggesting cutting the prices for LCDS licenses!
The inexpensive ($6K per CPU) departmental license is discontinued. LCDS Express edition is gone.
Get ready to pay around $30K per CPU for Enterprise LCDS 3 license. It’s really sad that Adobe marketing is killing a great product created by Adobe software engineers.
After reading the chain of comments to the blog of Anil Channappa, LCDS and BlazeDS project manager, it seems that Adobe does everything to ensure that our open source Clear Toolkit with BlazeDS will become even more popular.
Clear Data Builder (the flagship piece of Clear Toolkit) generates both Flex and Java code from POJO or SQL, supports data sync between different users (yep, with ChangeObjects under the hood), does the server side data push over AMF, knows how to deal with master-detail (hierarchical) collections, supports transactions, has smart DataForm and Validator components. We also know how to make BlazeDS scale to support many concurrent users.
Almost forgot, we have generators for AS3 classes from their Java peers and a generator of ANT build scripts from your Flex Builder projects.
Do you know the cost of Clear Toolkit per CPU? You got it. It’s zero dollars, euros, rubles and rupees.
At the time of this writing Clear Toolkit doesn’t support Model-Driven development…Read my lips.
If there is a customer who wants to hire us and shell a little bit of cash for R & D, we can add a support of RTMP too (shared copyright only).
Adobe also stopped offering commercial support of BlazeDS. Well, you know where to go for this.
Some companies have short memories. When Flex own by Macromedia, was server-side only and priced at $15K, nobody knew about this product. After the merger in late 2005, Adobe did a really smart move by moving this great tool to the client side with reasonably priced Flex Builder. Now, it looks like Adobe re-hired those old Macromedia salesmen. Big mistake.Huge.
Yakov Fain
P.S. I’d like to use this opportunity and invite Flex developers living in Europe to attend our Advanced Flex Master Class in Brussels, Belgium on March 1 and 2, 2010. We still have a couple of seats available.
Permalink

First of all, Flex and BlazeDS are open sourced and free, which is important for many IT shops even those from filthy rich Wall Street companies. Typically, an enterprise IT group has a limited budget, and even though a more advanced LiveCycle Data Services component offers you more options and better scalability than BlazeDS, for most of the applications using BlazeDS installed in any Java Servlet container is a very solid way of building RIA that are a lot more superior to those built on plain HTTP let alone SOAP Web Services.
The main power of BlazeDS is its binary AMF protocol that seamlessly serializes strongly typed data between Flex and Java. Just think of the typical use case described below.
A POJO on the server side gets a bunch of Customer.java records (say, ArrayList) from a data source and needs to display them as a grid in a Web Browser. With a regular HTML/JavaScript Web application you’d need to convert the customers’ data into some kind of text representation (losing the data types information of customer data), then GZip the data, send them to the client, and using JavaScript manipulations convert the data into appropriate data types for further processing.
You don’t need to do any of these while sending the data from Java on the server to Flex on the client. The ArrayList of customers gets serialized/deserialized into an ActionScript ArrayCollectoin of strongly typed data transfer objects defined in the class Customer.as.
HTTP batching and streaming is a combination of few technologies with a close resemblance to how car traffic is controlled on some highways. There are dedicated lanes for high-occupancy vehicles (HOV) that move faster during the rush hours. Such HOV lanes can be compared to the
HTTP channels opened for streaming. For example, you can program network communications in such way that one channel allows only two data pushes per second (a guaranteed QoS), while the other channel will try to push all the data, which may cause network congestion, delays, and queuing.
With AMF, the data gets loaded faster than with nonbatched requests/responses. And it plays nicely with the typical infrastructures that use firewalls as it piggybacks on the existing browser HTTP requests.
However, for critical HTML/JavaScript applications a problem remains: there is no QoS provided by HTTP protocol, which may become a showstopper. For example, think of a financial application that sends real-time price quotes to the users. The server keeps sending messages, regardless of the current throughput of the network, which in case of network congestion will be causing problems with queues overruns or lost packages.
Recently released LCDS 3 has introduced features to support reliable messaging and throttling, while BlazeDS won’t have it. This is when opensourceness of Flex and BlazeDS becomes handy, because it allows you to customize communication protocols to perfectly meet all the needs of your application and squeeze out a lot more performance from BlazeDS than it’s advertised by Adobe.
How do you even start customizing network protocols? Even the idea of doing this sounds scary, right? It won’t be, if you’ll attend our Master Class in Brussells, Belgium in March: http://www.eventbrite.com/event/527934065. We are planning to run a couple of more if these events in the USA too. Let me throw in some technical terms now since not everyone can appreciate the quality of the Belgium beer yet.
If you open the server-side configuration file services-config.xml that comes with BlazeDS, you’ll find declarations of several communication channels there, for example:
<channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
<endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/>
</channel-definition> |
This is an example of configured AMF communication channel. There are three important notions to understand here.
1. AMF operates using messaging under the hood. When you make an RPC call to a remote Java class (a.k.a. destination). Flash Player sends messages to the server, and you can change the way messages are being formed or processed.
2. On the client side (Flex) the ActionScript class a.k.a. channel can be customized, if need be. In the example above this would be the class mx.messaging.channel.AMFChannel.
3. On the server side, there are two Java classes that can be customized: an endpoint (see above flex.messaging.endpoints.AMFEndpoint) and adapter.
Let’s say, you want to ensure that every message header includes a userID that has been authenticated during the logon process, you can do it by customizing the channel and the endpoint classes. This way you won’t need to pass the user ID with every application-specific RPC call.
Two years ago, one of our financial clients was concerned with potential out-of-sequence messages in a trading workflow. Back than it was the application based on LCDS 2.5, which didn’t offer any support in this area. We’ve customized the channel and adapter to provide this functionality. We’ve also implemented throttling to slow down the message pushes in congestion situations. The same things can be implemented with BlazeDS.
Or let’s take another real-world situation when an extra security is required: the client’s workstation has to be automatically logged off and disconnected, if the server didn’t respond during a specified time interval. To put it simple, we need to implement some kinds of heartbeats. Yes, you can customize the AMF protocol so it’ll process heartbeats between the Flex client and Java server.
Didn’t respond to my heartbeat within 20 second? You’re a dead man! The user get’s logged out of the system.
Need better performance with BlazeDS? Introduce a non-blocking I/O.
How about an idea of a reverse RPC call? I mean what I mean. A Java server calls a specified function on the user’s (Flex) application passing whatever arguments are required by the function.
“You may say, I’m a dreamer. But I’m not the only one”, sang John Lennon.
For some reason, most of the RIA developers are into flashy UI as it’s considered to be uber cool. But don’t underestimate the power of the networking protocols in general and of AMF in BlazeDS in particular. At least I know, where the power of Flex and Java EE application is hidden.
Yakov Fain
Permalink

In my previous post I pointed to the BlazeDS classes that need to be replaced in order to prevent ActionScript Number.NaN from turning into Long or Integer zeroes on the MessageBroker side. The recommendation boiled down to re-jaring flex-messaging-core.jar or placing the modified classes somewhere earlier in the application server’s classpath. If neither option is allowed, you may configure your endpoint with the custom type marshaller, like the one below:
<channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
<endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf"
class="flex.messaging.endpoints.AMFEndpoint">
</endpoint>
<properties>
<serialization>
<type-marshaller>com.farata.messaging.io.CustomTypeMarshaller</type-marshaller>
</serialization>
</properties>
</channel-definition> |
In BlazeDS 4 you will base your type marshaller on flex.messaging.io.ASTranslator, in BlazeDS 3 they already have one level of extension called Java15TypeMarshaller, so build on top of that one:
package com.farata.messaging.io;
import com.farata.messaging.io.amf.translator.decoder.NumberDecoder;
import flex.messaging.io.amf.translator.decoder.DecoderFactory;
// For BlazeDS 4 you should extend flex.messaging.io.ASTranslator
public class CustomTypeMarshaller extends
flex.messaging.io.Java15TypeMarshaller {
private static final NumberDecoder numberDecoder = new NumberDecoder();
public Object convert(Object source, Class desiredClass)
{
if ( DecoderFactory.isNumber(desiredClass)){
return numberDecoder.decodeObject(source, desiredClass);
}else{
return super.convert(source, desiredClass);
}
}
} |
This route does not require neither server-level deployment nor modification of the flex-messaging-core.jar.
Please note that in my example I repackaged NumberDecoder as com.farata.messaging.io.amf.translator.decoder.NumberDecoder
I’d like to use this opportunity and invite Flex developers living in Europe to attend our Advanced Flex Master Class in Brussels, Belgium on March 1 and 2, 2010.
Victor Rasputnis
Permalink

This question we get on almost every new client project: “We’re struggling with handling of null values for numeric data types in Flex/Java projects. Every time there’s an update, we end up replacing the original nulls with zeros when the user didn’t actually change that value. Have you guys come up with a silver bullet for handling numeric nulls?”
Consider a Java method with a Double parameter. You pass uninitialized ActionScript Number, that is, Number.NaN. What will BlazeDS deserialize (unmarshal)? Double.NaN. At this point your Java code may use something like (value==Double.NaN)?null:value, capitalizing on the fact that information about special value of NaN had been delivered from your client code to your server code. Now, let’s assume you change the signature of the Java method to accept Long instead of Double. You pass NaN and you get … 0! The same happens with marshaling ActionScript object that carries Number.NaN properties: they turn into 0, if, god forbid, their Java counterparties are declared as Long or Integer.
The reason is that while Java has Double.NaN it does not support either Long.NaN or Integer.NaN. Looking at the following snippet of code you can see how differently Double and Long variables get treated by Java:
Double dbl = new Double(Double.NaN); // We emulate incoming numeric null
System.out.println(dbl); //prints NaN, cause dbl "knows" it came from null
long l = new Long(dbl.longValue(new Double(Double.NaN)));
System.out.println(l); // Oops, prints 0! |
Unfortunately, native BlazeDS flex.messaging.io.amf.translator.NumberDecoder falls into this trap. So, what is to be done? Luckily, BlazeDS is an open source product and this class has to be slightly modified.
Figure 1 illustrates the changes required to protect null-ability of your Long, Integer, etc values, except Double (we explain what to do with Double-s a bit later):

Figure 1. Modified NumberDecoder. Farata modification is on the left, canonical BlazeDS class is on the right.
Now, after you make the changes and compile the class against the rest of the flex-messaging-*** jars you can re-jar your own flex-messaging-core.jar.
Better yer, place this class in the common server folder so that it positively affects classpath of all applications on the server.
From now on, Number.NaN will come as Long null, or Integer null – whatever you decide on the Java side.
It this sounds like to big of a deal to you, keep using Double values and convert Double.NaN to null yourself, when appropriate.
Finally, if you would also like to see Double.NaN automatically converted to null, you will have to substitute one more BlazeDS class – flex.messaging.io.amf.translator.NativeDecoder. Explanation: it’s just so happens that BlazeDS marshalling ignores the NumberDecoder when the source (Number, aka Double) and target (Double) types are the same. Here we come and force BlazeDS to use NumberDecoder with numbers no matter what:
public class NativeDecoder extends ActionScriptDecoder
{
public Object decodeObject(Object shell, Object encodedObject, Class desiredClass)
{
if ( DecoderFactory.isNumber(desiredClass)){
NumberDecoder numberDecoder = new NumberDecoder();
return numberDecoder.decodeObject(encodedObject, desiredClass);
} else
return encodedObject; // the sole original BlazeDS line
}
} |
Source code:
NumberDecoder.java modified by Farata
NativeDecoder.java modified by Farata
I’d like to use this opportunity and invite Flex developers living in Europe to attend our Advanced Flex Master Class in Brussels, Belgium on March 1 and 2, 2010.
Victor Rasputnis
Permalink

After teaching our popular advanced Flex master class in New York, Boston, Toronto, London, and Moscow we are hitting the beer capital of the world: Brussels, Belgium. This class is scheduled for the first days of March, and we hope that Flex 4 will be officially released by this date. Our book Enterprise Development with Flex should hit the book stores by then too.
To take advantage of the early bird prices register early at http://bit.ly/59DdIU.
If you can’t make it to Brussells, I’ll be glad to meet with you at 360 Flex in San Jose, CA on March 7-10, where I’ll be presenting on one of the topic from this master class.
If you can’t make it to San Jose, I’ll be very happy to meet you at Flash and the City conference in May in New York City. Most likely I’ll show you a really cool way of embedding a Flex application into a PDF file to be played by Acrobat Reader.
If none of these dates/locations work for you, you can always invite us to teach this class privately on site in your organization almost anywhere on the planet Earth.
Yours
Yakov Fain
Permalink
|