Upcoming Training
July 2010
| M |
T |
W |
T |
F |
S |
S |
| « Jun |
|
|
| | 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 ActionScript

We started the process of open sourcing of our Clear Toolkit framework for developing enterprise Rich Internet Applications with Adobe Flex and Java. The source code is located in the Sourceforge CVS repository at http://sourceforge.net/projects/cleartoolkit/ . The current documentation, demos, user forums, and bug trackers are also there.
Clear Toolkit 3.1 includes the following Eclipse plugins and components:
Clear Data Builder 3.1 is an Eclipse plugin that allows to generate CRUD applications for BlazeDS or LCDS based on either an SQL statement or a Java data transfer object.
DTO2Fx is a utility that automatically generates proper ActionScript classes based on their Java peers.
Log4Fx is an Eclipse plugin built on top of Flex logging API, but it automates and makes the logging process more flexible and user friendly.
Fx2Ant is a generator of optimized ANT build scripts for your Flex Builder projects.
clear.swc is an enhanced Flex component library. The source code of all components is located in the package com.farata.components.
Clear Toolkit roadmap includes the following enhancements this year:
1. Offer data synchronization solution for AIR/BlaseDS applications - February 2009
2. Enhance Flex UI component to support PDF generation on the client – April 2009
3. Offer a solution for Flex-based portals – May 2009
4 Document classes from our component library (clear.swc) – June 2009.
All these components were (and still are) offered for free at http://www.myflex.org but now we are inviting developers from around the world to join us in making Clear Toolkit the open source platform of choice for all Flex developers
Yakov Fain
Permalink

If you had only one hour in Paris, what would you do?
I, for one, would walk around Notre-Dame, and the point I am going to make is about Flex:
If I could pass just one Flex advice that would be: Use Data Transfer Objects.
Use Data Transfer Objects and NOT the dynamic Objects, and NOT the XML to pass data between your server and Flash tiers. If you are working with a Java Server, make your Java (methods) accept/return custom classes and NOT Map objects.
With this keystone your architecture will be reliable and performing. You will save tons of time and energy. What do you do with these savings – none of my business.
Here are the details:
1. _DO_ define similar classes on Java and ActionScript. See details of Java/ActionScript type mapping in the Flex documentation.
2. _DO_ declare these classes as [Bindable] if you envision dynamic updates to the data. Further, _DO_ use collections of these Bindable instances as dataProviders for your DataGrid and let Flex do the miracle: all changes to the data will be reflected by the visual control. There are no miracles, of course: [Bindable] is a shortcut to dispatch event on a data change, the very same event that is expected by ArrayCollection. The collection in turn, dispatches a (different) event on its change. Importantly – the very same event that is expected by the DataGrid.
Let me put it another way: have you ever used collection.itemUpdated()? Well, once you start DTO’s “itemUpdated” will sound to you like the name of the undocumented event
OK, I will rub it in further: if you marshall (property) Array of Objects, the Array itself is Bindable, but none of the items are.
3. Make sure that your server-side and client-side DTOs _DO_ provide unique! set/get uuid property. Flex loves this property, do get in love with it too. Flex is using it to identify elements of data presented by the list-based controls. You will find numerous uses for it as well. For instance, instead of sorting by industry, ticker you would sort by industry, ticker and uuid. Why? Because then the hash value will be unique for each record, which would result in substantially better performance.
4. _DO NOT_ hunt for value change on the visual controls (aka View). This task belongs to the data layer (aka Model). Consider replacing [Bindable] public var with the get/set property pair and dispatching the event (PropertyChange) yourself:
private var _amount:Number;
public function get amount() : String{
return _amount;
}
public function set amount( value : Number ):void{
var oldValue:Object = this._amount;
if (oldValue !== value) {
this._amount = value;
dispatchUpdateEvent(“amount”, oldValue, value);
}
}
private function dispatchUpdateEvent(propertyName:String, oldValue:Object, value:Object):void {
dispatchEvent(
PropertyChangeEvent.createUpdateEvent(this, propertyName, oldValue, value)
); �
}
Then, to act on value change, consider customizing the set method. Better yet, consider extending your ActionScript DTO with another class: leave basic layer of DTOs untouched, do customization in the extension. One more gain right here: now you can intercept (breakpoint) whenever your data changes.
5. _DO_ use extension of DTO class (above) to introduce “computed columns”:
public function get unrealizedGain():Number {
return lastPrice – costBasis; �
}
Again, _DO NOT_ use itemEditEnd of the control for these and similar purposes.
_DO NOT_ be afraid of two [RemoteClass] pointing to the same Java DTO: Flex will resolve the reference in favor of the extension layer.
6. Over your project lifespan, you will see many additional fits for DTOs: custom serialization, custom toString() and toXML() methods.
Now, you may say that all these recommendation are way too obvious.
Then I just take off my hat and … see you around Notre-Dame, perhaps.
Otherwise, keep coding.
Victor
Permalink

Introduction
Flex has a short learning curve for Java developers, who will find there lots of familiar language constructs and patterns. It also provides excellent remoting capabilities for Java programmers allowing transparent data transfer between ActionScript and Java 1.4 data types. With Java version 5 and above you have a lot of Java data structures that use enum and need marshaling to/from the Flex applications. In this article I will provide a working example of the ActionScript language extension for enum data type. We will discuss the issues common for adding language extensions to the bytecode machines/compilers. We will also extend LiveCycle DataServices AMF3 protocol to support native translation of classes between Java 5 and ActionScript 3.
Problem Statement
One of the most discussed limitations of LiveCycle Data Services (LCDS) serialization mechanism is a lack of serialization support for Java 5 enumerations. It is partially due to the fact that the code is supposed to work against Java 1.4, which did not have enums. This problem is acknowledged by Adobe, so one of your choices is just waiting for the next release of LCDS. But, alternatively, with a moderate effort you can extend existing data service classes and get the necessary functionality right away.
Let us review some facts about Flex AMF serialization to understand better why LCDS fails to serialize enumeration values out of the box. Flex serialization does not mimic Java’s serialization, it has only some similarities. Here are restrictions for remoting imposed by the default behavior of serialization:
1. Remote Java objects must have a public no-arguments constructor to be successfully de-serialized. With Java serialization, even objects without such constructor can be de-serialized as long as they implement java.io.Serializable marker interface.
2. Flex populates all public non-final non-transient instance fields upon deserialization and sets the JavaBean properties (exposed as pair of get/set methods) of the instance. Java serialization mechanism populates all non-transient instance fields (even the final ones). By the way, FDS and LCDS use JavaBean introspection mechanism to find out the object’s properties, so in theory you may use any method names besides classic getSomething / setSomething pair as long as you provide necessary BeanInfo class.
3. Flex may use externalization instead of serialization. Your Flex class has to implement flash.utils.IExternalizable interface and the corresponding remote Java class must implement java.io.Externalizable.
As you can see, the items 1 and 2 from list above rule out Java 5 enumerations from Flex serialization process. We will need a custom serialization on the Java side to serialize/deserialize enumerations. But first, take a look at the following simple Java enumeration:
public enum Gender { MALE, FEMALE }
Under the hood, Java compiler generates something like this (decompile the generated class with one of the free Java decompilers available on Web):
final public class Gender extends Enum<Gender> {
private Gender(String name, int ordinal) { super(name, ordinal); }
public static final Gender MALE = new Gender(“MALE”, 0);
public static final Gender FEMALE = new Gender(“FEMALE”, 1);
/* rest is omitted */
}
First of all, there is no public no-arguments constructor. Second, inherited “properties” name and ordinal of custom enumeration type are read-only. So even any Java 5 enumeration is a valid type for Java serialization due to explicit built-in support, it can’t be used as Flex remote class. Actually, we may not use externalization mechanism either while it’s impossible to restore internal read-only fields of enumeration value in implementation of java.io.Externalizable.readExternal().
Solution
What we would like propose is a small extension that allows using custom Java 5 enumerations as remote classes with minimal effort. In short, this is a drop-in extension for standard Flex AMFEndpoint classes that augments LCDS functionality with special support for Java 5 enumeration types.
Adobe engineers take extensibility aspect of LiveCycle Data Services 2.5 seriously. Besides numerous code-free configuration options available out-of-the-box, the API itself is very developer-friendly. The endpoints and AMF serialization framework have a lot of extensibility hooks and have nicely applied creational design patterns, so extending existing functionality is a joy.
The idea of our extension library is to intercept read/write operations with enumeration type as argument, substitute enumeration type with some wrapper that plays nicely with Flex serialization rules and pass this wrapper to super implementation. Please download and explore the source code at http://www.myflex.org/articles/downloads/farata-j5-messaging.src.zip.
You should start from com.farata.messaging.endpoints.J5AMFEndpoint class that redefines classes used for serialization/deserialization of AMF messages.
public class J5AMFEndpoint extends AMFEndpoint {
public J5AMFEndpoint() {
this(false);
}
public J5AMFEndpoint(final boolean enableManagement) {
super(enableManagement);
deserializerClass = J5AmfMessageDeserializer.class;
serializerClass = J5AmfMessageSerializer.class;
}
}
Then, overridden serialization classes will immediately lead you to extended AMF0/AMF3 input/output classes where actual enhancements are provided. For example:
public class J5Amf3Output extends Amf3Output {
public J5Amf3Output(final SerializationContext context) {
super(context);
}
@Override public void reset() {
super.reset();
enumTable.clear();
}
@Override public void writeObject(final Object o) throws IOException {
if (o instanceof Enum) {
@SuppressWarnings(“unchecked”)
final Enum<?> e = (Enum<?>)o;
EnumHolder holder = enumTable.get(o);
if (holder == null) {
holder = new EnumHolder(e);
enumTable.put(e, holder);
}
super.writeObject( holder );
}
else
super.writeObject(o);
}
final private IdentityHashMap<Enum<?>, EnumHolder> enumTable = new IdentityHashMap<Enum<?>, EnumHolder>();
}
But before trying to play with the library, it’s necessary to answer one question,”How enumeration in Flex should looks like?”
If you are a seasoned Java developer then you might recall that before Java 5 it was common to use “Type-safe enumeration” pattern to emulate current enumerations feature. The pattern works quite well, and, in fact what Java compiler currently generates for enumeration closely resembles this pattern. Below code shows Gender enumeration of pre-Java 5 era:
final public class Gender implements java.io.Serializable {
private static int INDEX = 0;
final private int ordinal;
final transient private String name;
private Gender(String name) {
this.name = name; this.ordinal = INDEX++;
}
public String name() { return name; }
public int ordinal() { return ordinal; }
public String toString() { return name; }
/*
hashCode and equals are not overwritten
while we need identity equality
provided by Object class by default
*/
public static Gender[] values() { return (Gender[])VALUES.clone(); }
public static Gender valueOf(String name) {
if (“MALE”.equals(name)) return MALE;
if (“FEMALE”.equals(name)) return FEMALE;
throw new IllegalArgumentException(“Unknown enumeration entry name: ” + name);
}
private void Object readResolve()
throws java.io.ObjectStreamException {
return VALUES[ordinal];
}
public static final Gender MALE = new Gender(“MALE”);
public static final Gender FEMALE = new Gender(“FEMALE”);
private static final Gender[] VALUES = {MALE, FEMALE};
}
Majority of the code above is simple to grasp. We restrict clients from creating arbitrary instances of a class with private constructor and expose a limited number of instances via class-level constants. The only tricky place here is readResolve method, which is absolutely necessary. One of the ideas of “Safe-type enumeration pattern” and current Java 5 enumerations is to enforce the identity equality comparison between enumeration values. So we must replace any new entry created by serialization mechanism with corresponding class-level constant to enable this feature. Note also, that during deserialization of this class in Java its constructor is not invoked and the ordinal field is assigned by JVM.
In effect there are only 2 instances of Gender per class-loader and any new temporal instance created during deserialization is immediately replaced by one of the constants above, so client code may safely rely on identity equality.
So, is “Type-safe enumeration” pattern reproducible in ActionScript3? Well, depending on your view of the “half-full/half-empty glass” problem, the answer varies between “yes, up to certain extent” and “not exactly”:
1. Private constructors in ActionScript3 are not available. So no compile-time checking can be applied; the best thing we can do to enforce the Singleton functionality is throwing a run-time Error from constructor if object is instantiated by client code rather then as part of class constant initialization. By the way, enumeration is a generic example of Singleton design pattern, and what is typically called singleton is a special case. The pattern itself is about limiting number of instances of specific class, be it either five or one instance.
2. Flex de-serialization mechanism always invokes a constructor of the target class. This is something we have to deal with.
3. Here’s the toughest issue: there is no mechanism like readResolve in Flex. As it is explained above, the readResolve method in Java allows to replace deserialized object with other instance. In case with type-safe enumerations or built-in Java 5 enums this replacement is an instance declared as static constant. So client code may safely compare deserialized enumeration values with the constants defined in the class by identity (reference equality). On other hand, in Flex after deserialization we end up with several instances of the same enumeration value. Even if all of them have exactly same properties’ values, the references are all different. Because of this you either should not rely on identity equality for “safe-type enumerations” or enforce some strict rules to convert deserialized values to constant values.
Ok, let us start this process over. First, here is Java enumeration we will map to Flex:
enum Priority { LOW, MEDIUM, HIGH }
Next, here are two several Action script classes plus namespace that will simplify our task:
package com.farata.as3.lang {
public namespace as3_lang = “http://www.faratasystems.com/as3/lang”;
}
package com.farata.as3.lang {
import flash.utils.Dictionary;
public class EnumClass {
private var _declaring:Boolean = false;
private var _nextIndex:int = 0;
public var valueMap:Dictionary = new Dictionary;
public var values:Array = [];
private var _elementClass:Class;
public function EnumClass(elementClass:Class):void {
_elementClass = elementClass;
}
internal function get declaring():Boolean { return _declaring; }
internal function get nextIndex():int { return _nextIndex++; }
public function declare(name:String):EnumBase {
_declaring = true;
const result:EnumBase = new _elementClass(name);
valueMap[name] = result;
values.push(result);
_declaring = false;
return result;
}
}
}
The EnumClass serves as meta-class for custom enumerations. It helps to declare specific enumeration constants as well as collect all declared constants in indexed and associative arrays, so we can easily get constant value by name/ordinal in custom subclasses. But most importantly, it enforces singleton rules: any enumeration entry may be created only via EnumClass declare method otherwise run-time error will be thrown. This rule has one exception, but we talk about this a bit later. Instead, let us take a look how this rule is applied in second helper class, EnumBase:
package com.farata.as3.lang {
import flash.utils.IExternalizable;
import flash.utils.IDataOutput;
import flash.utils.IDataInput;
public class EnumBase implements IExternalizable {
private var _ordinal:int;
[Transient]
private var _name:String;
[Transient]
private var _c:EnumClass;
public function EnumBase(C:EnumClass, name:String = null):void {
_c = C;
if (!name) {
_ordinal = -1;
return;
}
if ( !C.declaring )
throw Error(“Illegal attempt to create enum value”);
_ordinal = C.nextIndex;
_name = name;
}
public function get ordinal():int { return _ordinal; }
public function get name():String { return _name; }
final public function writeExternal(output:IDataOutput):void {
output.writeInt(_ordinal);
}
public function readExternal(input:IDataInput):void {
_ordinal = input.readInt();
_name = _c.values[_ordinal].name;
}
as3_lang function intern():EnumBase {
return _c.values[_ordinal];
}
public function equals(o:Object):Boolean {
if ( !(o is EnumBase) ) return false;
if ( this === o) return true;
const other:EnumBase = EnumBase(other);
return other._c === _c && other._ordinal === _ordinal;
}
public function valueOf():Number { return _ordinal; }
public function toString():String { return _name; }
as3_lang static function enumOf(entryClass:Class):EnumClass {
return new EnumClass(entryClass);
}
}
}
EnumBase is the base class for every custom enumeration. It provides necessary enumeration behavior like ordinal/name properties and serialization via flash.utils.IExternalizable mechanism. Please note that enumerations are serialized by ordinal for efficiency, so make sure that both Flex and Java enumeration constants are declared in the same order. Our library does not support any customizations of the serialization protocol on Java side (i.e. only ordinals are restored there), hence the method EnumBase.writeExternal is declared as final.
On other hand, you may need o restore some properties after deserialization on Flex side, so it’s allowed to override EnumBase.readExternal. In this case, the only possible source of information your code may access is a state of corresponding internal constant; please check how the name of enumeration entry is restored in EnumBase.readExternal: first we obtain a static constant with the same ordinal from the values array of EnumClass meta-class, then name property is copied from the constant instance.
To better understand why EnumBase/EnumClass are designed this way let us create a Priority enumeration in Flex:
package sample {
import com.farata.as3.lang.EnumBase;
import com.farata.as3.lang.EnumClass;
import com.farata.as3.lang.as3_lang;
[RemoteClass(alias="sample.Priority")]
public class Priority extends EnumBase {
public function Priority(name:String=null) { super(Self, name); }
public function intern():Priority {
return Priority(super.as3_lang::intern());
}
public static function valueOf(name:String):Priority {
return Self.valueMap[name];
}
private static function _(name:String):Priority {
return Priority( Self.declare(name) );
}
private static const Self:EnumClass = as3_lang::enumOf(Priority);
public static const LOW:Priority = _(“LOW”);
public static const MEDIUM:Priority = _(“MEDIUM”);
public static const HIGH:Priority = _(” HIGH “);
public static const values:Array = Self.values;
}
}
As you probably noticed, Priority class constructor declares the name argument as optional, and EnumBase has special guard condition to exit early when name is null. Again, this is done due to Flex serialization mechanism. During deserialization object constructor is always invoked and this constructor must either have no parameters or all parameters must have default values. By agreement, we don’t allow non-name constants to be declared, so when parameter is null we can assume that this is call done by serialization routine.
The other pair of methods probably contradicts each other, but in fact they both enable 2 options to handle non-unique-by-identity deserialized values. First one is Java-like equals, that lets 2 enumeration constants be compared by content. Second one is intern (named after Java’s String.intern) that returns canonical internal constant value. All internal values may be compared by identity, i.e. using regular equality operator. Notice, that this method is defined in custom namespace, so sub-classes may define own intern method in public namespace with correct return type. The trick is necessary while covariant return types are not allowed in Flex.
Finally, there is an instance valueOf method declared in EnumBase that returns ordinal. It has a quite interesting application. Also ActionScript does not support (yet) operator overloading, it handles specially relation operators (<, <=, >=, >) for custom objects. To perform the comparison, ActionScript gets the result of valueOf call and compares returned values.
The variables of built-in Date type are compared by internally stored time in milliseconds. In certain way, we copied the feature of Java enumerations – they are comparable by ordinal as well. As a neat result, we may execute tests like Priority.LOW <= Priority.HIGH and get the expected results. Flex compiler is smart enough to prevent us from comparing apples to oranges, only objects of same type may be compared, so neither Priority.LOW <= “HIGH” nor Priority.HIGH > Gender.MALE is going to work (assuming that Gender is a different enumeration)
Now we are ready to deploy and test enumeration example with LiveCycle Data Services. The working example can be found here: http://www.myflex.org/articles/fxenum/FlexEnum.html. Use right-click menu on a Flash control to browse and download the relevant Flex sources.
To create your local copy of this example or to enable support of enumerations in your own data services projects please download farata-j5-messaging.jar http://www.myflex.org/articles/downloads/farata-j5-messaging.jar and drop it into WEB-INF/lib folder of your web application with configured LiveCycle Data Services.
Note: Users of previous version of Flex/LiveCycle Data Services (FDS 2.0.1) need different version of this library available at http://www.myflex.org/articles/downloads/farata-j5-messaging-fds.jar.
Then open WEB-INF/flex/service-config.xml file and alter definitions of relevant channels:
<channel-definition id=”my-amf”
class=”mx.messaging.channels.AMFChannel”>
<endpoint
uri=”http://{server.name}:{server.port}/demo/messagebroker/amf”
class=”com.farata.messaging.endpoints.J5AMFEndpoint”/>
<properties>…</properties>
</channel-definition>
<channel-definition id=”my-secure-amf”
class=”mx.messaging.channels.SecureAMFChannel”>
<endpoint
uri=”https://{server.name}:9100/{context.root}/messagebroker/amfsecure”
class=” com.farata.messaging.endpoints.SecureJ5AMFEndpoint “/>
</channel-definition>
In other words, you need just to replace endpoints class(es) to have enumerations support in your remote services. As far as managed data services works over endpoints abstraction, you may use enumerations as properties of your managed objects with any data assembler, even with such complex one as HibernateAssembler.
Now download sample Java sources from http://www.myflex.org/articles/downloads/enum-sample-java.src.zip, build and deploy them to your server. You may download precompiled sample Java application from http://www.myflex.org/articles/downloads/enum-sample-java.src.zip. The sample contains a very simple POJO service that works directly with Priority enumeration and custom data transfer object Task. Obviously, the Task object has Priority as one of its fields.
Afterwards you need to tweak the file WEB-INF/lib/remoting-config.xml and add the destination myService like below:
<destination id=”myService”>
<properties>
<source>sample.MyService</source>
</properties>
</destination>
Finally, you are ready to download and build a sample Flex project (you can download the source code of the project at http://www.myflex.org/articles/downloads/enum-sample-java.src.zip).
Going forward
Draft of EcmaScript 4 also dictates the native support of enum in the future. ActionScipt 3 is compliant with EcmaScript 3 and most likely to add enum support in the next release. In meanwhile, Adobe has released their plans to open source Flex compiler by the end of the year(http://labs.adobe.com/wiki/index.php/Flex:Open_Source). That should allow Flex community to implement many of Java patterns natively in the language. For example, adding enumeration could have been done by adding and processing on compiler level additional annotations similar to [Managed], [Bindable], etc:
package sample {
[Enum values=”LOW,MEDIUM,HIGH” remoteClass="sample.Priority"]
public class Priority { }
}
You can also use available Java code generators like Clear Data Builder to automatically generate ActionScript enumeration classes out of the Java code
Conclusion
As you have seen in this article, adding a new base type and making it serializable is a reasonably simple operation. You can also easily extend the range of the datatypes that go across the wire today. Most importantly, you can use the approach described in this article and provide other custom extensions to AMF3 protocol for any type of the native data.
Valery Silaev
Permalink
Do not miss tomorrow’s live TV show from Times Square on Rich Internet Appilcations. SYS-CON.TV’s will webcast an hour-long “RIA Shoot-Out” covering major Rich Internet Application (RIA) technologies.
Farata’s own Yakov Fain will participate in this discussion. If your firm is considering various tools and techniques for development of your next RIA, this show will definitely help you with making the right decision. This show will feature an interactive Q&A session from viewers during its final segment.
This free event will start at 1PM EST, and you can register at http://web2.sys-con.com/read/375328.htm
Enjoy the show,
Victor
Update: The short (edited) version of the podcast is available at http://tv.sys-con.com/read/385147.htm
Permalink

An Eclipse plugin version of Web reporter ClearBI (a.k.a. FlexBI) is available for public Beta testing. ClearBI is a business intelligence engine that allows software developers automate report generation process, and end users can customize reports (grouping, filtering, export to Microsoft Excel et al.) in Flash Player.
Other than Flash Player, ClearBI does not require any additional software install on the client side. At the time of this writing, ClearBI is the only professional reporting solution on the market of rich Internet applications developed using Adobe Flex and Java.
ClearBI is available in two versions: ClearBI Plugin and ClearBI End-User:
• ClearBI Plugin allows a software developer create and customize a new report in Eclipse IDE. This report can be integrated into any Flex application by including an extra MXML and recompiling the main application. The end users will be able to work with the report (sorting, filtering, grouping, export to Microsoft Excel, et al.), but won’t be able to save this customized report.
• ClearBI End-User has all the functionality of the plugin version, and it also allows the end users create reports from the universe of the data fields without need to install any software other than Flash Player. The end users can create, customize and save reports in the centralized database server without any help from the IT department.
You can download the beta version of ClearBI plugin at www.myflex.org. Create an account and request the trial license for ClearBI. Download the ClearBI User Guide that contains installation instructions. We are actively working on the User Guide and will upload the newer version of this doc every other day.
ClearBI plugin comes with Clear Data Builder (a.k.a. DaoFlex), and you’ll need to download its User Guide as well.
Please send all the comments or bug reports at info at faratasystems.com .We really appreciate your input.
Thank you,
Yakov Fain
Permalink

Up till now, most of the time we’ve been teaching Adobe Flex by invitations from our corporate clients. But since the Flex market really picks up in New York, we decided to run public classes as well to accommodate the needs of smaller businesses that just want to train one or two developers.
Since the blogging genre allows some room for a self promo, here it is.
Our instructors are not those fly by night trainers that would teach you by reading aloud someone’s manual in the classroom. We spend most of our time working on the real-world projects that include Adobe Flex, Java, and a plethora of other technologies. We can offer you Adobe Certified Flex training, where we use original Adobe courseware and labs enriched with live discussions of the real-world issues that developers face daily. Last week, I’ve been teaching a class to a large group of Java developers of a Fortune 100 firm, and in addition to covering the training materials – I’ve spent at least two hours discussing the proper ways of designing their first Java/Flex projects.
We are the ones who write books, and articles. Besides being experts and published authors, our instructors speak at conferences, teach seminars and have been taught programming at such prestigious schools as New York University and Columbia University.
We offer several ways to get you trained in development of the rich Internet applications with Adobe Flex:
1. A typical week of training at your site consists of two Adobe Certified courses:
Flex2: Developing Rich Client Applications (3days) and Flex2: Data Communications (2 Days).
2. Customized Flex training as per your firm’s request. In addition to Flex we can teach a Java class as well.
3. Mixed public training on weekends. In two consecutive weekends (4 days) we’ll deliver Adobe certified class Flex2: Developing Rich Client Applications and one day of custom training discussing the proper ways of starting your Flex/Java project. The next public training will take place in New York City on July 21, 22, 28 and 29 of 2007. Tuition for this course is $1495 USD.
4. One day hands-on Flex boot camps for developers around the USA, and the closest one is scheduled in New York on June 24, 2007.
5. One hour lunch-and-learn on-site session (New York and New Jersey) giving an overview of what’s happening in the rich Internet application arena in general, and how to properly utilize Adobe Flex as a front end to your robust server side application written in other languages.
Please give us a call about all your training needs or fill out the contact form.
Yakov Fain
Permalink

A couple of years ago when my son asked me about the book on programming for kids, I could not find one, and have written my own e-book called Java Programming for Kids, Parents and Grandparents. For some reason computer books targeting teenagers are very rare. There are reader-rabbit kind books for very little kids, but 10-16 years old people do not have much of a technical literature, and 17-18 years old are studying computers using boring adult technical books (the Head First series is a lucky exception).
By the time kids are out of school, they know from their own bad experience that computer science is not an exciting career, which eventually will lead to a “death” of such profession here in the USA.
Adults do not want to admit that kids are smarter than them. They keep saying something like, “My son is not too good at math – he can’t be a programmer”. But most of the programming tasks require only minimal knowledge of arithmetic and algebra skills. To start programming, a kid needs to understand what x = y+2 means. Another important concept is an if-statement. This is pretty much it.
Kids learn much faster than adults, and they do not have “previous programming experience”, which may actually be a good thing, because they do not have to switch from a procedural to object-oriented way of thinking. After learning about inheritance in Java, my son called my wife a super class.
Some people recommend using simple languages to teach people programming – I disagree. Java can be a good first programming language, but you should do it right. That’s why I’ve included lots of color cartoon-like characters that act like a Java-fabric softener.
This e-book was never printed. I’ve got some offers to publish it in black and white because it’s cheaper. I rejected these offers – this book has to be printed in color.
This book was written about three years ago, but it’s about core Java, which did not change that much. I’ve been using Eclipse IDE in the book, but IDE does not really matter – use NetBeans or whatever else you have handy.
You can download the book at this URL. I hope you’ll enjoy the reading and will introduce your kids to an exciting world of programming.
Yakov Fain
Permalink

Next year, Silverlight’s DLR should be able to run programs written in several languages and Smalltalk was not one of them. Today I ran into a very interesting post by a guy who is writing a Smalltalk compiler for DLR and is thinking about porting it to Flash. It’s a great idea. Flash Player 9 is a fast VM that applies JIT compiler to the byte code produced by Flex or ActionScript 3.0 compilers (does Laszlo generates the code for Flash Player 9 yet?). If someone will offer compilers from other languages that can generate the same byte code, Flash Player will be happy to play it for you. I’m not saying that you’d want to create GUI components with Smalltalk, but having an opportunity to link libraries written in other languages to your Flash application sound very useful and logical to me.
Adobe has no choice but to lead such efforts, if they want to successfully compete with Silverlight 1.1 DLR. So I won’t be surprised to hear such announcements during the next MAX conference.
Disclaimer: these are just my speculations, and I do not have have any insiders’ information that there is something in the works at Adobe.
Yakov Fain
Permalink

Last Summer one of my colleagues had to prepare a presentation on Java to a client. When I looked at it, I got goose bumps – his document had the image of Duke in there. I knew that it was illegal – Sun trademarks everything and anything when it comes to Java language wordings and images.
Outsourcing Java meant the end of the jail time for Duke – it’s free now.
Adobe Flex frameworks is open sourced now, and my question is this are we, third-party developers allowed to use the word Flex as a part of the name of our products? For example, next week we are releasing four commercial plugins – DaoFlex, Flex2Ant, Log4Flex, and Flex2Doc, and the FlexBI in a month. None of these names uses the word Flex as is, but rather as a part of the product name. Is this legal? Are we allowed to use the Fx image anywhere in our logos, headers, product screens?
Sun Microsystems published their trademarks document, which is not too easy to understand but at least it’s something. Does Adobe have a similar document regarding the Flex-related trademarks?
I’d appreciate if someone from Adobe legal team could answer my questions using the sample names that I mentioned above…and preferably in English so regular people could understand it too. I’m sure such information would be useful for the entire Flex community.
Thanks,
Yakov Fain
Permalink

When Microsoft renamed WPF/E into Silverlight it was just a re-branding news. But yesterday’s news requires some serious attention. Microsoft has announced SilverLight 1.1 Alpha.
Here’s the quote from asp.net:
“Silverlight is a cross-browser, cross-platform plug-in for delivering the next generation of .NET based media experiences and rich interactive applications for the Web. Silverlight offers a flexible programming model that supports AJAX, VB, C#, Python, Ruby, and integrates with existing Web applications.”
If Silverlight 1.0 Beta was about XAML GUI with the business logic written in JavaScript, now a new runtime called Dynamic Language Runtime will be used for the RIA deployment, and the fun part is that you’ll be able to create these applications with any of the languages mentioned above. This is really breaking news. The new runtime will weigh about 4Mb (Flash Player 9 that holds two VMs weighs 1.2Mb), and expected seamless installation time is under 30 sec (similar to Flash Player 9). JIT is also there.
While Java community is discussing which language features to include in the heavy tank of the future called Java 7 , their main competitor provides support to multiple languages. JVM is a very powerful but underutilized machine, and it’s about time to run more than just tried and true Java there.
Now Adobe has to respond to Microsoft with some secret weapon besides Apollo. If I were running Adobe RIA division, I’d pick up the phone and dialed the number of Jonathan Schwartz.
“Jonathan, what do you think of this crazy idea – let’s see if we can run some trimmed down version of Java in Flash Player 10”.
Yakov Fain
Permalink

Today Adobe has announced that a large portion of the next version of Flex goes open source under Mozilla Public License (MPL). Here’s the partial list of what becomes open: mxml, compc, and ActionScript compiler, command line debugger FDB, Flex framework and RPC libraries and testing infrastructure.
These are some of the components and tools that will not be open sourced: Flex Builder, Charting components, Flash Player, Apollo.
This is a step toward creating a wider Flex 2 market. The interest to rich Internet technologies grows leaps and bounds, and Adobe Flex is one of the leaders in this league. There is already a decent number of developers who are interested in Flex and Adobe hopes that open sourcing Flex will bring more developers on board.
The source code of the Flex framework was available all the time, but the developers could have improved it by extending these components. But now they will be able to improve the original components as well.
Another good thing is that the third-party component developers will be able to include Flex compilers into their components. To the best of my knowledge, MPL will allow third parties distribute their own components under any other licenses as long as the original Flex code stays under MPL.
Next week we’ll start selling our first commercial Flex components and plugins at myflex.org. I’d love to hear an explanations of the MPL licensing from one of the Adobe officials using these components as an example. Does this move really encourages commercial component development by small companies?
The Web tier compiler is a gray area though – it’ll be open sourced for Apache containers and Microsoft IIS.
I was not able to get a clear answer if the third-party developers will be able to include Flex Web compiler into components deployed under commercial J2EE servers. In May, we are releasing our flagship component called FlexBI, which uses Flex Web compiler. Yesterday, we were assuming that it would by our customer’s responsibility to obtain Web tier compiler from Adobe. Will it change with open sourcing Flex? Are we allowed to include the Web tier compiler without worrying about what J2EE server our customer will deploy it under? What do you say, Adobe?
How are you planning to fix the Flex bugs in the new world? Sun Microsystems has so called bug parade for Java. People were able to vote for bugs, and the most “popular bugs” were supposed to be taken care of. This was a failure because some of the most voted bugs were sitting there for 7 years.
What about forking Flex framework? Is this going to be an issue?
One more question. Are we allowed to copy paste a chunk of the Flex source code into our commercial component as long as we keep references to the original author of this piece of code?
The FAQ on open source Flex, is written in Legal language, it would be nice to have an explanation in English with some use cases I’ve mentioned above.
Adobe will still govern the modifications of the Flex libraries – they’ll set up the repositories for the Flex source code, will set up builds, etc.
I believe that open sourcing Flex will draw attention of some serious developers to the new kid on the block. The Flex team may become substantially larger.
Yakov Fain
Permalink

Event-driven programming model offers an excellent architecture based on loosely-coupled components consuming and throwing events. This simply means that a properly designed component knows how to perform some functionality and notifies the outside world by broadcasting one or more custom events. I need to stress, that such component does not send these events to any other component(s). It just broadcast its “exciting news” the event dispatcher. If any other component is interested in processing this event, it must register a listener for this event.
Before explaining how to create an event-driven component let’s state how we are going to use them. This is a typical scenario: MyApplication uses Component1 and Component2. Components do not know about each other. Any event-handling component should define this event inside. For example, Component1 dispatches this custom event sending out an instance of the Event object, which may or may not carry some additional component-specific data. MyApplication handles this custom event and if needed, communicates with Component2 with or without feeding it with data based on the results of the first component event.
We’ll create a “shopping cart” application that will include a main file and two components: the first a large green button, and the second one will be a red TextArea field. These components will be located in two separate directories “controls” and “cart” respectively.
To create our first MXML component in Flex Builder, select the “controls” directory and click on the menus File | New MXML Component. In the popup screen we’ll enter LargeGreenButton as a component name and we’ll pick Button from a dropdown as a base class for our component. Flex Builder will generate the following code:
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Button xmlns:mx=”http://www.adobe.com/2006/mxml“>
</mx:Button>
Next, we’ll make this button large, green and with rounded corners (just to give it a Web 2.0 look). This component will be dispatching an event named greenClickEvent. When? No rocket science here – when someone clicks on the large and green.
Custom event in MXML are annotated within the Metadata tag in order to be visible to MXML. In the listing below, in the metadata tag [Event] we declare a custom event of generic type flash.events.Event. Since the purpose of this component is to notify the sibling objects that someone has clicked on the button, we’ll define the event handler greenClickEventHandler() that will create and dispatch our custom event.
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Button xmlns:mx=”http://www.adobe.com/2006/mxml”
width=”104″ height=”28″ cornerRadius=”10″ fillColors=”[#00ff00, #00B000]”
label=”Add Item” fontSize=”12″ click=”greenClickEventHandler()”>
<mx:Metadata>
[Event(name="addItemEvent", type="flash.events.Event")]
</mx:Metadata>
<mx:Script>
<![CDATA[
private function greenClickEventHandler():void{
trace("Ouch! I got clicked! Let me tell this to the world.");
dispatchEvent(new Event("addItemEvent", true));// bubble to parent
}
]]>
</mx:Script>
</mx:Button>
Listing 1. LargeGreenButton.mxml
Please note, that the LargeGreenButton component has no idea of who will process its addItemEvent. It’s none of its business: loose coupling in action!
In dynamic languages following naming conventions. Common practice while creating custom components is to add the suffix “Event” to each of the custom events you declare, and the suffix ”Handler” to each of the event handler function.
Here’s the application that will use the LargeGreenButton component:
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
xmlns:ctrl=”controls.*” layout=”absolute”>
<ctrl:LargeGreenButton addItemEvent=”greenButtonHandler(event)”/>
<mx:Script>
<![CDATA[
private function greenButtonHandler(event:Event):void{
trace("Someone clicked on the Large Green Button!");
}
]]>
</mx:Script>
</mx:Application>
Listing 2. EventApplication.mxml
We have defined an extra namespace “ctrl” here to make the content of “controls” directory visible to this application. Run this application in the debug mode, and it’ll display the window below. When you click on the green button it will output on the console the following:
Ouch! I got clicked! Let me tell this to the world.
GreenApplication:Someone clicked on the Large Green Button.
While adding attributes to <ctrl:LargeGreenButton>, please note that code hints work, and Flex Builder properly displays the greenClickEvent in the list of available events of new custom component button.

Figure 1. The output of GreenApplication.xmxl
Our next component will be called BlindShoppingCart. This time we’ll create a component in the “cart” directory based on the TextArea.
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:TextArea xmlns:mx=”http://www.adobe.com/2006/mxml”
backgroundColor=”#ff0000″ creationComplete=”init()”>
<mx:Script>
<![CDATA[
private function init():void{
parent.addEventListener("addItemEvent",addItemToCartEventHandler);
}
private function addItemToCartEventHandler(event:Event){
this.text+="Yes! Someone has put some item inside me, but I do not know what it is. \n";
}
]]>
</mx:Script>
</mx:TextArea>
Listing 3. BlindShoppingCart.mxml
Please note, that the BlindShoppingCart component does not expose to the outside world any public properties or methods. It’s a black box. The only way for other components to add something to the cart is by dispatching the addItemEvent event. The next question is how to map this event to the function that will process it. When someone will instantiate the BlindShoppingCart, Flash Player will dispatch the creationComplete event on the component, our code calls the private method init(), which adds an event listener mapping the addItemEvent to the function addItemToCartEventHandler. This function just appends the text “Yes! Someone has put …” to its red TextArea.
The application RedAndGreenApplication uses that uses these two components LargeGreenButton and BlindShoppingCart.
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”vertical”
xmlns:ctrl=”controls.*” xmlns:cart=”cart.*”>
<ctrl:LargeGreenButton addItemEvent=”greenButtonHandler(event)”/>
<cart:BlindShoppingCart width=”350″ height=”150″ fontSize=”14″/>
<mx:Script>
<![CDATA[
private function greenButtonHandler(event:Event):void{
trace("Someone clicked on the Large Green Button!");
}
]]>
</mx:Script>
</mx:Application>
Listing 4. RedAndGreenApplicatoin.mxml
Let’s go through the sequence of its events:
When the green button is clicked, the greenButtonHandler is called and it creates and dispatches the addItemEvent event on itself. The event bubbles to the parent container(s) notifying all listening parties of the event. BlindShoppingCart listens for such event and responds with adding text. Run this application, click on the button, and the window should look as follows:

Figure 2. The output of RedAndGreenApplication.mxml
And one more time: the green button component shoots the event to the outside world without knowing anything about it. That is very different from the case when we would write “glue” code like cart.addEventListener(“click”, applicationResponseMethodDoingSomethingInsideTheCart).
Sending Data Using Custom Events
To make our blind shopping cart more useful, we need to be able not only to fire a custom event, but this event should deliver description of the item that was passed to shopping cart. To do this, we’ll need to create a custom event class with an attribute that will store application-specific data.
This class has to extend flash.events.Event, override its method clone to support event bubbling, and call the constructor of the super class passing the type of the event as a parameter. The ActionScript class below defines a property itemDescription that will store the application-specific data.
package cart {
import flash.events.Event;
public class ItemAddedEvent extends Event {
var itemDescription:String; //an item to be added to the cart
public static const ITEMADDEDEVENT:String =”ItemAddedEvent”;
public function ItemAddedEvent(description:String )
{
super(ITEMADDEDEVENT,true, true); //bubble by default
itemDescription=description;
}
override public function clone():Event{
return new ItemAddedEvent(itemDescription); // bubbling support inside
} }
}
Listing 5. The custom event ItemAddedEvent
The new version of the shopping cart component is called ShoppingCart, and its event handler extracts the itemDescription from the received event and adds it to the text area.
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:TextArea xmlns:mx=”http://www.adobe.com/2006/mxml”
backgroundColor=”#ff0000″ creationComplete=”init()”>
<mx:Script>
<![CDATA[
private function init():void{
parent.addEventListener(ItemAddedEvent.ITEMADDEDEVENT,addItemToCartEventHandler);
}
private function addItemToCartEventHandler(event:ItemAddedEvent){
text+="Yes! Someone has put " + event.itemDescription + "\n";
}
]]>
</mx:Script>
</mx:TextArea>
Listing 6. ShoppingCart.mxml
There is a design pattern called Inversion of Control or Dependency Injection, which means that an object does not ask other objects for required values, but rather assumes that someone will provide the required values from outside. This is also known as a Hollywood principle: ”Don’t call me, I’ll call you”. Our ShoppingCart does exactly this – it waits until some unknown object will trigger event it listens to that will carry item description. Our component knows what to do with it, i.e. display in the red text area, validate against the inventory, send it over to the shipping department, and so on.
Next, we will completely rework our LargeGreenButton class into NewItem component – to include a label and a text field to enter some item description, andthe same old green button:
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:HBox xmlns:mx=”http://www.adobe.com/2006/mxml” >
<mx:Metadata>
[Event(name="addItemEvent", type="flash.events.Event")]
</mx:Metadata>
<mx:Label text=”Item name:”/>
<mx:TextInput id=”enteredItem” width=”300″/>
<mx:Button
width=”104″ height=”28″ cornerRadius=”10″ fillColors=”[#00ff00, #00B000]”
label=”Add Item” fontSize=”12″ click=”greenClickEventHandler()”/>
<mx:Script>
<![CDATA[
import cart.ItemAddedEvent;
private function greenClickEventHandler():void{
trace("Ouch! I got clicked! Let me tell this to the world.");
dispatchEvent(new ItemAddedEvent(enteredItem.text));
}
]]>
</mx:Script>
</mx:HBox>
When we look at our new application with new ShoppingCart and NewItem components, it is almost indistinguishable from the original one. If we would of kept the old class names, we could of used the old application.
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”vertical”
xmlns:ctrl=”controls.*” xmlns:cart=”cart.*”>
<ctrl:NewItem />
<cart:ShoppingCart width=”350″ height=”150″ fontSize=”14″/>
</mx:Application>
Listing 7. RedAndGreenApplication2.mxml
When the user enters the item description and clicks the green one, the application creates a new instance of the ItemAddedEvent, passing the entered item to its constructor, and the ShoppingCart properly properly displays selected ”New Item to Add” on the red carpet.

Figure 3. The output of the RedAndGreenApplication.mxml
Making components loosely bound simplifies development and distribution but comes at higher cost during testing/maintenance times. Depending on delivery timeline, size and lifespan of your application you would have to make a choice between loosely coupled or strongly typed components. One last note. The itemDescription in Listing 2 does not have access level qualifier. It’s so called package level protection. The ShoppingCart can access itemDescription directly, but the classes outside of “cart” package can’t.
Event-driven programming is nothing new – we routinely did it in mid-nineties in such toos as PowerBuilder or Visual Basic. In Java, it also exists as an implementation of Observer/Observable pattern. But entire Flex programming is built on events, which makes coding a lot simplier.
Yakov Fain
Permalink

I met with Jeff Whatcott from Adobe a couple of times, and have to admit that he’s a top-notch professional product manager. He knows how to talk the talk, and I mean it. But let me explain you what I mean. Intelligent Enterprise magazine has published an interview with Jeff on Rich Internet Applications. Of course, Jeff likes Adobe Flex technology for RIA (surprise, surprise).
The question is how do you say it properly? Especially when these journalists are asking questions like what do you think of AJAX, as if they do not understand that you are into Flex and for a good reason. Flex developers really like this product, but I’d split them into three categories based on how they’d answered the question, “What do you think of AJAX”.
Junior programmers and amateurs would simply say “AJAX sucks”. That’s why they are still junior.
Experienced Flex developers would say AJAX sucks because… and they’d give a half a dozen of valid reasons (I put myself into this category).
And the top notch professionals like Jeff, would put it right (no irony is intended here). Let’s read it, enjoy it, and most importantly learn how to talk the talk.
The journalist asks, “How would you compare Flex with alternative routes to RIAs such as Ajax, JavaScript, Active X and Microsoft’s Windows Presentation Foundation?”
This question is wrong for various reasons. First of all, you can not compare AJAX with Flex as the former is a set of techniques for creation of richer Web applications, while the latter is a product of a particular vendor – Adobe in this case.
Also, asking Adobe product manager what he thinks about AJAX or WPF, is like asking me if I like my wife better that Joe Smith’s one.
But Jeff answers the question gracefully. He says, “There are lots of ways to build RIA user experiences, but you have to use the right tool for the job. There’s no one tool that’s right for every solution. Ajax is really great for bringing incremental improvements to existing Web applications. If you have a big Web app and you want to eliminate page refreshes here and there and bring some improvements to the user experience, it’s a great fit because it follows the same [development] model. It’s relatively easy for Web application developers to understand and adopt Ajax for simple things, and that takes you pretty far.”
I’d like to emphasize this statement, “If you have a big Web app and you want to eliminate page refreshes here and there and bring some improvements to the user experience, it’s a great fit”. Absolutely. AJAX is great tool for improving an old application here and there. Three Botox shots around the mouth. What’s that under your left eye? Let me fix it real quick. Ouch!! Done. It’s still Joan Rivers, but hey…I do not mind watching her at the Red Carpet this Sunday. Sure, Melissa looks better…a little.

But let’s get back to Ajax. Jeff continues, “Ajax gets a lot more complicated and more challenging to use when you’re building full-on, large-scale rich Internet applications that are very data intensive and very graphical. A lot of Ajax frameworks are fairly lightweight and not terribly complete“.
Jeff has to be careful, so let me try to interpret this last statement. IMHO, “lightweight and not terribly complete” means scattered widgets and pieces of functionalities that are not even close to solid Flex framework offerings. Opponents of Flex often say that they do not want to commit to a proprietary technology (they refer to Flex). But they do not get it – since writing AJAX application manually is something that even AJAX proponents do not recommend- you’d have to select one of two dozen of immature AJAX frameworks and lock yourself right in this proprietary tool.
And Jeff rightly states so, “Some of the commercial-grade frameworks are more complete, but they’re often incompatible and can’t be mixed and matched. When you pick one, you are really making a long-term commitment as to how your software is going to be built, so it could be a fairly risky decision. Another problem with Ajax is that productivity tends to suffer because of the cross-browser compatibility issues that pop up when you’re dealing with very large-scale applications. It takes time to track down and fix all the bugs. Flex is most powerful in these large-scale, complex development scenarios and it solves all the issues I just mentioned. “
Since I do not work for Adobe, I have a luxury to say that Flex is not a silver bullet either, you still need to write code and deal with non-trivial tasks daily. But it is a good and extensible platform, which can bring your enterprise Web application to a different level.
The next question was, “What about Microsoft Presentation Foundation? “
I do not know what Jeff was thinking about their direct competition, but he gave an open answer without burning any bridges, “That’s an incredibly powerful tool set. It’s really cool stuff and good technology, but it’s still a little early. It’s not yet widely proven in a lot of rollouts, so there may be lurking issues that we don’t know about.”
I consider this interview as a good lesson on interviewing techniques. This does not mean that I will be answering the same way, but I’m taking my hat off to Jeff for his speaking skills. I mean it.
Yakov Fain
P.S. Having said all this, I respect people who are overcoming AJAX challenges on a daily basis. I also respect people who climb Everest.
Permalink

How Fast is Development in Flex?
Ask me what is the easiest way to build RIA apps and you do not have to wait for the answer: it’s Flex, of course. Ask me is it fast to develop in Flex and I will say “it depends”.
First, it depends where are you coming from. Literally. I’ve seen enough places where Struts/HTML is the only known UI technology. Meanwhile the business is running a huge VB app that changed hands 6 times before last developer left during the .com days. Now everyone wants it on the Web, but expectations of the development complexity are distorted by the culture of straw houses.
“Nevermind that legacy Client/Server system took 10 man years to build. We have never done Struts/HTML app in more then 6 months and Flex is a “better HTML” so it should take 3 months in Flex, should it not?”
This rhetorical question brings me to the second point.
What is simple and straightforward in Flex, has been often out of the question, unthinkable in Web 1.0 applications. The paradox, that I call the “Home Depot Effect”, is that once the threshold of “possible” has changed, you want it all. It is easy to put the tiles, it is easy to do the lights, it is easy to build the patio, etc. Does it mean you are going to rebuild that old house in the same time you used to paint your Struts/HTML appartment?
Now you know what I meant by “it depends”.
Victor
Permalink

We are entering an era of Rich Internet Applications (RIA), and many enterprise development managers are facing the dilemma – which way to go – remain with tried and true Java or .Net technologies or less know yet AJAX, Flex, OpenLaszlo or a number of other vendors. This article is an attempt to give a brief overview of what’s out there on the RIA market.
Historically there have been major shifts in the software industry. We moved from mainframes with dumb terminals to client/server. Users gained in convenience and productivity, and mainframe systems were patronizingly labeled as legacy. With the availability of the World Wide Web industry visionaries turned the tables: vendors and corporate IT had been eager to get rid of the complexity of client/server version management and technologists were sold on multi-tier computing. This time client/server was called legacy. Excited with server multi-threading, messaging, persistence, and similar toys, we pretend not to think that, at the end of the day, we’d have to trade user experience and productivity for the transparency of application deployment. And to make us feel better, we proudly called the new breed of applications “thin client.”
Now we are entering an era of RIA, which restores the power of desktop applications…inside downloadable Web page. RIAs run in a virtual machine (i.e., Adobe Flash Player or Java VM) and have the potential of becoming a full-featured desktop application soon. As opposed to just simply displaying Web pages delivered from some server machine, RIA really run on the client. Many of the data manipulation tasks (sorting, grouping, and filtering) are done locally like in the old client/server days. In three or four years most newly developed projects will include RIA technologies.
A rich Internet application combines the benefits of using the Web as a low-cost deployment model with a rich user experience that’s at least as good as today’s desktop applications. And, since RIAs don’t require that the entire page be refreshed to update their data, the response time is much faster and the network load much lower. Think of a globally available client/server application.
Let’s illustrate the difference between “legacy” Web and RIA with a shopping cart example. Non-RIA Web applications are page-based. Since HTTP is a stateless protocol, when the user moves from one page to another, a Web browser doesn’t “remember” the user’s actions on the previous page. As a common treatment of this “amnesia,” a user state is stored on the server side in the form of the HTTP session.
Consider the case of an online shopping session. It can go as follows:
1. The user initiates a search for an item on Web page #1.
2. The server processes this request and returns page #2 that may (or may not) contain the required item.
3. The user adds an item to a shopping cart that takes yet another trip to the server to create the shopping cart and store it on the server side. Then the server responds with page #3 so the user can either continue shopping (repeating the first three steps) or proceed to the checkout – page #4.
At the checkout the server retrieves selected items from the session object and sends page #5 to the user for shipping info. The data entered travels back to the server for storage, and the client gets back page #6 for billing information. After that page #7 will confirm the order and only then goes to the order completion page.
This simplest of online purchases consisted of seven roundtrips to the server. In striking difference to desktop applications, a few-seconds-per-page refresh is considered fast(!) for a typical Web application, and the commonly acceptable delay is up to eight seconds. Is the user motivated enough to complete the purchase? Think again, because your system gave him a chance to reconsider seven times in a row. Now assume that the network and/or server are slow…your potential customer went elsewhere.
Rich Internet applications eliminate the roundtrips and substantially improve system performance by doing a lot more of the processing on the client than a thin client Web application. Besides, RIAs are stateful: they accumulate the information right on the client! To put it simply, RIA isn’t a set of pages controlled by the server; they are actual applications running on the client’s computer and communicating with servers primarily to process and exchange data.
Both consumer-facing and enterprise applications benefit from being RIAs. It’s a well-known fact that e-commerce Web sites such as online ticket reservation systems and online retailers are losing revenues because users abandon shopping carts on non-responsive Web sites during the checkout process. Such Web sites result in lots of calls to the call center, a major operational expense in and of itself. The performance of any system operated by employees is critical to company productivity and RIAs provide a performance boost over HTML applications, while reducing operating and infrastructure costs.
RIA Platforms: The Major Choices
There’s more than one way to create RIAs that run in the client’s browser with the help of some kind of client engine. These are the most popular products or technologies:
- A Java programmer can create Java applets. As mentioned, this solution has been available since 1995.
- Using Adobe Flex you can create an ActionScript application for the ubiquitous Flash Player, a high-performance multimedia virtual machine that runs bytecode files in the SWF format (pronounced swif). The player’s JIT compiler converts the SWF bytecode to native machine code for fast performance. The later facility is specific to Flex 2, available since 2006. Although early versions of Flex were out in 2004, they didn’t support just-in-time compilation.
- Microsoft Windows Presentation Foundation (WPF) was released as part of .NET 3.0 in November of 2006 and can be used to create both Internet and desktop applications (it also has the Everywhere version – WPF/E).
- AJAX, a k a DHTML, born circa 1998. This solution was recently boosted with XMLHttpRequest API support for all major browsers. AJAX served as a wake-up call for the user and developer communities. It is often the first step on the migration path from the legacy Web to the world of RIA despite being seriously handicapped by having to support browser incompatibilities and a poor programming model.
Java
Even though the Java programming language became popular largely because of applets and the famous dancing Duke (http://java.com/en/download/help/testvm.xml ), applets haven’t become Java’s main use pattern. The main reason: the large footprint of the required JVM (currently 16MB). And there are other drawbacks. For instance, although Java Swing pushed a platform-independent look-and-feel, absent any good-looking off-the-shelf GUI widgets it was hard selling it to the public. In this regard Flash and Flex creators did a much better job with their eye-candy components. Or take audio and video integration. Today people are used to having streaming audio and video components embedded in Web pages. But the multimedia Java API remains rudimentary, to say the least.
There are some efforts to minimize the size of the JVM used by Web browsers and the Java Browser Edition project now needs “only” about 3MB to run a primitive Hello World applet. But this can’t compete with Flash Player 9, which managed to accommodate two virtual machines in a 1.2MB download that can run any RIA however complex.
Another issue with Java applets is that they don’t offer a seamless download of the proper version of the JVM along with the applet. Flash Player’s express install does precisely that.
Having said that, I must acknowledge that Java Swing is a very mature and robust technology for creating GUI applications delivered either over the Web or installed on the desktop. You can do literally anything with Java Swing – if you can afford it. No, you don’t pay licensing fees, but because of the longer development cycle and need to engage expert programmers, industrial-size Swing projects are usually quite expensive to build and maintain.
Adobe Flex 2
Flex 2 applications run cross-platform in a ubiquitous Flash Player 9 that’s a lightweight virtual machine. The platform includes:
- an XML-based language called MXML that supports the declarative programming of GUI components targeting designers;
- the standard object-oriented programming language, ActionScript 3.0, based on the latest ECMAScript specification;
- server-side integration via Flex Data Services giving client applications transparent access to the world of J2EE;
- charting components, access to multimedia controls, etc;
- and an Eclipse-based full-featured IDE with automated deployment, debugging, and tracing facilities.
The Flex 2 platform is easily extendable and integrates well with server-side Java, ColdFusion, PHP, Ruby, ASP, and the like.The SWF file format is open, and there are third-party open source products that offer tools for creating RIAs delivered by Flash Player like OpenLaszlo from Laszlo Systems. This is what comes at no cost with Flex 2:
- MXML – an XML-based declarative programming language for creating GUI.
- ActionScript 3.0 – an object-oriented language similar to Java.
- Flash Player 9 – a virtual machine with a tiny footprint that lives inside a Web browser and runs your compiled bytecode (.SWF).
- Command-line compilers and debugger.
- Flex Framework, which includes a library of well-designed GUI component: buttons, tab folders, data grids, tree controls, animated effects, and more.
- Flex Data Services Express (FDS) – a template Web application deployed in a J2EE server to communicate with ActionScript client application run by Flash Player. FDS Express is limited to a single CPU, which makes it useful only for learning purposes.
The following Flex tools require a purchased license:
- Flex Builder – the Eclipse-based IDE
- Charting component
- Flex Data Services Departmental, 24×7, 100 concurrent users
- Flex Data Services Enterprise, 24×7, unlimited users
In a nutshell, the process of creating a basic Flex 2 application consists of the following steps:
1. Design application by adding MXML components like this button:
<mx:Button label=”Place Order” click=”processOrder(event)”/>
If you use Flex Builder IDE, you can apply drag-and-drop techniques. Alternatively, you can write the MXML as text.
2. Write the code in ActionScript per your functional specification, for example:
private function processOrder (event:Event):void{
//The business logic goes here
}
3. Compile the code: The Flex compiler automatically converts MXML into ActionScript and creates bytecode output in a form of an SWF file to be run in Flash Player 9 or above. You’ll enjoy a fully automatic compilation process if you use the Flex Builder IDE.
4. Deploy the SWF file and the wrapping HTML page in the Web server of your choice. The deployment process and creating the wrapped can be completely transparent if you use the Flex Builder IDE.
More advanced Flex applications can include interaction with the server-side systems through FDS, which provides remote access to server-side Java objects and Java EE components, extensive messaging support (including JMS integration), synchronization with persisted data, and integration with other persistent technologies.
WPF
Recently released Microsoft’s Windows Foundation Platform, or WPF uses an XML-based declarative programming language called XAML to create GUIs and C# as a general-purpose programming language. WPF is suitable for creating both RIA and desktop applications. XBAP stands for XAML Browser Application and it’s a WPF way of creating RIAs that runs in Internet Explorer.
Microsoft has released a Beta version called WPF/E that will run on some non-Windows platforms (this version uses substitutes C# with JavaScript). While living in a sandbox, XBAP will have access to all .NET 3.0 functionality but WPF/E won’t. Common Language Runtime (CLR) is the client’s WPF engine.
To create WPF applications, developers can use Microsoft’s Visual Studio 2005 IDE with installed .NET 3.0 extensions. The next version of this IDE, called Orcas, will include a visual GUI designer. WPF developers use the same code base for writing XBAP and desktop applications: they just enclose the code sections that aren’t allowed in XBAP into the ifdef blocks.
Microsoft XAML code looks similar to Adobe’s MXML. Even though today’s Flex 2 is a lot more mature than WPF, Microsoft has an established developer base, while Adobe traditionally catered to designers, and its main goal today is to convince enterprise developers (particularly the Java camp) that Flex can be a tool of choice for creating business RIAs.
AJAX
While the term AJAX was coined by Jesse James Garret in February of 2005 and is partly rooted in the asynchronous XmlHttpRequest implemented by Mozilla, lots of developers have used Microsoft’s version of XMLHttpRequest and alternative techniques like IFrame since 1999. These techniques facilitate synchronous and asynchronous communications between the script in a page and server-side code. The main problem with AJAX is that despite its popularity it has no technical foundation. While the other solutions we mention here are based on rock-solid virtual machines, there’s no standard VM for AJAX. Each browser implements AJAX building blocks differently. There’s a chance that deployed AJAX application will require code changes with each new browser release. Wait, let’s rephrase that: there’s a chance that a deployed AJAX apps may run as is on a new browser release. Do you want to take chances with your business?
That said, Internet giants like Google, Yahoo, and Amazon are building AJAX apps on top of their own abstraction layers such as Google Web Toolkit (GWT). Because of the immature level of the technology, these abstract layers need constant vendor attention as soon as changes appear.
AJAX Shortcomings
An ability to create flicker-free Web apps without buying more software is AJAX’s big appeal. You may have heard the chant “AJAX is free.” Here’s the simple translation: no commercial AJAX tool is worth paying for. There are hundreds of libraries, toolkits, and control sets that give you the impression that AJAX applications are cheap to develop and strategically safe since there’s no vendor lock-in. Actually, there is vendor locking because you won’t manually write JavaScript code and will have to pick an AJAX library of some vendor. Now think about it: starting from the ground up you need a communication layer, messaging and remoting mechanisms, an HTTP sniffer, a library of UI components with shared objects and event models, a visual IDE that understands these components in design time, and a debugger that accommodates all this stuff. On top of that, there’s internationalization support, accessibility for the disabled, and support for automated testing tools.
You really think you’re safe with mix-and-match from different vendors? If the answer is yes, you must be working for a software company in the RIA business. Coming to reality, long development cycle, lack of free quality GUI components, and the shortcomings listed below make AJAX less appealing and, actually, the most expensive way of creating RIAs.
These are some of AJAX’s current drawbacks:
JavaScript development tools are limited due to the dynamic nature of the language, and debugging any DHTML/JavaScript mix is a pain. Yes, Google’s GWT can spare you from writing JavaScript manually, but at the end of the day, it’s still JavaScript that has to be deployed in production. When the system isn’t working and time is limited, what are you going to use to debug it – the real page of Java mock-up?
Tons of JavaScript source code has to go over the wire to the client to be interpreted by the browser. We’re talking about business applications, not some proof-of-concept demo.
Web browsers will happily display your application even if a piece of JavaScript didn’t arrive at the client. You won’t know of a problem exists until you execute the particular use case.
A simple right-click followed by the “View Source code” menu option would reveal your business application code. Better yet, all this code resides as plain text in the browser cache on disk. Because of this, you have to drop all the code comments and use obfuscators to protect your code from being stolen.
HTML rendering is slow: think of a data grid that contains 5,000 records. How long are you ready to wait for your sales report?
Any data manipulation by JavaScript is inherently slow because JavaScript is an interpreted, not a compiled language. We’re talking thousand of times slow.
The code is more vulnerable to hacker attack, a fact that was proved recently by a worm that stole a bunch of mail addresses from Yahoo address books.
AJAX doesn’t support server push. The server-side application can’t publish the data directly to the client. AJAX applications have to poll the data from the server at specified time intervals without knowing if the data is there or not.
It’s not easy to find good AJAX programmers.
To summarize, if you’re developing a new enterprise business RIA from scratch, AJAX may not be the way to go. Choose a solid application development environment that offers a virtual machine at runtime like Flex/Flash, Java, or WPF. Any of these environments is more productive than AJAX. If you already have AJAX applications you can nicely integrate new Flex RIAs in existing AJAX applications using tools like FABridge from Adobe for communicating between AJAX and Flex.
During AJAX’s first year of life, every article or book on the subject mentioned Google Maps and Gmail, and various type-ahead samples: you enter the first zip code digit in a text field, and it suggests your possible choices based on your input without a page refresh. Today, you can read about a number of AJAX applications, including ones that work with photo images loaded from the popular flickr.com Web site.
Lastly, I’d like to make it clear that popular comparisons of Flex versus AJAX are simply wrong, since Flex is a framework and complete development platform, while AJAX is a set of techniques. To compare apples to apples, you should compare products like Flex against GWT (Google) and the like.
Other RIA Solutions
OpenLaszlo
OpenLaszlo from Laszlo Systems is an open source product that lets you create applications that can be deployed as DHTML or Flash Player files. The ability to generate DHTML code made it a good candidate for developing applications for mobile devices, and Sun Microsystems has recently partnered with Laszlo Systems to bring this technology to the Java mobile space. This is direct competition for Adobe Flash Lite.
GWT
GWT stands for Google Web Toolkit lets you write programs in Java and convert them to JavaScript so they can be delivered as AJAX Web applications.
An interesting GWT feature is that it compiles Java into various versions of JavaScript to accommodate the specific needs of different Web browsers. GWT comes with a library of extensible components. The number of these components was limited, but that will probably change soon, because it’s Google.
NexaWeb
NexaWeb offers a Java-based thin client that doesn’t require any additional installation on the user’s desktop. The application’s state is controlled by a small Java applet running on the client. This applet communicates with the NexaWeb Java EE application as needed. To avoid issues related to the version of the Java Runtime Environment installed with the Web browser, NexaWeb uses JRE 1.1 for its applet.
Some Pragmatic Flex/Java Considerations
Cool technologies come and go. Only some of them settle down in the toolbox of a professional programmer working on enterprise business applications. The technical excellence of any software is important, but it’s not the only component in its success.
The Learning Curve: Reuse of Skills and Code
One important concern of any development manager is the availability of a large pool of people who know a particular software. There are plenty of Java programmers with the skills required to develop Web applications, and the good news is that enterprise Java developers with servlet/Java EE programming skills or Java Swing experience will find the Flex path very easy.
Java and ActionScript 3 are very similar; Eclipse is a familiar environment for many Java developers. Since Flex piggybacks on Java EE and browser technologies, a server-side Java programmer should be able to correlate his current skills with the development process in Flex. Java Swing developers will instantly spot similarities to Java event and layout models. In our experience, the typical ramp-up time for motivated Java developer is two weeks. The best part is that Flex seamlessly integrates with existing Java server code of any flavor – POJO, EJB, Hibernate/Spring, or JMS, so the server-side part can literally remain unchanged.
Application Security
Another important consideration is the security of Flex/Java applications. Flex server-side security management is quite extensive, and it lets you use either container offerings or custom security providers via declarative XML binding. There are a couple of challenges since Flex supports multiple protocols, so Java EE security that relies only on HTTP sessions has to be extended, but it’s a simple and well-documented process. On the client side, it builds on Flash Player security that’s known for its lack of serious security flaws. You have a built-in security manager that has all the standard protection for cross-domain and zone access. Corporations can further restrict the code they get from third parties by wrapping the code loaders in additional security managers.
Flex GUI Performance
Java Swing is a tried and true tool for developing responsive GUIs in demanding applications like stock trading and online auctions. Flex is capable of providing near-real-time data rendering to the GUI and very high refresh rates on large data sets. Flash Player 9 is the high-performance modern virtual machine with precompiled optimized code and a just-in-time (JIT) machine code compiler.
Shorter Development Cycle
It’s very possible to build the client side of a real-time portfolio display integrated with news feeds and graphs in about 200 lines of Flex 2 code. A similar Swing program (even if it’s created with commercial IDEs) would be several times larger.
A decent Flex developer should be able to prototype (short of server processing) most of the UI for a specific trading system by the end of the first week. If you’re lucky and system integration went okay, you can add the collaboration features and multimedia – with the total client code base for the whole project coming within 1,000-1,500 lines. This is definitely not possible with Swing. Of course, some people will say modern Java IDEs generate lots of boilerplate code automatically, but this is still the code that someone has to read, understand, and fix if needs be.
Having said all this, there is a big difference between an application prototyping and delivering a final product – you still need to write code, create new components extend ActionScript classes and implement interfaces. Flex is not a magic wand.
Flex: Room for Improvement
While many programmers who dealt with previous versions of Flex are really happy now that they have a professional Eclipse-based IDE, Java programmers are spoiled by the variety of excellent and responsive IDEs. Flex Builder helps a lot in writing Flex code, but it’s not as Flex Builder helps a lot in writing Flex code, but it’s not as sofisticated and elegant as it could have been. It’s even not as good as its daddy Eclipse.
While you can use Flex just to connect to your existing applications written as JSP or any other HTTP-compatible technologies, you’ll get performance gain if you’ll use Flex remoting and messaging that is build on fast Adobe proprietary protocols called AMF3 and Real Time Messaging Protocol (RTMP). To take advantage of these benefits you have to purchase Flex Data Services licenses, while may not be affordable for small businesses.
Connection Management
Flex provides an extensive infrastructure for managing connections between the Web browser and the server. It lets you specify all the protocol details for the RTMP, HTTP, HTTPS as well as plain socket connections. You can then specify the order in which the protocols should be tried due to availability/firewall issues. You also get alternative real-time push or pull connections on additional protocols, a direct socket API, and tons of low-level hooks that let you build any protocol you want.
Flex and Agile Development
In mid-‘90s PowerBuilder and Visual Basic were the tools of choice in the client/server field. Software developers didn’t really worry about what was under the hood, but more importantly, they were business users’ best friends. They could do stuff quickly, or using the modern jargon, they were agile programmers without even knowing it. They’d ask the business user Joe, “How do you usually do your business? What would you like to have on this screen? Describe the steps of your business process.” Most likely Joe wouldn’t know all the answers, but this was okay, because developers could come back to the user the next day with a working prototype. This was easy with PowerBuilder’s DataWindow. When Joe-the-user saw the prototype, his glassy look all of a sudden would become friendly and understanding. Now Joe was back in control: “No, you did this part wrong, I wanted it different.” No problem, developers would return with the changes the next day (not next month, but the next day!).
Developers didn’t really know how DataWindow worked, but they trusted this component. PowerBuilder used event-driven programming model, which was clean and simple. Object A triggers event XYZ on object B, and this event can carry a payload – the data that object B needs to operate. Using modern jargon it’s called Inversion of Control or Dependency Injection design pattern. What’s important is that the object B doesn’t know about object A. On the same note, if object B needs to return the result of some internal function back, it would broadcast this result “to whom it may concern” by triggering one of its own events. This is loose coupling in action.
The mentality of many Java programmers was different. They’d assign lower priority to the user’s windows and spend most of their time designing a multi-tier system that didn’t depend on any specific look-and-feel and could be universal. Meetings with Joe would be rare because they couldn’t create a decent prototype fast. Fancy IDEs with GUI designers like Matisse weren’t in the picture yet and, more importantly, Java programmers were thinking big: UML, design patterns, application servers, and clustering. They enjoyed the programming process for itself. They didn’t like the mindset of old-fashioned PowerBuilder or Visual Basic programmers who were thinking windows and screens.
With Flex you started to care about the business users again. You can change the prototype twice a day, and Joe can do the same with his business requirements. No pile of project documentation is needed. The napkin is back and it works. Flex architects can give the server-side Java team the final okay only after Joe is 100% happy.
Besides, with Flex we can have the best of both worlds: the source code of the Flex framework is available, we can learn how it works inside, and override some functionality with what suits our needs better.
Working with Flex promotes agile development, where the people we build the software for are the driving force. Agile development methodology suggests minimizing each development cycle to mitigate the risk of delivering something to the users that they don’t want. Agile development encourages frequent face-to-face meetings with the end users as opposed to preparing and sending documents back and forth.
Summary
This quick overview of major RIA-enabling technologies and various approaches to making Web applications richer. It’s by no means a complete list: new commercial and open source RIA frameworks and components arise every day. Regardless of what RIA tools you are going to select, start your evaluations now to get a competitive edge.
Yakov Fain
Permalink

Software engineers of Farata Systems present on several conferences every year during which they enjoy learning from others and share their accomplishments. Below are our confirmed presentations for the Spring of 2007.
1. EclipseCon 2007, March 5-8, San Jose, CA.
Anatole Tartakovsky will present on Rapid Application Development of Rich Internet Applications with Eclipse plugins.
2. Flex 360, March 5-7, Santa Clara, CA.
Anatole Tartakovsky will present on Using Flex for Business Intelligence and will demo a number of Flex Builder plugins.
3. AJAXWorld 2007, March 18, New York, NY.
Yakov Fain and Victor Rasputnis will run a one-day hands-on Flex bootcamp. During this event we’ll be also paticipate in a book signing event for our new book on RIA Development with Adobe Flex and Java .
4. SOAWorld Conference, June 25-27, New York, NY.
Yakov Fain will present on “SOA, RIA and the Human Factor“.
Please feel free to contact us either before, or during the conference for any formal or informal disscussions.
Thanks,
Yakov Fain
Permalink

This year started with a surge of requests to work on Flex projects. We need to grow – we are looking for Flex developers to work on various projects. Our small company has very good reputation on Wall Street, and to maintain this status we always cherry pick people we work with. We are looking for seasoned developers. We need people who are motivated to work and master Flex.
Our requirements are pretty reasonable: you have to be smart, know how to survive in a corporate environment, deliver on time and what’s expected, and require very little supervision. Beside working knowledge of Flex 2 you should have experience developing applications using J2EE.
We can work with you either on the corp-to-corp basis, or offer full time employment. Please send your resume and salary/rate requirements at info at faratasystems dot com.
While we do not hire junior developers at this time, we will open a limited number of internship positions to talented students for the Summer of 2007. We hope that some of these interns will eventually start working for Farata Systems. Please get in touch with us early describing why you are a good candidate for being an intern. If does not matter where you live – you will telecommute – but good English and passion about developing rich Internet applications is a must.
Thank you,
Yakov Fain
Permalink

Several years ago I wrote an article on using abstract classses and interfaces in Java . Back than I was absolutely sure that writing object-oriented code is a must. These days, I’m using yet another language called ActionScript 3 (AS3), which supports all OOP paraphenalia plus has provisions for dynamic data types. This article illustrates my up to date vision of OOP with and without interfaces. OK, let’s go.
You know the drill: a language is called object-oriented if it supports inheritance, encapsulation and polymorphism. The first two notions can be easily defined:
• Inheritance allows you to design a class by deriving it from an existing one. This feature allows you to reuse existing code without doing copy and paste. AS3 provides the keyword extends for declaring class inheritance, for example:
package com.theriabook.oop{
public class Person {
var name:String;
}
}
package com.theriabook.oop{
public class Consultant extends Person{
var dailyRate:Number;
}
}
package com.theriabook.oop{
public class Employee extends Person{
var salary:Number;
}
}
Listing 1. The ancestor and two descendents
• Encapsulation is an ability to hide and protect data. AS3 has access level qualifiers such as public, private, protected and internal to control the access class variables and methods. In addition to a Java-like public, private, protected and package access levels, in AS3 you can also create namespaces that will give you yet another way of controlling access to properties and methods. However, if Java enforces object-oriented style of programming, this is not the case with AS3, because it’s based on the scripting language standard. Object-oriented purists may not like the next code snippet, but this is how HelloWorld program may look in AS3:
trace(“Hello, world”);
That’s it. No class declaration is required for such a simple program, and the debug function trace() can live its own class-independent life, as opposed to Java’s println() doubly-wrapped in the classes System and PrintStream. You can write your own functions, attach them to dynamic objects and pass them as parameters to other functions. AS3 supports regular inheritance chain as well as so-called prototype inheritance when you can add new properties to the class definitions, and they will be available to all instances of this class. Moreover, you can disable validation of the properties and methods during compilation by turning off “strict” mode. In Java, behind every object instance there is an entity of type Class. This is not an object itself, but it’s placed in memory by class loaders.
Program Design with Interfaces and Polymorphism
As in Java, AS3 interfaces are special entities that define the behavior (methods) that can be implemented by classes using the keyword implement. After explaining crucial for OOP interfaces, we’ll discuss how to write generic code even without their.
To illustrate how you can design AS3 programs with interfaces, let’s work on the following assignment:
A company has employees and consultants. Design classes to represent people working in this company. The classes may have the following methods: changeAddress, giveDayOff, increasePay. Promotion can mean giving one day off and raising the salary by a specified percentage. For employees, the method increasePay should raise the yearly salary and, for consultants, it should increase their hourly rate.
First, we’ll add all common methods that are applicable to both employees and consultants to the class Person.
package com.theriabook.oop {
public class Person {
var name:String;
public function changeAddress(address: String): String {
return “New address is” + address;
}
private function giveDayOff(): String {
return “Class Person: Giving an extra a day off”;
}
}
}
Listing 2. The Ancestor class: Person
In the next step, we’ll add a new behavior that can be reused by multiple classes: an ability to increase the amount of a person’s paycheck. Let’s define an interface Payable:
package com.theriabook.oop
{
public interface Payable
{
function increasePay(percent:Number): String;
}
}
Listing 3. Interface Payable
More than one class can implement this interface:
package com.theriabook.oop
{
public class Employee extends Person implements Payable
{
public function increasePay(percent:Number):String {
// Employee-specific code goes here …
return “Class Employee:Increasing the salary by “+ percent + “%\n”;
}
}
}
Listing 4. AS3 class Employee implementing Payable interface
package com.theriabook.oop
{
public class Consultant extends Person implements Payable {
public function increasePay(percent:Number): String{
// Consultant-specific code goes here …
return “Class Consultant: Increasing the hourly rate by ” + percent + “%\n”;
}
}
}
Listing 5. Class Consultant implementing Payable
When the class Consultant declares that it implements interface Payable, it “promises” to provide implementation for all methods declared in this interface – in our case it’s just one method increasePay(). Why is it so important that the class will “keep the promise” and implement all interface’s methods? An interface is a description of some behavior(s). In our case the behavior Payable means existence of a method with the signature
boolean increasePay(int percent).
If any other class knows that Employee implements Payable, it can safely call any method declared in the Payable interface (see the interface example in class Promoter).
In Java, besides method declarations, interfaces can contain final static variables, but AS3 does not allow in interfaces anything but method declarations.
Interfaces is yet another workaround for the absence of multiple inheritance. A class can’t have two independent ancestors, but it can implement multiple interfaces, it just needs to implement all methods declared in all interfaces. One of the way to implement multiple ingeritance (we often use but do not recommend – use at your own risk) is to use “include” statement with complete implementation in all classes implementing interface:
public class Consultant extends Person implements Payable {
include “payableImplementation.as”
}
public class Employee extends Person implements Payable {
include “payableImplementation.as”
}
For example, a class Consultant can be defined as follows:
class Consultant extends Person
implements Payable, Sueable {…}
But if a program such as Promoter.mxml (see below) is interested only in Payable functions, it can cast the object only to those interfaces it intends to use, for example:
var emp:Employee = new Employee();
var con:Consultant = new Consultant();
var person1:Payable = emp as Payable;
var person2:Payable = con as Payable;
Now we’ll write a MXML program Promoter, which will use classes Employee and Consultant defined in the Listing 4 and 5. On the button click it’ll create an array with a mix of employees and consultants, iterate through this array and cast it to Payable interface, and then call the method increasePay() on each object in this collection.
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”>
<mx:Label y=”10″ text=”Inheritance, Interfaces and Polymorphysm” width=”398″ height=”35″ fontWeight=”bold” horizontalCenter=”-16″ fontSize=”16″/>
<mx:Button x=”93″ y=”66″ label=”Increase Pay” width=”172″ fontSize=”16″ click=”startPromoter()” id=”starter”/>
<mx:TextArea x=”26″ y=”114″ width=”312″ height=”133″ id=”output” wordWrap=”true” editable=”false” borderStyle=”inset”/>
<mx:Script>
<![CDATA[
import com.theriabook.oop.*;
function startPromoter():void{
output.text="Starting global promotions...\n";
var workers:Array = new Array();
workers.push(new Employee());
workers.push(new Consultant());
workers.push(new Employee());
workers.push(new Employee());
for(var i: int = 0; i < workers.length; i++) {
// Raise the compensation of every worker using Payable
// interface
var p: Payable = workers[i] as Payable;
output.text+= p.increasePay(5);
//p.giveDayOff(); would not work. Payable does not know
// about this function
}
output.text+=”Finished global promotions…”;
}
]]>
</mx:Script>
</mx:Application>
Listing 6. Promoter.mxml
The output of this program will look as follows:

The line p.increasePay(5); in the listing above may look a little confusing: how can we call a concrete method increasePay on a variable of an interface type? Actually we call a method on a concrete instance of the Employee or a Consultant object, but by casting this instance to the type Payable we are just letting the AVM know that we are only interested in methods which were declared in this particular interface.
• Polymorphism – when you look at our Promoter from Listing 6, it looks like it calls the same method increasePay() on different types of objects, and it generates different output for each type. This is an example of polymorphic behavior.
In the real world, array workers would be populated from some external data source. For example, a program could get the person’s work status from the database and instantiate an appropriate concrete class. The loop in Promoter.mxml will remain the same even if we’ll add some other types of workers inherited from the class Person! For example, to add a new category of a worker – a foreign contractor, we’ll have to create a class ForeignContractor that implement the method increasePays and might be derived from the class Person. Our Promoter will keep casting all these objects to the type Payable during the run-time and call the method increasePay of the current object from the array.
Polymorphism allows you to avoid using switch or if statements with the type checking operator is. Below is a bad (non-polymorphic) alternative to our loop from Promoter.mxml that checks the type of the object and calls type-specific methods increaseSalary() and increaseRate() (assuming that these methods were defined):
for(var i: int = 0; i < workers.length; i++) {
var p: Person = workers[i] as Person;
if (p is Employee){
increaseSalary(5);
} else if (p is Consultant) {
increaseRate(5);
}
}
Listing 7. A bad practice example
You’d need to modify the code above each time you add a new worker type.
Polymorphism without interfaces
If this would be a Java article, I could have patted myself on the back for providing a decent example of polymorphism. But I’d like to step into a little bit dangerous territory: let’s think of a more generic approach – do we even need to use interfaces to ensure that a particular object instance has a required function like increasePay? Of course not. Java has a powerful introspection and reflection mechanism, which allows to analyze which methods exist in the class in question. It’s important to remember though, that in Java object instances have only those methods that were defined in their classes (blueprints). This is not the case with AS3.
There is yet another urban myth that reflection is slow, and you should use it only if you have to. But this consideration is not valid for programs that run on the client’s PCs, because we do not have to worry about hundreds of threads competing for a slice of time of the same server’s CPU(s). Using reflection on the client is fine. Even on the server, a proper combining of reflection with caching allows avoiding any performance penalties.
AS3 provides very short and elegant syntax for introspection, and we’d like to spend some time illustrating polymorphism without typecasting and strict Java-style coding.
Let’s re-visit our sample application. Workers have pay and benefits and vacations, consultants have hourly pay. But retirees may have some other forms of receiving pension, board of directors might have pay with no benefits – are they workers? No they are not, and their objects may not necessarily implement Payable interface, which means that the typecasting from Listing 6 would cause a run-time exception.
How about raising the compensation of every Person even if it does not implement Payable? If one of these objects will sneak into the array of workers, simple casting to Payable show below will throw an exception
Payable p = Payable(workers[i]);
Let’s re-write the loop from Listing 6 as follows:
for(var i:uint = 0; i < workers.length; i++) {
var p:* = workers[i]["increasePay"];
output.text+=p==undefined?”no luck”:p(5);
}
This short loop deserves explanations. First, we’ve declared a variable p of type *. Using an asterisk a bit more open than var p:Object; as it allows the variable p to have a special value of type undefined, which is used in the above code sample.
Let’s dissect the following line:
var p:* = worker[i]["increasePay"];
It means, “Get a reference to the function increasePay() from the array element workers[i]. You may ask, why do you use brackets around the increasePay instead of the dot notation? The reason being that dot notation would ask the compiler to find and validate this function, while the brackets tell compiler not to worry about it: the program will take care of this little something inside the brackets during the runtime.
Basically, this single line above performs the introspection and gets a pointer to the function increasePay for the future execution in the next line:
output.text+=p ==undefined?”no luck":p(5);
If this particular element of the workers array does not have increasePay defined (its class must be declared as dynamic), add “no luck” to the text field, otherwise execute this object’s version of increasePay passing the number five as its argument. The line above still has a potential problem if the class does not have the function increasePay, but has a property with the same name. The bulletproof version looks like this:
output.text+=!(p is Function)?"no luck":p(6);
Let’s emphasize again: this method increasePay does not have be defined in any interface.
Java programmers would call this a wild anarchy. Of course, adhering to strict rules and contracts in Java leads to more predictable code and less surprises during the run-time. But modern Java moves toward dynamic scripting, added implicit typecasting, run-time exceptions, etc. Overuse of interfaces, private, protected and other “nice and clean object-oriented techniques” does not promote creative thinking of software developers. By the way, protected variables is another weird thing in OOP.
Summary
Now raise your hand if you are a Java programmer and after reading this article you are thinking to yourself, “Hmm, may be ActionScript 3 is not too bad and I should take a look at it ?”.
Now, stand up if you are thinking, “Java rules, the rest of programming languages sucks”.
ActionScript 2 programmers can remain seated, but might want to reconsider the way they program.
Yours truly,
Yakov Fain
Permalink

For Farata Systems the year 2007 started with a surge of requests for working on new Flex projects, which was expected, but a number of requests fall under umbrella “Save our project“. For consulting firms, it may sound good, because any repair job is more expensive than creation of the product from scratch. But it may also represent a bad trend – some enterprise development managers will fall into the same trap – the project should go to production in a month, but it’s not in a good shape. Let’s see what happened.
Adobe markets Flex as a RAD tool. The main threads of most of their Flex presentations is how to develop a working application under ten minutes or so. But seasoned enterprise developers understand that there is big difference between a short demo and development of a real world application, which most likely is more complex that reading an XML feed into a plain data grid. But what if your organization does not have seasoned Flex developers? What if you did not have a say during the budget planning? What if your project plan was painted in large brush strokes? It does not take a rocket scientist to figure out that you might not meet your deadlines, which were set by some “bad executive”.
If you’ve been around in the industry for a while, you may remember that the forth generation client server tools like SQL Windows (Gupta) and PowerBuilder were the hottest tools on the market about fifteen year ago. Back than, if you knew how to disable a Button and how to write an SQL join (Hibernate was not invented yet), you’d get a job in no time. Then, you’d learn on the go. This was a Client-Server Wild West. Now we are entering the RIA golden rush. This is great, but do not expect Flex to be a silver bullet. It’s a great tool, but you’ll have to deal with same old issues like performance, application size, custom data renderers, dealing with J2EE components, and more.
That’s why we, and I’m sure many other Flex consultancies started to hear S.O.P. (Save Our Project) signals. Flex is a great tool but do not get overly excited, invest some serious money in training of your developers, and carefully plan your transition to the great RIA world, where every serious enterprise is moving.
Yakov Fain
Permalink

It started as a simple task – I needed to store user preferences. No problem SharedObject.getLocal() will do the job. Oh, by the way, we do not want to store the preferences on the local disk because users want to be able to switch workstations. SharedObject.getRemote()? No good. Who’s going to let you store the data on the server’s machine? And even if they will, how are you going to organize multi-user complex preferences?
Using DBMS is a no-brainer. I’ll create a two-column table – userID and something with properties. What something? An object as a blob. What type of object? Hmm. How about ByteArray? Rolling up the sleeves.
Before we proceed, let me remind you I spend many years doing pure object-oriented programming in Java. You’ll see why it’s important in a little bit.
There is a lots of various user preferences to remember. For example, which is a default tab in TabNavigator, which columns should be visible in a datagrid and more. Here’s what goues through my mind, “For simple preferences I’ll just use Strings and Numbers, and more complex ones I’ll put in a collection with key-value pairs. Then, I’ll create the object UserPrefs, add all the preferences to it, convert it into a ByteArray and will store it either in the SharedObject.data or send it over to a POJO for storage in the DBMS”. Sounds good? Boy, I was wrong…
It started with the fact that I decided to use ActionScript 3 Dictionary class. When I opened the language reference, I was surprised by several things:
a) The class Dictionary is inherited right from the Object and has only a couple of extra methods there. To iterate the dictionary, I was looking for a property length or something to know how many elements are there in my collection. Nope, there is not such thing there. Now it’s getting clearer how Flash Player’s VM is so light comparing to JVM. No big deal. Will loop through the collection while it has some elements.
b) The fun began when I started adding my collections to the UserPrefs object trying serialize them into the ByteArray for storing in the SharedObject. When the user will start my application, I’ll de-serialize it using ByteArray.readObject(). Oopsie…Class deserialization is not supported in ActionScript 3. Need to recreate collections manually. But what if I’ll have collections inside collections?
Anyway, finally I got it to work…while debugging in Flash Player. The regular run-time kept giving me some errors…
My colleague Anatole suggested, “Forget about Dictionary. In this case you can live with a simple Object, but use dynamic typing, and Flash will do deep copying”. I followed his advice, the program became simpler, I got rid of my UserPref class and it works like a charm. The following sample creates some hardcoded preferences for illustration purposes, converts them to byte array, saves them, and the on a button click retrieves and deserializes them. Conversion to byte array and back is done just to simplify communication with the Java back end, if any. Here’s the code:
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”>
<mx:Button x=”173″ y=”16″ label=”Save Hardcoded Preferences” width=”185″ click=”saveData()”/>
<mx:Button x=”203″ y=”46″ label=”Read Preferences” click=”getSavedData()”/>
<mx:TextArea x=”86″ y=”76″ width=”356″ id=”txtOutput” height=”156″/>
<mx:Script>
<![CDATA[
private var prefs:SharedObject;
private const COOKIE_SIZE:int=10000;
private function getSavedData():void{
prefs = SharedObject.getLocal("UserPrefs5");
var myBA:ByteArray = prefs.data.justTheBytes;
var recoveredUPrefs:Object=myBA.readObject();
var defaultTab:String=recoveredUPrefs["defaultTab"];
txtOutput.text+= “default tab=”+defaultTab + “\n”;
var visibleColumns:Object=recoveredUPrefs["visibleColumns"];
for (var elem:String in visibleColumns){
txtOutput.text+= elem+”=”+visibleColumns[elem]+ “\n”;
}
}
private function saveData():void{
prefs = SharedObject.getLocal(“UserPrefs5″);
var uPrefs:Object= new Object();
var visibleCol:Object = new Object();
//which col’s to make visible
visibleCol["custName"]=”true”;
visibleCol["custAddress"]=”false”;
visibleCol["customerAge"]=”true”;
uPrefs["visibleColumns"]=visibleCol;
// which tab in TabNavigator has to be opened first
uPrefs["defaultTab"]=”CanceledOrders”;
// turning the object with prefs into a set of bytes
var baPrefs:ByteArray = new ByteArray();
baPrefs.writeObject(uPrefs);
baPrefs.position = 0;
// Saving the byte array on disk in a SharedObject
prefs.data.justTheBytes=baPrefs;
var flushStatus:String = null;
try {
prefs.flush(COOKIE_SIZE);
} catch (error:Error) {
trace(“Error…Could not write SharedObject to disk”+ error.message);
}
} ]]>
</mx:Script>
</mx:Application>
Press the button Save, and it’ll save the hardcoded preferences in a local shared object – a String called defaultTab and a collection of flags for visible columns. Before saving, it serializes the Object (yes a simple Object with dynamically added properties) into an array of bytes and stores it in a local shared object. If you want, you can pass this array to the backend for storage in the database.
Press the Read button, and the properties will be resurrected from the disk and added to the text area on the screen. Simple, elegant, and flexible. Not exactly object-oriented. Sorry.
Yakov
Permalink

Below is a short comparison table of major elements/concepts of these two languages for a quick reference.
You can read this table either left-to-right or right-to-left, depending on what’s your primary programming language is today.
This list is not complete, and your input is appreciated.
|
Concept/Language Construct
|
Java 5.0
|
ActionScript 3.0
|
|
Class library packaging
|
.jar
|
.swc
|
|
Inheritance
|
class Employee extends Person{…}
|
class Employee extends Person{…}
|
|
Variable declaration and initialization
|
String firstName=”John”;
Date shipDate=new Date();
int i;
int a, b=10;
double salary;
|
var firstName:String=”John”;
var shipDate:Date=new Date();
var i:int;
var a:int, b:int=10;
var salary:Number;
|
|
Undeclared variables
|
n/a
|
It’s an equivalent to the wild card type notation *. If you declare a variable but do not specify its type, the * type will apply.
A default value: undefined
var myVar:*;
|
|
Variable scopes
|
block: declared within curly braces,
local: declared within a method or a block
member: declared on the class level
no global variables
|
No block scope: the minimal scope is a function
local: declared within a function
member: declared on the class level
If a variable is declared outside of any function or class definition, it has global scope.
|
|
Strings
|
Immutable, store sequences of two-byte Unicode characters
|
Immutable, store sequences of two-byte Unicode characters
|
|
Terminating statements with semicolons
|
A must
|
If you write one statement per line you can omit it.
|
|
Strict equality operator
|
n/a
|
===
for strict non-equality use
!==
|
|
Constant qualifier
|
The keyword final
final int STATE=”NY”;
|
The keyword const
const STATE:int =”NY”;
|
|
Type checking
|
Static (checked at compile time)
|
Dynamic (checked at run-time) and static (it’s so called ‘strict mode’, which is default in Flex Builder)
|
|
Type check operator
|
instanceof
|
is – checks data type, i.e. if (myVar is String){…}
The is operator is a replacement of older instanceof
|
|
The as operator
|
n/a
|
Similar to is operator, but returns not Boolean, but the result of expression:
var orderId:String=”123”;
var orderIdN:Number=orderId as Number;
trace(orderIdN);//prints 123
|
|
Primitives
|
byte, int, long, float, double,short, boolean, char
|
all primitives in ActionScript are objects.
Boolean, int, uint, Number, String
The following lines are equivalent;
var age:int = 25;
var age:int = new int(25);
|
|
Complex types
|
n/a
|
Array, Date, Error, Function, RegExp, XML, and XMLList
|
|
Array declaration and instantiation
|
int quarterResults[];
quarterResults =
new int[4];
int quarterResults[]={25,33,56,84};
|
var quarterResults:Array
=new Array();
or
var quarterResults:Array=[];
var quarterResults:Array=
[25, 33, 56, 84];
AS3 also has associative arrays that uses named elements instead of numeric indexes (similar to Hashtable).
|
|
The top class in the inheritance tree
|
Object
|
Object
|
|
Casting syntax: cast the class Object to Person:
|
Person p=(Person) myObject;
|
var p:Person= Person(myObject);
or
var p:Person= myObject as Person;
|
|
upcasting
|
class Xyz extends Abc{}
Abc myObj = new Xyz();
|
class Xyz extends Abc{}
var myObj:Abc=new Xyz();
|
|
Un-typed variable
|
n/a
|
var myObject:*
var myObject:
|
|
packages
|
package com.xyz;
class myClass {…}
|
package com.xyz{
class myClass{…}
}
ActionScript packages can include not only classes, but separate functions as well
|
|
Class access levels
|
public, private, protected
if none is specified, classes have package access level
|
public, private, protected
if none is specified, classes have internal access level (similar to package access level in Java)
|
|
Custom access levels: namespaces
|
n/a
|
Similar to XML namespaces.
namespace abc;
abc function myCalc(){}
or
abc::myCalc(){}
use namespace abc ;
|
|
Console output
|
System.out.println();
|
// in debug mode only
trace();
|
|
imports
|
import com.abc.*;
import com.abc.MyClass;
|
import com.abc.*;
import com.abc.MyClass;
packages must be imported even if the class names are fully qualified in the code.
|
|
Unordered key-value pairs
|
Hashtable, Map
Hashtable friends = new Hashtable();
friends.put(“good”,
“Mary”);
friends.put(“best”,
“Bill”);
friends.put(“bad”,
“Masha”);
String bestFriend= friends.get(“best”);
// bestFriend is Bill
|
Associative Arrays
Allows referencing its elements by names instead of indexes.
var friends:Array=new Array();
friends["good"]=”Mary”;
friends["best"]=”Bill”;
friends["bad"]=”Masha”;
var bestFriend:String= friends[“best”]
friends.best=”Alex”;
Another syntax:
var car:Object = {make:”Toyota”, model:”Camry”};
trace (car["make"], car.model);
// Output: Toyota Camry
|
|
Hoisting
|
n/a
|
Compiler moves all variable declarations to the top of the function, so you can use a variable name even before it’s been explicitly declared in the code.
|
|
Instantiation objects from classes
|
Customer cmr = new Customer();
Class cls = Class.forName(“Customer”);
Object myObj= cls.newInstance();
|
var cmr:Customer = new Customer();
var cls:Class = flash.util.getClassByName(“Customer”);
var myObj:Object = new cls(); |
|
Private classes
|
private class myClass{…}
|
There is no private classes in AS3.
|
|
Private constructors
|
Supported. Typical use: singleton classes.
|
Not available. Implementation of private constructors is postponed as they are not the part of the ECMAScript standard yet.
To create a Singleton, use public static getInstance(), which sets a private flag instanceExists after the first instantiation. Check this flag in the public constructor, and if instanceExists==true, throw an error.
|
|
Class and file names
|
A file can have multiple class declarations, but only one of them can be public, and the file must have the same name as this class.
|
A file can have multiple class declarations, but only one of them can be placed inside the package declaration, and the file must have the same name as this class.
|
|
What can be placed in a package
|
Classes and interfaces
|
Classes, interfaces, variables, functions, namespaces, and executable statements.
|
|
Dynamic classes (define an object that can be altered at runtime by adding or changing properties and methods).
|
n/a
|
dynamic class Person {
var name:String;
}
//Dynamically add a variable // and a function
var p:Person = new Person();
p.name=”Joe”;
p.age=25;
p.printMe = function () {
trace (p.name, p.age);
}
p.printMe(); // Joe 25
|
|
function closures
|
n/a. Closure is a proposed addition to Java 7.
|
myButton.addEventListener(“click”, myMethod);
A closure is an object that represents a snapshot of a function with its lexical context (variable’s values, objects in the scope). A function closure can be passed as an argument and executed without being a part of any object
|
|
Abstract classes
|
supported
|
n/a
|
|
Function overriding
|
supported
|
Supported. You must use the override qualifier
|
|
Function overloading
|
supported
|
Not supported.
|
|
Interfaces
|
class A implements B{…}
interfaces can contain method declarations and final variables.
|
class A implements B{…}
interfaces can contain only function declarations.
|
|
Exception handling
|
Keywords: try, catch, throw, finally, throws
Uncaught exceptions are propagated to the calling method.
|
Keywords: try, catch, throw, finally
A method does not have to declare exceptions.
Can throw not only Error objects, but also numbers:
throw 25.3;
Flash Player terminates the script in case of uncaught exception.
|
|
Regular expressions
|
Supported
|
Supported
|
Permalink

We earn our living at Farata Systems by selling Flex/Java consulting services and training. While doing this, every now and then we create reusable components, and so far we are giving them away for free. Some pathetic bloggers call this ‘giving back to the community’. We look at it simple: if we do not have time to productionize a component, we donate it.
These days some people are trying to sell Flex item renderers: they create a list-based control with a custom renderer and immediately put a price tag on it. I wish them good luck in selling these toys.
But I’m talking about real stuff here. For example, we’ve created an open source component called DAOFlex. Just enter “Select * from customers”, provide parameters of the Java EE data source, and go and make yourself a cup of coffee… if you can do it in 20 seconds. Because this is how long it takes DAOFlex to create all artifacts in Java, MXML, ActionScript and XML required for deployment of a FLex DataGrid with complete CRUD functionality.
Very proud of ourselves, we’ve uploaded this DAOFlex to Flex components exchange, and it quickly became one of the most downloadable Flex open source components…and then we started receiving lots of emails asking for tech support. Yes, we’ve provided instructions on how to install it. Yes, we’ve written an article about this component. Our upcoming Flex book has a chapter explainin how to create such components. All this is not enough – people need tech support. Some of them do not bother reading instructions – for them it’s easier to send an email asking for help.
Then, we’ve given away our logger component for free.
Now we have another one – we call it a supergrid, or a reporting component FlexBI. If you want to see a real power of DataGrid, do us a favor and spend 30 minutes watching this WebCast based in our recent presentation at MAX 2006. If there are PowerBuilder developers in the audience, think DataWindow-like reporting.
Just watch the webcast now….I’ll wait. Is it cool or what?
You can create a complex report populated with the data from a database in less than a minute. Then an end user can manipulate the data using drag-an-drop interface, create grouping, filters, write formulas on the fly… Raise your hand if you know how to write a program in any language that allows an end-user write and execute dynamic formulas (I’m not talking about selecting from a predefined list of sum, min, max and the like). Want to export the data to MS Excel? No problem.
The funny thing is that we are afraid of giving away FlexBI for free. We do not have enough resources to answer tech support questions. We are still debating if we should charge for FlexBI, which saves A LOT of time to any developer who needs to create ad hoc reports for business users. Actually, power users can create their reports themselves with FlexBI.

Anyway, if you’ll see a price tag on FlexBI, it means that we’ve hired a tech support person, and someone has to pay his/her salary. We need to move on – Apollo is looming, and we have lots of new ideas.
Yakov
Permalink

After attending half a dozen conferences this year I took a break and did not go to MAX. I check MXNA blog aggregator daily, but finding useful info is not easy. This is how a typical blog looks like. Yo man, it’s so cool! I’m going to MAX in three days! Two days till the conference… One…I’m in the airport. My flight is delayed. And again. And again. Finally I’m up in the air. What happen to the beer? Five bucks? You gotta be kidding me. That’s a bummer. The good news is that now they allow three ounce shampoo on the plain. I should not forget to take a dozen of these little shampoo and body lotions from my Venetian hotel room. By the way, anyone knows what the body lotion is for? Is it supposed to be used while in shower or after? There is no instructions on the bottle. Need to check Wikipedia…
I’m in Vegas! They gave me this military bag with some promo junk. Let me throw it away real quick. This bag is going to be for my cousin Vinni. Need to pick up a couple of XXL T-shirts on the vendor’s floor for my ant and mom.
Almost forgot about the Flex/ActionScript posters! Here they are! Yep, they are free! Adobe wanted to sell them for ten bucks each, but the entire blogosphere said, “Ain’t gonna buy no stinking posters for ten bucks”. I like Adobe. They always listen to the community, and now these great posters are free. This poster discussion is the most popular subject of the week at mxna. Finally I can get rid of this old J-Lo poster in my cube. She’s not that hot anymore.
Let me check the mxna feed and see what other guys are blogging about. Lemme see…Max is so cool…Cool is Max… Is Max Cool?…Adobe has released Flex Builder 2 for Mac OS X. Is there such thing as Flex Builder 1?
Several guys are leaking. They are leaking this tomorrow’s opening keynote. Everyone’s saying that we should be there at least for the first ten minutes. Some Blue Guys are giving either a demo or a show. I need more T-shirts.
My schedule for tomorrow is finally shaping up:
8:30-8:40 – keynote. Ben Forta hits 3 millionth mile spreading the good word about ColdFusion. I hope he’s in American Express miles award program. Ben, Bloomingdales gives away gift certificates: $1 for each hundred Amex miles. Your wife deserves these thirty grand! I have great respect of this man, really!
100K Flex developers. I wonder how they count? Is this just a number of downloads? Since Flex framework is free, you can’t even count sold licenses now. This raises one more question. The MAX book store was carrying 60 copies of the Flex Training from the source book, which is the only Flex tutorial available today and you can’t but it in stores yet. Hello Adobe marketing! I guess you’ve never heard of 100K Flex developers. No worries. The store promises another 40 copies of the book for the day 2. Round of applause to the newly hired Adobe Senior VP of marketing…I guess she needs some more time.
8:45-9:30 – hit some slot machines to warm up
9:30-10:30 – Black Jack table
10:30-11:15 – I’m presenting on Flex 2 tips and tricks
11:15-2PM – Roulette table
Hmmm, if you use the random number generator from ActionScript and the PieChart component from Flex Charting, you can easily emulate a roulette table! I just need to learn how to spin it! Should I register a new startup Online Flex Gambling right here in Vegas or Delaware is still the best for incorporation? I’ll need to create a number of skins for the roulette, a couple of transitions effects for showing the winning number, add some audio, which is piece of cake in Flash Player.
2:15 –4PM Hit the vendors floor. Do not get intimidated. Like the design of this T-shirt? Just stop by the booth, introduce yourself and spend five minutes listening to the brouhaha about how the product XYZ will revolutionize your life. Get the T-shirt and move to the next table. Look at these nice little glowing pens! Aren’t they something? Just give these vendors your business card and bring home a couple of pens for your kids. You’ll sure get this annoying phone call from their salesman in a month or so, but it’s in a month… while your kids will start enjoying these pens next week. Daddy came back from the business trip! What did you get for us? Look at this lady in red: she carries a huge bag of freebies and brochures. Trust me, she’s not going to read them. In the best case scenario, she’ll bring them to her office after MAX. But most likely she’ll leave them in the hotel room instead of tipping the maid.
4-5PM Attending a session on E4X. I need to learn how to write an RSS feed.
OK, Create XMLListCollection, declare a Filter object on it. Got it. The call to refresh functions will actually remove unwanted blog entries. How many mxna aggregates? More then 900? I’ll keep a couple of dozens in my feed. Where Celine Dion is singing? In Caesars? E4X rules! Flex 2 rules! Flex rules 2! Adobe is cool! Can’t wait till MAX 2007!
Yours truly,
Yakov
P.S. There are two bloggers that take good notes at MAX: Jen deHaan and Tariq Ahmed Thank you, guys!
Permalink

As a tribute to MAX2006, we have uploaded the latest release of our open-source daoFlex code generator and library.
What’s cool in this release? We now support complete data synchronization via Flex Remoting. Here is how: we’ve created a ActionScript class DataCollection that descends from ArrayCollection, but it is “destination-aware” and has its own methods fill() and sync(). DataCollection knows how many elements have been modified, created, deleted, etc. and can manipulate them freely.
ActionScript class BatchService allows sending updates done to multiple DataCollections in our batch. We wrote a small BatchGateway destination which applies such batch as a unit of work (JTA transaction). More, you can batch arbitrary remote calls, say invoking a stored procedure in the same transaction. And watch this: you can do this without writing a single line in Java, except defining annotated abstract classes.
So now you can use Flex Remoting for your data synchronization with back-end on par with Flex Data Services. These technologies are complementary to each other. Use Flex Data Services when you need the server push and pagination. For all other use cases Remoting is sufficient. Classes generated by daoFlex are universal for either solution. You take the side, we will supply the ammo
If you are in Vegas this week, I’ll be showing it in action at MAXUP.
Victor Rasputnis
Permalink

Ten years ago I’ve been doing PowerBuilder and my mentality was different: first, I was the best friend of business users, and second I did not really worry about what’s under the hood. I could do stuff quickly, or using the modern jargon, I was an agile programmer without even knowing this (on the same note, lots of people were creating Ajax applications five years ago without knowing this, but it’s off topic). I’d ask the business user Joe, “How do you usually do your business, what would you like to have on this screen, what step do you do after this step?” Most likely Joe did not really know, but I’d still give him a wide American smile: “No problem, I’ll come back tomorrow and will show you something”. Mary, yes, you, “What’s the most important word in my last sentence?” No, Mary, not “I’ll come back”, but TOMORROW. Not next week, not next month, but tomorrow.
With DataWindow component it was easy. I did not have to pull Joe’s teeth, I was able to create a working prototype in a day, show it to Joe next day, his glassy look all of a sudden would become friendly and understanding. Now Joe was back in control: “No, Yakov, you did this part wrong, I want it differently”. No problem, Joe, I’ll see you tomorrow. Mary, what was the most important word in my last sentence? Good girl, Hasta maniana! I did not really know how DataWindow worked, but I trusted this component. PowerBuilder used event-driven programming model, which was clean and simple. An object A triggers an event XYZ on object B, and this event can carry a payload – the data that the object B needs to operate. Using the modern jargon it’s called Inversion of Control or Dependency Injection design pattern. Whatever. What’s important is that the object B does not know about the object A. Loose coupling in action.
Then I became a Java programmer, and my mentality have changed. Big time. I realized that the user’s screens are not that important, because I have an intimate knowledge of how programs work internally. Screw users. I’ll spend majority of my time designing a multi-tier system that does not really depend on any specific screen and is universal. Joe still asked me, when is our next meeting? In a month. Mary, do not raise you hand. I see that you know the most important word here. Why in a month? Because I could not do a decent prototype sooner (Java folks, easy, easy – Matisse was not even in the picture yet), and more importantly, we started to make fun of PowerBuilder or Visual Basic programmers who were thinking screens, while us, cool Java gurus, knew how the motor worked inside! These guys were enjoying a ride and counting cup holders, while we were thinking sparking plugs and combustion chambers. We were enjoying the process of programming in itself.
There is this Russian stand-up comedian Mickhail Zhvanetskiy, and one of his excellent phrases was “Who cares about the soup, when so much is going on in the kitchen!”
Now, with Flex I started to care about the soup again, because I can. I can change the prototype twice a day, and Joe does the same with his business requirements. No six-freaking-sigmas documentation. Napkin on the knee is back and it works. I’ll give the final OK to my server side Java team only after Joe is 100% happy.
Besides, with Flex I can have the best of both worlds: the source code of the Flex framework is available, I can learn how it works inside and override it (not always it’s as easy as it should be, but it’s doable).
Working with Flex promotes agile development. If you do not know what it is, get a really good book Agile Java Development with Spring, Hibernate and Eclipse. This is one of these mis-titled books, which has not much to do with Spring, Hibernate and Eclipse other than the fact that it comes with the working sample application written with these tool/technologies. It presents an excellent overview of the development process in an enterprise Java shop. You’ll learn how to set up the environment, gather business requirements, and build the project deliverables in agile way.
Dear user, I’m your friend again! Now I’m as flexible as Flex can be. What do you want me to change?
Permalink

I’ll be teaching a hands-on Flex 2 class at NYU starting on November 9. It’s a 5-session evening class that will run over five weeks, which is a slow-pace way to learn how to create RIA with Flex. I still did not decide on the text book to recommend to the students for purchase.
Since I am Adobe Certified Flex instructor, I’m allowed to use Adobe’s original courseware. It’s a well written manual with great labs. The only thing is that the courseware may be a little expensive for students – need to talk to Adobe.
The other choice is O’Reilly book “Training from the Source“, but it’s printed version is not available yet.
And the third choice is to use three chapters of our upcoming book “Developing RIA with Flex and Java“. While this book is not a tutorial, it has beginning chapters where we just create a bunch of really small applications demonstrating various techniques/styles of programming. This “just-do-it” approach works well if there is an instructor in the room. The book is not printed yet, but I can create ten-page handouts. We’ll see.
NYU has already signed me up for a similar course in April 2007. There will be plenty of printed materials on Flex by the next Spring. I enjoy teaching programming and am looking forward to it.
Yakov Fain
Permalink

ActionScript 3 allows a function to have a variable number of arguments by using so-called … (rest) parameter. Ellipses followed by the name represent an array parameter that can contain any number of comma-delimited arguments:
public static function calcTax(… taxParams):Number{
for (uint i=0; i< taxParams.length; i++){
trace(taxParams[i]);
}
}
Java programmers may find the … (rest) similar to the varargs notation. You can mix the … (rest) with other function parameters as long as it’s the last parameter listed.
Unless you use the rest parameter, AS3 creates in memory a special object called arguments, which is an array that include references to each of the arguments and a reference to function itself (arguments.callee). AS3 allows you to call a function with more parameters than were included in the function declaration, and each of the parameters can be access by using the arguments[i] notation.
Here’s an idea of using … (rest) parameter to overcome the absence of overloaded constructors in AS3:
public function MyCLass(…args) {
switch (args.length) {
case 0: constructor1(); return;
case 1: constructor2(args[0]); return;
case 2: constructor3(args[0], args[1]); return;
…
} }
This sample covers the case of constructors having different number of parameters. But if you want this solution to work with functions having the same number of parameters but different types, you’d need to add the type check to each of these cases above, i.e.
if(args[0] is String) {
//do one thing
}else if (args[0] is Number){
// do another thing
}
Permalink
Today’s assignment is to be able to run a Flex application against different servers (dev, uat, prod) without the need to recompile SWF. It does not take a rocket scientist to figure out that the URL of the server should be passed to SWF as a parameter, and we’ll do this by using a special variable flashVars in HTML wrapper. Flex documentation suggests to include flashVars parameters in the tags Object and Embed and read them using Application.application.parameters in AS3 code. At the time of this writing this does not work. But as the ancient saying goes, “Adobe closes one door but opens another”. Let’s get familiar with Flex code:
Read more…
Permalink
Just finished writing an article called “Polymorphism Without Interfaces”. I challenge you to review and explain the code below:
for(var i:uint = 0; i < workers.length; i++) {
var p:* = workers[i]["increasePay"];
output.text+=p==undefined?”no luck”:p(5);
}
The person who writes the best explanation, will get a free copy of my e-book “Java programming for kids, parents and grandparents “. I’m sure people understand the syntax of this code snippet, but I’m looking for an explanation of WHY it’s written this way.
Good luck,
Yakov
Permalink

My primary clients are Java shops. When I suggest using Adobe Flex 2 as a rich client tool for their Web applications, they typically ask about the cost on the server side. Expected answer: free. When I start telling them about really powerful features of Flex Data Services, they like it. They just do not like the licensing cost,which is very reasonable. But Flex 2 it’s too young, and some people are still in denial phase. It’ll change soon, but there got to be a free solution. Just to get the foot in the door. And there is one.
I’ll be using a JavaServer page (JSP) here, but you can replace a JSP with any technology you’re comfortable with: servlets, Active Server Pages, Python, PHP et al. Whatever can spit out an XML to a Web browser should work the same way.
I’ll show you a really simple application written in Flex 2 that talks to the XML producing JavaServer page. Just to make it simple, let’s take an XML with the information about employees:
<people>
<person>
<name>Alex Olson</name>
<age>22</age><skills>java, HTML, SQL</skills>
</person>
…
</people>
Now, let’s hardcode this (I’ve got three persons) into a super simple JSP that consists of one out.println() call, where the xml should go between the double quotes:
<%out.println(“…”); %>
The complete JSP looks like this (just put your XML in one line so you won’t bother with string concatenations):
<%
out.println(“<?xml version=\”1.0\” encoding=\”UTF-8\”?><people><person><name>Alex Olson</name><age>22</age><skills>java, HTML, SQL</skills></person><person><name>Brandon Smith</name><age>21</age><skills>PowerScript, JavaScript, ActionScript</skills></person><person><name>Jeremy Plant</name><age>20</age><skills>SQL, C++, Java</skills></person></people>”);
%>
Deploy this JSP under some servlet container. I have Tomcat, so I just saved it as employees.jsp under my webapp\test directory. Do a sanity check to make sure that you’ve deployed this JSP correctly: entering http://localhost:8080/test/employees.jsp in your Web browser has to return the employee data.
Now comes the client part. If you have extra $500 laying around, purchase a license of Flex Builder from Adobe and enter the code below code in its editor. If you do not want to spend any money, just type this code in any text editor and use free command line mxmlc compiler that comes with Flex 2.
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
applicationComplete=”employees.send()”>
<mx:HTTPService id=”employees” useProxy=”false” method=”POST”
url=”http://localhost:8080/test/employees.jsp” />
<mx:DataGrid dataProvider=”{employees.lastResult.people.person}” width=”60%”>
<mx:columns>
<mx:DataGridColumn dataField=”name” headerText=”Name”/>
<mx:DataGridColumn dataField=”age” headerText=”Age”/>
<mx:DataGridColumn dataField=”skills” headerText=”Skills”/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
Not too much typing, isn’t it?
This code uses the <mx:HTTPService> component that allows you to connect to a specified URL either directly or through a proxy. In my example I just specify the URL of my JSP. The data provider of my data grid uses binding (see the curly braces) and E4X syntax to parse the XML and populate this table with the elements located under the
XML tag that is coming from our employees.jsp. Next month, I’ll write a piece explaining Flex data binding in more details. On the application Complete event, we send a request to the HTTPService object known under id employees, and our JSP readily returns the XML, which is bound to the data grid. Compile and run this program, and it’ll show you the following:
Not a bad result for a dozen lines of code.
Of course, it’s better to be rich and healthy than poor and ill. But my point is that even poor (or pretending to be poor) people can use Flex 2 with their existing server side Web tools for free.
Read about Flex to servlet communication at http://flexblog.faratasystems.com/?p=143
Permalink
|