This Java architecture is a tough sell

Three years ago I ‘ve suggested a light architecture for Web/J2EE applications that was based on a Servlet container with transaction processing, Message Oriented Middleware, and a DBMS: http://java.sys-con.com/node/204697 . This piece was a part of an old and semi-serious Gas Station series published at Java Developer ‘s Journal.

Even though during the last three years I was predominantly involved with the client side part, I ‘ve been watching closely what ‘s happening in the Java EE domain.

Today, I was discussing an architecture of a new Flex/Java application with a colleague, and we came up with even lighter architecture: Flex-AMF protocol-JavaServlet+Transaction support library-DBMS with potential introduction of asynchronous messaging, if need be. I want to stress – only if there will be a need to scale, adding it on the protocol level so the application developers won ‘t even notice it. We ‘ve learned how to seriously scale well designed Jetty ‘s servlet container empowered by Adobe ‘s BlazeDS ( it ‘s a pity that Jetty-based early draftsof JSR 315 has been buried, which deserves a separate article).

No EJB or Spring container, no Hibernate either – just tried and true SQL/JDBC.

After the conversation was over, I ‘ve had this deja vu feeling and recalled that old article. On one hand, I still believe that this is the right way to architect Web applications, but on the other hand I know that it ‘ll be a tough sell – selling an architecture at a gas station is not the same as selling to Wall Street IT architects. This application will be developed for large corporate clients, which implies that I ‘ll need to present and defend this architecture in front of the architecture groups of these corporations.

EJB are out of style these days. In the Java world, the buzzwords of the first decade of this Century are Spring and Hibernate. If the PowerPoint won ‘t include such boxes on the architectural diagram, most likely the enterprise architects won ‘t approve it. Now I need to decide if I want to be 100% honest and jeopardize more efficient design, or be street smart, add these two boxes to the slide show, and when the project will be approved, quietly or with a fist fight remove them one by one.

I need to be very careful.

I need to think hard.

I need to consult with sales people.

I need to be smart.

I need to be politically correct.

Repeat.

The future of the Web: I disagree

Tim Bray, a Distinguished Engineer and Director of Web Technologies at Sun Microsystems has been interviewed by InfoQ about the future of the Web. With all my respect to Sun “s engineers, I have to disagree with some of the statements Mr. Bray made.

He said, “Anything that discards the Back button is a step backward “.

I strongly disagree that people who are used to the page-based Web apps can “t/won ‘t learn how to live without it. But even if it is the case, you can create RIA that support Back button – just decide what application view (no page) to show when the user hits the Back button.

Here “s one more of Mr. Bray “s statements, “The whole universe runs on polling and it scales beautifully “.

I don “t think so. To support server-side push an application has to keep an open socket connection that doesn “t take almost any resources most of the time. For a server, it ‘s easier to keep open 65000 connections on the server, than repeatedly responding to multiple requests from 65000 clients when most of them return “Sorry, I don ‘t have any new data for you “.

I agree that opening a socket present issues for Web applications running behind firewalls, but still the whole polling universe doesn “t scale beautifully.

Mr. Bray continues, “Web applications are not computational intensive “.

Of course, if you are using page-based applications that just show the data, there ‘s nothing to do on the client other than, well, showing the data. But in the world of RIA, we should get into a different state of mind – you can and should treat the client ‘s CPU as a first class citizen.

For example, our company helped Mercedes Benz in design and development of their Flex-based RIA: http://www.mbusa.com . There ‘s a bunch of interdependent rules for each car model that should enable/disable UI controls depending on the user ‘s selection. For example, if you ordered white leather interior, you can ‘t have yellow exterior. We ‘ve implemented the entire rule engine on the client, which makes the entire system a lot more responsive.

During one of my recent presentations, I said that if you build Flex/Java RIA utilizing fast AMF or RTMP protocols, you can bring 5000 records and keep them on the client in a split of a second.

A person from the audience asked,

“Why would I even need to keep 5000 records on the client? ”

“Because you can! Of course, something like this sounds wrong for AJAX applications, but it ‘s normal to bring 5000+ records of reference data to the client and keep them in the client “s VM so the user ‘s application wouldn ‘t need to do a round trip to the server to validate user ‘s input “.

If you offload the processing to the clients, you don ‘t need to horizontally scale the servers. With RIA, you can afford to have Client/Server mentality again.

Mr. Bray believes that the direction of Web applications is moving form J2EE to PHP and Rails. He didn ‘t make it clear for what kind of applications though. Is he talking about applications like Twitter that can go down several times a day and people will keep using it because they don ‘t have any better choice? I ‘ve heard creator of Rails calling Java legacy, and I understand the populist nature of such a statement, but it ‘s strange to hear this from one of Sun ‘s higher ups.

In this case Tim Bray is right. But if you take any application that handles your money (Banking, eCommerce, auctions) I ‘d rather stick to tried and true J2EE on the server and the RIA client software (Flash Player, Silverlight, JavaFX) that runs inside a predictable Virtual Machine.

I believe that Web moves to a VM-based stateful clients with fast communication lines between the client and the server moving tons of strongly-typed data back and forth. This was a mouthful sentence, wasn “t it?

A quote on the open source software

I like quotes by great minds. Here ‘s my favorite quote by Henry Ford:

If you think you can do a thing or think you can ‘t do a thing, you ‘re right.

As of today, we ‘ve submitted drafts of 75% of the chapters of our upcoming O ‘Reilly book “Enterprise Development with Flex ” . Some of these chapters had opening software-related quotes. Our editor suggested that if decided to open chapters with quotes, it should be done in every chapter for consistency. This makes sense.

Chapter 6 is titled “Open Source Networking Solutions “, which begs for a specific quote on open source software, but I ‘m not aware of any pundit who said something short and catchy in this field.

No biggy, I decided that I might as well come up with a quote myself. In less than three minutes I gave birth to this one:

99% of the people who reject using the software until it gets open sourced, neither plan nor will look at its source code.

Now it ‘s your call. If I won ‘t get feedback suggesting a better quote on open source software, I ‘ll keep this one.

So why do these people want someone ‘s software to be open sourced?

1. Some just hate these filthy rich software vendors and want them to have less control over their own software they created spending ton of money and other resources.

2. Some of them were raised as communists and don ‘t like when other people work hard and make money selling products of their own work. I used to work for a person who said “All people who drive Lexus are assholes “. As simple as that.

3. Some of them just hate the word proprietary.

4. Most of them hope that the remaining 1% of smarter guys can potentially fix/improve it, if need be.

5. Some of them believe that if the software is open sourced, its bugs will be fixed sooner and requests for improvements will be noticed a lot sooner.

6. Some individuals and most corporate IT shops want to copy this software without worrying about getting the licenses. But guess what, even open source software has a variety of licensing options.

OK, but why do people open source their own software?

To put it simple, they failed to sell their software, and this is THE main reason. But I can certainly give you some minor ones too:

1.Because they failed to create a software that can be sold for $.99 to millions of people and work on iPhone.

2. Because they can ‘t afford to hire salesmen who are members of the same golf clubs as CEO ‘s of Fortune 500.

3. Because other people already did the same, and having proprietary software hurts your image.

4. Because they are sick and tired of giving away their own software for free while paying people for answering tech support questions. Open sourcing software and creating user forums might lower the number of help request a little bit.

5. They don ‘t need this software anymore, but instead of dumping it, they can earn some good PR by open souring the sucker.

6. Here ‘s the main reason: they hope to substantially increase the number of users of their software and turn a small number of these users into paying customer (tech support, training, customization).

What if IBM will buy Sun for real?

When Wall Street Journal writes, they have their reasons. A couple of days ago they wrote that IBM wants to buy Sun Microsystems for $6.5B.

To me, this is sad news. I like Sun and don “t want them to die. Neither do I want to see thousands of Sun “s employees being laid off. But if IBM will really purchase Sun such consequences are unavoidable.

But if laid off people will be re-hired by other employers, some Sun “s software will die. I mean will cease to exist.

IBM is a huge firm. It makes hardware, software and has an extensive consulting arm. While IBM has been always supporting Java and its derivatives like IDE and J2EE servers, they were always behind. Just look at the delays in implementing latest Java specs in WebSphere. RAD IDE is not as good as Eclipse either.

So what software will die first?

IMO, Glassfish won “t survive. For years, Sun has been pushing this server that certainly has some modest following, but I doubt that IBM will need this product. They have WebSphere.

NetBeans will bite the bullet too. Again, this IDE has small number of developers who use it (mostly outside of the US), but Netbeans enjoyed an enormous amount of marketing dollars from Sun. Without such food supplements NetBeans would have really tough times staying competitive. Besides, IBM does not need it to compete neither with RAD IDE nor with Eclipse.

OK, it “s sad that these two products will go, but what worries me the most is the fate of JavaFX, which is not even a toddler yet. IBM may throw this baby with the bath water, and I don “t want this to happen. Even though JavaFX 1.1 is not competitive with its rival Flex and Silverlight just yet, it “s a very potent technology that in a year or two could become an equal player in the RIA space. But today, it needs bret feeding and it gets it. Continuing leadership of Sun plus outsourcing of JavaFX could bring good results. But I doubt that IBM would be as interested as Sun in success of JavaFX.

Even though JavaFX is not ready yet for enterprise application development, let “s not forget that Java Kernel project saw the light mainly to make JavaFX competitive. It “s because of JavaFX, the Java “s browser “s plugin doesn “t depend on the browser any longer. Remember that 10 year old law suite between Sun and Microsoft over the fact that Microsoft quietly added some libraries to Java making it dependent on the platform?

Back than, Sun won that battle but lost the war. Sun lost the runtime for Java applets available back then on more than 90% of computers since Internet Explorer was literally the only game in town. Even now, IE holds 75% of the market hellip; and is shipped with ten year old Java 1.1 plugin.

Now, we see the light again ndash; JRE won “t depend on the browser any longer. IMO, JavaFX was the main pusher for this.

But if IBM will swallow Sun, it “s not clear why would they want to overly invest in this language. Sun wasn “t too successful with monetizing of their software, but we as a community, were enjoying working with their products. Oh, well hellip;

We shouldn “t forget about yet another piece of software that Sun “s leaders purchased for $1B. Yes, the chances are they made this decision while being under the influence hellip;As of now, creators of MySQL left Sun.

Anyway, there are 10 million users of MySQL Server. Sun is thinking of using these legions for smart marketing that will allow selling them other goodies. Sun CEO blogged that even if one percent of MySQL users would decide to purchase others Sun “s products hellip;

IBM certainly needs 10M users. But do they need competition for UDB? I don “t know. Can they quietly kill MySQL? I don “t know.

Am I painting things pitch black for no reason? Do you see any positive developments for the Java community resulting from this $6.5B deal?

I see only one – JAVA stockholders will get a better price for their stock .

Stupid Passengers and Usability of UI

When you design UI, it has to be intuitive. If a user does something wrong, the first reaction of rookie developers is, “Stupid Users! rdquo;.

While some users may not be exceptionally bright, if they make mistakes using your software, most likely it “s your fault. I ran into a couple of such issues within the last three days.

1. While placing an order in one online store, I “ve entered my credit card number and pressed the button Submit. After a round trip to the server (this was a thin client Web application), I got an error page stating that the credit card number is invalid. Actually, the error message was very friendly and warm. It suggested, “Consider removing spaces from the credit card field rdquo;. I was so grateful! Indeed, I “ve entered my CC number as groups of four digits separated by spaces. Removed the spaces, another round trip to the server, and it took it!

Now I “m talking to you, the moron programmer who implemented this form. Have you heard that coders are allowed to perform string operations? Some advanced programmers even know how to programatically remove spaces from a string of characters. Guess what, it take less time than to program an error message stating that this stupid user should remove the spaces.

2. I spent two days in Atlanta attending Devnexus conference for Java developers. On the way back, I was checking in at the Delta “s kiosk. To identify myself, I “ve inserted my credit card into a special slot. The checking process was fast. I arrived earlier, and Delta “s software suggested that there is another flight to Newark, NJ an hour earlier and for mere $50 I can get a seat on that plane. Being a cheap bastard, I politely rejected this option. I can spend this hour having a dinner in a restaurant with my laptop and Boingo Internet, which I “m subscribed to.

So I picked up my boarding pass and started to look for a cozy place that has martini and an electric outlet in the wall. All of a sudden, this thought came to my tired mind, “Taking an earlier flight costs an extra fifty bucks, but on the other hand it “ll save me money on dinner at the airport. Eureka! rdquo;

While walking back to the Delta “s kiosk, I opened my wallet – the credit card was neither there nor in any of my pockets. I left it in that stupid slot in the Delta “s kiosk. 


The kiosk was still there, but the card was gone. I asked the Delta “s workers behind check in counter ndash; no one returned my CC. A quick call to my colleague (thank you, Anatole) and the CC was canceled.

Of course, you may say that I “m an idiot, but let me respectfully disagree. Yes, I was really tired after delivering two presentations in one day and the last thing that was on my mind was removing CC. But now I “m talking to you, the moron Delta programmer. Why did you print my boarding pass without forcing me to remove the credit card first? You didn “t thinks about it? Then don “t complain when your employer will file for bankruptcy once again, and this time it “s going to be Chapter 7.

While standing in line in the unemployment office, think of that stupid customer that decided not to use Delta any longer just because you didn “t care to write one extra if-statement suggesting that each stupid user has to remove his/her stupid credit card from that stupid slot in that Delta kiosk.

Annoying people, etiquette and Web site useability

Yahoo email (the old one) quietly introduced the AJAX-based online chat. Why would I care? Because people who I ever sent an email started giving me these popups asking my permissions to add me to their online chat rooms. There ‘s no freaking way that I can get rid of these popups other than answering “Decline “. But this would be rude to the person who I know. Is there any way to suppress these popups without telling them “Leave me alone. If I need you, I ‘ll send you an email “.

Thanks to AJAX, it doesn ‘t refresh the entire page but rather takes 1/8 of my screen.

In the past I was annoyed by all these people who keep signing up with various social networking sites. It seems that they just import their entire contact list from Yahoo email and send the message to all of their contacts, “Mary Lou would like to add you as a friend on a SoShmo network. ” Yes, I know Mary, but I never knew that she ‘s so annoying.

Or Joe Shmo is updating his Plaxo contacts. Please refresh you contact info. Dear Joe, what makes you think that you decision to refresh your contacts should make me wanna do the same? Can ‘t you respect other people ‘s privacy? The fact that I sent you an email two years ago doesn ‘t mean that you should request me to keep your stinking contact book up to date. Take care of it on your own. Please…

Or let ‘s take LinkedIn. I created a group for Flex Experts there and clearly stated that only people who have Flex-related blogs will be admitted. People don ‘t give a shit. They feel that the fact that they know Flex is enough to be included in my group. Guys, why won ‘t you create your own group and accept anyone there? Why don ‘t respect my wish to have only people with blogs, a.k.a. giving back to the community? The only option LinkedIn gives me is Decline. I can ‘t just delete a hundred of requests without the need to get into conflicts with people.

Twitter. I have love/hate relations with Twitter. But there ‘s no way to leave. It ‘s like a Hotel California. You can check out any time you want, but you can never leave…. “This service is temporarily is not available “. Lie. I know that Twitter is down more than any other social networking site because it was build on RoR. But having the unsubscribe feature permanently down is too bad even for RoR.

The next comes reunion.com. Admit. I made a mistake by subscribing to it. But how to get outta there? Do you have an idea? Am I sentenced to be there forever? These morons recently re-branded them as mylife.com. For some reason, it reminds me of Hitler ‘s book Mein Kampf.

Internet is annoying.

twitter.com/yfain

Introducing Enhanced Flex components from Clear Toolkit

The goal of this article is to give you a brief overview of some of the objects from clear.swc, which is a part of the open source Clear Toolkit framework available at https://sourceforge.net/projects/cleartoolkit.

Component library clear.swc includes a number of enhanced Flex components that software engineers of Farata Systems have been developing and using during the last three years in many enterprise projects. To better understand brief explanations given in this document, we strongly recommend to check out the source code from Sourceforge CVS repository and examine the source code of the classes mentioned below.

The ChangeObject Class

If you are familiar with LCDS, you know that Data Managemet Services use ChangeObject, which is a special DTO that is used to propagate the changes between the server and the client. Our component also includes such object but it can be used not only with LCDS but with BlazeDS too.

The class ChangeObject lives on the client side – it is just a simple storage container for original and new versions of the record that is undergoing some changes:


package com.farata.remoting {

[RemoteClass(alias= “com.farata.remoting.ChangeObjectImpl “)]

public class ChangeObject {

public var state:int;

public var newVersion:Object = null;

public var previousVersion:Object = null;

public var error:String = ” “;

public var changedPropertyNames:Array= null;

public static const UPDATE:int=2;

public static const DELETE:int=3;

public static const CREATE:int=1;

public function ChangeObject(state:int=0,

newVersion:Object=null, previousVersion:Object = null) {

this.state = state;

this.newVersion = newVersion;

this.previousVersion = previousVersion;

}

public function isCreate():Boolean {

return state==ChangeObject.CREATE;

}

public function isUpdate():Boolean {

return state==ChangeObject.UPDATE;

}

public function isDelete():Boolean {

return state==ChangeObject.DELETE;

}

}

Every changed record can be in DELETE, UPDATE or CREATE state. The original version of the object is stored in the previousVersion property and current one is in the newVersion. That turns the ChangeObject into a lightweight implementation of the Assembler pattern, which offers a simple API to process all the data changes in a standard way similar to what “s done in Data Management Services that come with LCDS.

The DataCollection class that will be described below automatically keeps track of all the changes made by the use in the UI and sends a collection of the corresponding ChangeObject instances to the server.

On the server side, you can you need to separate a task into DAO and Assembler layers by introducing external interfaces ndash; the methods with fill (retrieve) and sync (update) functionality (note the suffixes _fill and _sync in the Java code below). Iterate through the collection of ChangeObject instances and call appropriate persistence functions:

/* Generated by ClearDB Utility (Dao.xsl) */

package com.farata.datasource;

import java.sql.*;

import java.util.*;

import flex.data.*;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.transaction.*;

import com.farata.daoflex.*;

public final class EmployeeDAO extends Employee {

public final List /*com.farata.datasource.dto.EmployeeDTO[]*/ fill{

return getEmployees_fill();

}

public final List getEmployees_sync(List items) {

Coonection conn = null;

try {

conn = JDBCConnection.getConnection( “jdbc/test “);

ChangeObject co = null;

for (int state=3; state gt; 0; state–) { //DELETE, UPDATE, CREATE

Iterator iterator = items.iterator();

while (iterator.hasNext()) { // Proceed to all updates next

co = (ChangeObject)iterator.next();

if(co.state == state amp; amp; co.isUpdate())

doUpdate_getEmployees(conn, co);

if(co.state == state amp; amp; co.isDelete())

doDelete_getEmployees(conn, co);

if(co.state == state amp; amp; co.isCreate())

doCreate_getEmployees(conn, co);

}

}

} catch(DataSyncException dse) {

dse.printStackTrace();

throw dse;

} catch(Throwable te) {

te.printStackTrace();

throw new DAOException(te.getMessage(), te);

} finally {

JDBCConnection.releaseConnection(conn);

}

return items;

}

DataCollection class

This object keeps track of the changes on the client. For example, a user modifies the data in a DataGrid that has a collection of some objects used as a data provider. We “ve made a standard Flex ArrayCollection a little smarter so it “ll create a collection of ChangeObject instances for every modified, new, and deleted row. The class DataCollection will do exactly this.

Generate a sample CRUD application with Clear Data Builder and review the code of the generated sample Flex clients. The code to populate DataCollection will look similar to this one:

[Bindable]

public var collection:DataCollection ;

collection = new DataCollection();

collection.destination= “myEmployeeDestination “;

collection.method= “getEmployees “;

collection.addEventListener( CollectionEvent.COLLECTION_CHANGE, logEvent);

collection.addEventListener( “fault “, logEvent);

collection.fill();

When the user is ready to submit the changes to the server, the following line will send a collection of ChangeObject instances to the server:

collection.sync();

Below are some relevant fragments from the class DataCollection. It offers an API for manipulating collection “s state. You can query the collection to find out if this particular object is new, updated or removed:

public function isItemNew(item:Object):Boolean {

var co: ChangeObject = modified[item] as ChangeObject;

return (co!=null amp; amp; co.isCreate());

}

public function setItemNew(item:Object):void {

var co:com.farata.remoting.ChangeObject = modified[item] as ChangeObject;

if (co!=null){

co.state = ChangeObject.CREATE;

}

}

public function isItemModified(item:Object):Boolean {

var co: ChangeObject = modified[item] as ChangeObject;

return (co!=null amp; amp; !co.isCreate());

}

public function setItemNotModified(item:Object):void {

var co: ChangeObject = modified[item] as ChangeObject;

if (co!=null) {

delete modified[item];

modifiedCount–;

}

}

private var _deletedCount : int = 0;

public function get deletedCount():uint {

return _deletedCount;

}

public function set deletedCount(val:uint):void {

var oldValue :uint = _deletedCount ;

_deletedCount = val;

commitRequired = (_modifiedCount gt;0 || deletedCount gt;0);

dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, “deletedCount “, oldValue, _deletedCount));

}

private var _modifiedCount : int = 0;

public function get modifiedCount():uint {

return _modifiedCount;

}

public function set modifiedCount(val:uint ) : void{

var oldValue :uint = _modifiedCount ;

_modifiedCount = val;

commitRequired = (_modifiedCount gt;0 || deletedCount gt;0);

dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, “modifiedCount “, oldValue, _modifiedCount));

}

private var _commitRequired:Boolean = false;

public function set commitRequired(val :Boolean) :void {

if (val!==_commitRequired) {

_commitRequired = val;

dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, “commitRequired “, !_commitRequired, _commitRequired));

}

}

public function get commitRequired() :Boolean {

return _commitRequired;

}

public function resetState():void {

deleted = new Array();

modified = new Dictionary();

modifiedCount = 0;

deletedCount = 0;

}

All the changes are accessible as the properties deletes, inserts and updates:

public function get changes():Array {

var args:Array = deletes;

for ( var item:Object in modified) {

var co:com.farata.remoting.ChangeObject =

com.farata.remoting.ChangeObject(modified[item]);

co.newVersion = cloneItem(item);

args.push(co);

}

return args;

}

public function get deletes():Array {

var args:Array = [];

for ( var i :int = 0; i lt; deleted.length; i++) {

args.push(

new ChangeObject(

ChangeObject.DELETE, null,

ObjectUtils.cloneItem(deleted[i])

)

);

}

return args;

}

public function get inserts():Array {

var args:Array = [];

for ( var item:Object in modified) {

var co: ChangeObject = ChangeObject(modified[item]);

if (co.isCreate()) {

co.newVersion = ObjectUtils.cloneItem(item);

args.push( co );

}

}

return args;

}

public function get updates():Array {

var args:Array = [];

for ( var item:Object in modified) {

var co: ChangeObject = ChangeObject(modified[item]);

if (!co.isCreate()) {

// make up to date clone of the item

co.newVersion = ObjectUtils.cloneItem(item);

args.push( co );

}

}

return args;

}

This collection should also take care of the communication with the server and call the fill and sync methods:

public var _method : String = null;

public var syncMethod : String = null;

public function set method (newMethod:String):void {

_method = newMethod;

if (syncMethod==null)

syncMethod = newMethod + “_sync “;

}

public function get method():String { return _method; }

protected function createRemoteObject():RemoteObject {

var ro:RemoteObject = null;

if( destination==null || destination.length==0 )

throw new Error( “No destination specified “);

ro = new RemoteObject();

ro.destination = destination;

ro.concurrency = “last “;

ro.addEventListener(ResultEvent.RESULT, ro_onResult);

ro.addEventListener(FaultEvent.FAULT, ro_onFault);

return ro;

}

public function fill(… args): AsyncToken {

var act:AsyncToken = invoke(method, args);

act.method = “fill “;

return act;

}

protected function invoke(method:String, args:Array):AsyncToken {

if( ro==null ) ro = createRemoteObject();

ro.showBusyCursor = true;

var operation:AbstractOperation = ro.getOperation(method);

operation.arguments = args;

var act:AsyncToken = operation.send();

return act;

}

protected function ro_onFault(evt:FaultEvent):void {

CursorManager.removeBusyCursor();

if (evt.token.method == “sync “) {

modified = evt.token.modified;

modifiedCount = evt.token.modifiedCount;

deleted = evt.token.deleted;

}

dispatchEvent(evt);

if( alertOnFault amp; amp; !evt.isDefaultPrevented() ) {

var dst:String = evt.message.destination;

if( dst==null || (dst!=null amp; amp; dst.length==0) )

try{ dst = evt.target.destination; } catch(e:*){};

var ue:UnhandledError = UnhandledError.create(null, evt,

DataCollection, this, evt.fault.faultString,

“Error on destination: ” + dst);

ue.report();

}

}

public function sync():AsyncToken {

var act:AsyncToken = invoke(syncMethod, [changes]);

act.method = “sync “;

act.modified = modified;

act.deleted = deleted;

act.modifiedCount=modifiedCount;

if (writeThrough)

resetState();

return act;

}

}

}

Data Styling with Resource Files

Resources are small files that can be attached as a property to a regular UI component as well as DataGrid column. We call programming with resources data styling.

Again, start with examining the code of a sample project generated by Clear Data Builder. You can find a number of resource files under the folder flex_src\com\farata\resource.

Review the code of YesNoCheckBoxResource.mxml:

lt;?xml version= “1.0 ” encoding= “utf-8 “? gt;

lt;fx:CheckBoxResource

xmlns= “com.farata.resources ” xmlns:mx= “http://www.adobe.com/2006/mxml

xmlns:resources= “com.theriabook.resources.* ”

offValue = “N ”

onValue = “Y ”

textAlign= “center ”

gt;

lt;/fx:CheckBoxResource gt;

Doesn “t it look like a style to you? It can be specific to locale too. It makes it easy to change Y/N as on/off values to Д/Н, which means Да/Нет in Russian and Si/No in Spanish.

We “d like you to think of such resources as of entities that are separate from the application components. Isn “t such functionality similar to what CSS is about?

As a matter of fact, it “s more sophisticated than CSS because this resource is a mix of styles and properties. The next code example is yet another resource called StateComboBoxResource.mxml. It demonstrates using properties (i.e. dataProvider) in such resource, which we also call a Business Style Sheet. Such resource can contain a list of values such as names and abbreviations of states:

lt;?xml version= “1.0 ” encoding= “utf-8 “? gt;

lt;fx:ComboBoxResource

xmlns= “com.farata.resources ” xmlns:mx= “http://www.adobe.com/2006/mxml

xmlns:resources= “com.theriabook.resources.* ”

dropdownWidth= “160 ”

width= “160 ”

gt;

lt;fx:dataProvider gt;

lt;mx:Array gt;

lt;mx:Object data= “AL ” label= “Alabama ” / gt;

lt;mx:Object data= “AZ ” label= “Arizona ” / gt;

lt;mx:Object data= “CA ” label= “California ” / gt;

lt;mx:Object data= “CO ” label= “Colorado ” / gt;

lt;mx:Object data= “CT ” label= “Connecticut ” / gt;

lt;mx:Object data= “DE ” label= “Delaware ” / gt;

lt;mx:Object data= “FL ” label= “Florida ” / gt;

lt;mx:Object data= “GA ” label= “Georgia ” / gt;

lt;mx:Object data= “WY ” label= “Wyoming ” / gt;

lt;/mx:Array gt;

lt;/fx:dataProvider gt;

lt;/fx:ComboBoxResource gt;

Yet another example of a resource contains a reference to remote destination for automatic retrieval of dynamic data coming from, say a DBMS:

lt;?xml version= “1.0 ” encoding= “utf-8 “? gt;

lt;fx:ComboBoxResource

xmlns= “com.farata.resources ” xmlns:mx= “http://www.adobe.com/2006/mxml

xmlns:resources= “com.theriabook.resources.* ”

width= “160 ”

dropdownWidth= “160 ”

destination= “Employee ”

keyField= “DEPT_ID ”

labelField= “DEPT_NAME ”

autoFill= “true ”

method= “getDepartments ”

gt;

lt;/fx:ComboBoxResource gt;

As a matter of fact, you can “t say from this code if the data is coming from a DBMS or from somewhere else. That data is cleanly separated from the instances of the ComboBox objects associated with this particular resource and can be cached either globally (if the data needs to be retrieved once) or according to the framework caching specifications. If you are developing a business framework, you may allow, say lookup objects to be loaded once per application or once per view. This flexibility doesn “t exist in Singleton-based architectural frameworks.

Based on this resource file you can only say that the data comes back from a remote destination called Employee, which either a name of a class or a class factory. You can also see that the method getDepartments() will be returning the data containing DEPT_ID and DEPT_NAME that are going to be used with our enhanced ComboBox described earlier in this chapter.

OK, now we need to come up with a mechanism of attaching such resources to Flex UI components. To teach a Combobox working with resources, add a resource property to it:

private var _resource:Object;

public function get resource():Object

{

return _resource;

}

public function set resource(value:Object):void {

_resource = value;

var objInst:* = ResourceBase.getResourceInstance(value);

if(objInst)

objInst.apply(this);

}

The resource property allows you to write something like this:

lt;fx:ComboBox resource= rdquo;{DepartmentComboResource} rdquo;

Each of the enhanced UI components that “s included in clear.swc includea such property.

Since interfaces don “t allow default implementation of such setter and getter and since ActionScript does not support multiple inheritance, the easiest way to include this implementation of the resource property to each control is by using the language compile-time directive #include, which includes the contents of the external file, say resource.as, into the code of your components:

#include “resource.as rdquo;

Check the code of Employee_getEmployee_GridFormTest.mxml generated by Clear Data Builder. You “ll find there several samples of using resources:

lt;fx:DataGrid dataProvider= “{collection} ” doubleClick= “vs.selectedIndex=1 ” doubleClickEnabled= “true ” editable= “true ” height= “100% ” horizontalScrollPolicy= “auto ” id= “dg ” width= “100% ” gt;

lt;fx:columns gt;

lt;fx:DataGridColumn dataField= “emp_id ” editable= “false ”

headerText= “Emp Id “/ gt;

hellip;

lt;fx:DataGridColumn dataField= “dept_id ” editable= “false ”

headerText= “Department ”

resource= “{com.farata.resources.DepartmentComboResource} “/ gt;

lt;fx:DataGridColumn dataField= “state ” editable= “false ” 


headerText= “State ”

resource= “{com.farata.resources.StateComboResource} “/ gt;

lt;fx:DataGridColumn dataField= “bene_health_ins ” editable= “false ”

headerText= “Health ”

resource= “{com.farata.resources.YesNoCheckBoxResource} “/ gt;

lt;fx:DataGridColumn dataField= “bene_life_ins ” editable= “false ”

headerText= “Life ”

resource= “{com.farata.resources.YesNoCheckBoxResource} “/ gt;

lt;fx:DataGridColumn dataField= “bene_day_care ” editable= “false ”

headerText= “Day Care ”

resource= “{com.farata.resources.YesNoCheckBoxResource} “/ gt;

lt;fx:DataGridColumn dataField= “sex ” editable= “false ”

headerText= “Sex ” 


resource= “{com.farata.resources.SexRadioResource} “/ gt;

lt;/fx:columns gt;

lt;/fx:DataGrid gt;

Using resources really boosts your productivity.

The DataForm Component

Almost every enterprise application uses forms. Flex has the Form class that application programmers bind to an object representing data model. But the original Form class does not have means of tracking the data changes.

Since DataCollection is smart enough to automatically tracks the changes to the data on the client side, we found the way of enhancing the Form class so it works similarly to DataGrid/DataCollection duo. Yep, it has the dataProvider too.

Our DataForm control is bound to its model of type a DataCollection and it automatic tracks of all changes compatible with ChangeObject class that is implemented with remote data service.

The second improvement belongs to the domain of data validation. The DataForm can validate not just individual form items, but the form in its entirety too. Our DataForm stores its validators inside the form rather than in an external global object. The form becomes a self-contained black box that has everything it needs.

Software developers working on prototypes would appreciate if they should not be required to give definitive answers as to which control to put on the data form. The first cut of the form may use a TextInput control, but the next version should use a ComboBox instead.

The third improvement should simplify the UI prototyping. We came up with a UI-neutral data form item that will allow not to be specific like, “I “m a TextInput rdquo;, or “I “m a ComboBox rdquo;. Instead, developers will be able to create prototypes with generic data items with easily attachable resources.

The DataForm is a subclass of a Flex Form, and its code implements two-way binding and includes a new property dataProvider. Its function validateAll()supports data validation. This DataForm component will properly respond to data changes propagating them to its data provider.

Review the code of the class DataForm available in Sourceforge CVS repository. Notice the setter dataProvider that always wraps up the provided data into a collection. This is needed to ensure that our DataForm supports working with remote data services the same way as DataGrid does. It checks the data type of the value. It wraps an Array into an ArrayCollection, and XML turns into XMLListCollection. If you need to change the backing collection that store the data of a form, just point the collection variable at the new data.

If a single object is given as a dataProvider, turn it into a one-element array and then into a collection object. A good example of such case is an instance of a Model, which is an ObjectProxy that knows how to dispatch events about changes of its properties.

Once in a while, application developers need to render non-editable forms hence the DataForm class defines the readOnly property.

The changes of the underlying data are propagated to the form in the method collectionChangeHandler(). The data can be modified either in the dataProvider on from the UI and the DataForm ensures that each visible DataFormItem object (items[i]) knows about it. This is done in the function distributeData().

private function distributeData():void {

if((collection != null) amp; amp; (collection.length gt; 0)) {

for (var i:int=0; i lt;items.length; i++) {

DataFormItem(items[i]).data = this.collection[0];

}

}

}

Again, we need the data to be wrapped into a collection to support DataCollection or DataService from LCDS.

Technically, a DataForm class is a VBox that lays out its children vertically in two columns and automatically aligns the labels of the form items. But we “d like our DataForm to allow nesting ndash; containing items that are also instances of the DataForm object. A recursive function enumerateChildren() loops through the children of the form, and if it finds a DataFormItem, it just adds it to the array items. But if the child is a container, the function loops through its children and adds them to the same items array. In the end, the property items contains all DataFormItems that have to be populated.

The DataForm has a function validateAll(), which in Flex framework is located in the class Validator. There, the validation functionality was external to Form elements and you “d need to give an array of validators that were tightly coupled with specific form fields.

Enhancing Validation

It seems that validation in Flex has been designed with an assumption that software developers will mainly use it with forms and each validator class will be dependent only on one field it “s attached to. Say, you have a form with two email fields. Flex framework forces you to create two instances of the EmailValidator object ndash; one per field.

In the real life though, you may also need to come up with validating conditions based on relationships between multiple fields. You may also need to highlight invalid values in more than one field. For example, set the date validator to a field and check if the entered date falls into the time interval specified in start and end date fields. If the date is invalid, you may want to highlight all form fields.

In other words, you may need not just to validate an object property, but also have an ability to write a number of validation rules in a function that can be associated not only with the UI control but also with the underlying data, i.e. with a data displayed in a row in a DataGrid.

Yet another issue of Flex Validator is its limitations when it comes to working with view states when the UI controls are created automatically. Everything would be a lot easier if validators could live inside the UI controls, in which case they would be automatically added to view states along with the hosting controls.

Having convenient means of validation on the client is an important part of the enterprise Flex framework.

Let “s consider a RIA for opening new customer accounts in a bank or an insurance company. This business process often starts with filling multiple sections in a mile-long application form. In Flex, such an application may turn into a ViewStack of custom components with, say five forms totaling 50 fields. These custom components and validators are physically stored in separate files. Each section in a paper form can be represented as a content of one section in an Accordion or other navigator. Say you have total of 50 validators, but realistically, you “d like to engage only those validators that are relevant to the open section of the Accordion.

If an application developer decides to move a field from one custom component to another, he needs to make appropriate changes in the code to synchronize the old validators with a relocated field.

What some of the form fields are used with view states? How would you validate these moving targets? If you are adding three fields when the currentState= rdquo;Details rdquo;, you “d need manually write AddChild statements in the state section Details.

Say 40 out of these 50 validators are permanent, and the other 10 are used once in a while. But even these 40 you don “t want to use simultaneously hence you need to create, say two arrays having twenty elements each, and keep adding/removing temporary validators to these arrays according to view state changes.

Even though it seems that Flex separates validators and field to validate, this is not a real separation but rather a tight coupling.

During a conversation with a software developer, one manager said, “Don “t give me problems, give me solutions rdquo;. OK, here comes the solution.

We “d like to make it clear ndash; our goal in not to replace existing Flex validation routines, but rather offer you an alternative solution that can be used with forms and list-based controls.

We want to be able to have a ViewStack with five custom components, each of those has one DataForm whose elements have access to the entire set of 50 fields, but each will validate only its own set of 10. In other words, all five forms will have access to the same 50-field dataProvider. If during account opening the user entered 65 in the field age on the first form, the fifth form may show fields with options to open a pension plan account, which won “t be visible for young customers.

That “s why each form needs to have access to all data, but when you need to validate only the fields that are visible on the screen at the moment, you should be able to do this on behalf of this particular DataForm.

Clear component library includes the class ValidationRule. We won “t go into details of this class here, but will rather tease you by showing a code snippet that illustrates how easy it is to embed a validator inside of the DataGridColumn:

lt;fx:DataGridColumn dataField= “PHONE ” headerText= “Phone Number ”

formatString= “phone ” gt;

lt;fx:validators gt;

lt;mx:Array gt;

lt;mx:PhoneNumberValidator wrongLengthError= “Wrong

length, need 10 digit number “/ gt;

lt;/mx:Array gt;

lt;/fx:validators gt;

lt;/fx:DataGridColumn gt;

Needless to say that this is not an original Flex DataGridColumn, but its descendent.

Summary

In this writeup we “ve just touched upon the major players from the Clear component library. In the next article we “ll review the enhanecements made for the small guys like ComboBox or CheckBox.

We are also planning to record and publish a number of screencsasts that illustrate the use of various components of clear.swc. The process of creating enhanced library of Flex components will be described in greater detail in our upcoming O “Reilly book “Enterprise Development with Flex rdquo;.

How long is your job post?

Fifteen years ago, when a New York company needed a programmer, it would publish an ad in the classified section of Sunday edition of New York Times. The paper would charge by column/inch. The ads were short and up to the point. Only big guys like IBM, Microsoft or Oracle could afford to purchase an eights or a quarter of a page.

The smaller placement agencies were placing heavily abbreviated ads to squeeze in 15 words position description and the contact info.

These days, the life is different – we live in the paperless Internet world, and job boards place ads that are hundreds words. Below you ‘ll see an ad placed by Alta IT Services – they are looking for a mid-level Java developer that I picked from Dice search board. It ‘s more that 550 words.

Who needs to read all this bullshit? Doesn ‘t “Mid-level Java developer ” says it all? OK, you need to be more specific, add another 10 words. But please, don ‘t give me this crap like “Works under general direction to achieve project milestones and cost objectives “. Isn ‘t it clear that this poor mid-level Java developer will have a boss and unrealistic deadlines?

Or take this gem, “Assists development efforts in a specialized area of the project “. WTF? Please, explain me what does it mean?

One more, “Interfaces with staff from other systems, other contractors, and government agencies “. I guess, that they want a mid-level Java developer who can talk. Actually, deaf and mute people can also communicate with other contractors, aren ‘t they?

This one is the best: “Must have 3 years Java programming experience within the last 5 years (actual coding exp. ” I am speechless. The would accept a candidate who was coding in Java for 5 years and programming in Java three years out of five? Did I get it right?

I have an idea, this ad can be used during technical job interview too. If a candidate can explain what every sentence of this add means and is comfortable working in this environment, he ‘s hired!

But I ‘m going to pass on this opportunity. If you ‘d like to apply, here ‘s the URL for this job post: http://tinyurl.com/atraf7

If the link has expired, here ‘s the full text of that ad, enjoy!

twitter.com/yfain

Job Description

* Works under general direction to achieve project milestones and cost objectives.

* Efficiently produces software/software changes and documentation/documentation changes that are somewhat error free.

* Functions in a specialty discipline of the project such as hardware interface, inter-agency interface, legacy evolution, infrastructure, data mining, etc.

* Assists development efforts in a specialized area of the project.

* Develops and operates technical testing (unit and/or integration) prior to turning software packages over to the Development Lead and/or the Configuration Manager; activities include developing, perfecting, and executing the test scripts.

* Produces technical documentation to satisfy quality standards imposed by ICE OCIO, ITESS, and the project.

* Performs data migration and data fixes.

* Helps define the project scope, plans, and deliverables by working with the Operations Lead and Release Leads/Requirements Analysts.

* Demonstrates an understanding of the clients* business and IT needs as well as their IT standards for software, hardware, and documentation (the lifecycle).

* Produces rough order of magnitudes, estimates, and detailed impact assessments.

* Interfaces with staff from other systems, other contractors, and government agencies.

* Communicates with the Development Lead to notify him/her of development milestones (ready for builds, completion of TPR rework, etc).

* Demonstrates good record keeping through updates to the SCR (planned amp; actual effort, rework effort, affected components, impacts, related SCRs, notes, etc.) as well as the CIAs, unit test cases, and designs.

* Reports on development status; reports are thorough, clear, and include areas of concern which may require Development Lead attention.

* Sets up and maintains security rights and access permissions for team members, testers, support staff, and users as needed.

* Reports on progress/issues to Development Lead, Operations Lead, Release Leads, Project Management and users to ensure that all stakeholders are made aware so that action can be taken as needed.

* Researches system problems detected during environment setup, development, testing, implementation, and production to identify and fix the root cause of the problem so that there is minimal impact to the project schedule and the users.

* Identifies, develops, updates, and enforces policies, standards, and procedures (technical and non-technical).

* Reviews and provides input on system designs to ensure selection of appropriate technology, efficient use of resources, and integration of multiple systems and technologies.

* Monitors and ensures resolutions of performance issues.

* Researches and stays current on emerging tools, techniques, and technologies that are relevant or may benefit the FPS Program.

* Completes all corporate-required training and project-required training on time.

* Completes all corporate data calls on time.

* Completes timecards daily.

* Completes other tasks as assigned.

Skills

Technical

* Must have some experience developing web applications

* Must demonstrate some Java skills and object oriented design experience

* Must have 3 years Java programming experience within the last 5 years (actual coding exp.) or 3 years ASP, Visual Basic or Cold Fusion within the last 10 years (actual coding exp.)

* Must have exposure to a range of Java technologies

* Must possess some database skills * Oracle or SQL Server required

* Must possess knowledge of session management and XML web services

* May have experience with large-scale enterprise applications

* May demonstrate proven track record of excellent estimation skills

* Spend 100% of the time completing technical tasks (coding and related documentation)

Other

* Must be a US Citizen

Beer in NYC and Flex Workshop in Boston

On Tuesday evening, I “ll be buying beer for every attendee after our workshop for Flex architects: http://www.eventbrite.com/event/247789144 . To get $300 off the price, enter the discount code adjusting2crisis.

If you can “t make it in New York City, we “ll be running this event in Boston, MA on May 11 and 12: http://www.eventbrite.com/event/295389518

To the best of my knowledge, such advanced public training is not offered by any other RIA company.

Let “s have a beer (or two) together!

Our Flex framework Clear Toolkit goes open source

Our company, Farata Systems, 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 Document classes from Clear component library (clear.swc) – June 2009

4. Open source ClearBI, a Web reporter for Flex – August, 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.

twitter.com/yfain