Archive for February, 2007

Accessing Spring beans from flex (FDS)

1. What is Spring? Why do we care about Spring?
Christophe Coenraets  ‘ s 30 minute test drive provides good answer to these questions. See details here.

2. Spring Configuration
You can follow the steps described by Christophe or Jeff Vroom, or you can follow the steps below which provide easier access to the required jars.
1). Download spring.jar and flex-spring-factory.jar to your machine, and put them into your flex app’s WEB-INF/lib directory.
2). Add the following into your flex app’s WEB-INF/web.xml file, inside <web-app> tag.

    <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>

3). Add the following into to WEB-INF\flex\services-config.xml inside <services-config> tag:
               <factory id="spring" class="flex.samples.factories.SpringFactory"/>
4). If you are using JRun as app server, set the following in WEB-INF\jrun-web.xml to avoid parser conflicting:
Now you are ready to use flex to access Spring beans. 

3. Create Spring beans

We are going to use the sample code in To understand the code and configuration, see ""How to get Single Managed Objects from a specified remote destination". In that example, we access data from DataService using an Assembler  With the Assembler, we should be able to access Spring beans, right? Well, we are just a couple of steps away.

1). Create an interface (

Because we are trying to access Spring beans, we need to add an interface that represents all the methods we are going to use. From we can see that there are only two methods for this sample, so is going to be very simple: 

package myfds; 

import java.util.Collection;

import java.util.List;

import org.springframework.dao.DataAccessException; 

public interface MyDAO {       

            public List getProducts()  throws DataAccessException ;

             public MyBean getProduct(int myid)  throws DataAccessException ;



2). Modify and

— copy and save it as

Change the class to extends JdbcDaoSupport and implements the interface:

import org.springframework.dao.DataAccessException;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;

import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import org.springframework.jdbc.core.namedparam.SqlParameterSource;


public class MyServiceSpring extends JdbcDaoSupport implements MyDAO {


— copy and save it as

Change the class with setMyDAO():


public class MyAssemblerSpring extends AbstractAssembler {

        private MyDAO myDAO;

        public void setMyDAO(MyDAO myDAO) {

                this.myDAO = myDAO;



3). Compile your java code

Remember to include spring.jar and flex-messaging.jar in the classpath,

C:\flex\jrun4\servers\default\samples2\WEB-INF\classes>javac -classpath ./;C:\fl
efault\samples2\WEB-INF\lib\flex-messaging.jar  -Xlint myfds/*.java

Now we have the spring bean that we can access from flex, we need to register it with our flex app, and configure flex destination to point to the Spring factory.

4. Spring beans registration and flex destination configuration

1). Create applicationContext.xml and put it under your flex app’s WEB-INF directory. Here is the applicationContext.xml for this example:

<?xml version="1.0" encoding="UTF-8"?>



<!–define a data source to connect to your database –>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>

    <property name="url" value="jdbc:hsqldb:hsql://localhost/flexdemodb"/>

    <property name="username" value="sa"/>

    <property name="password" value=""/>


<!– define your service (methods) with a reference to dataSource –>

        <bean id="myServiceSpring" class="myfds.MyServiceSpring">

        <property name="dataSource" ref="dataSource"/>


<!– define assembler with reference (dependency) to myServiceSpring –>

<bean id="myAssemblerSpring" class="myfds.MyAssemblerSpring" singleton="true">

        <!–the property name myDAO should match the variable for interface MyDAO defined in MyAssemblerSpring–>

        <property name="myDAO" ref="myServiceSpring"/>



 Note, myServiceSpring will be the soruce name you use in the destination you define below.

2). Configure destination

We have registered Spring factory in WEB-INF\flex\services-config.xml in step 2 #3).

 <factory id="spring" class="flex.samples.factories.SpringFactory"/>

Therefore we need to point the destination to spring factory. Add the following into WEF-INF\flex\Data-management-config.xml:

<destination id="myfds-spring">

          <adapter ref="java-dao" />





                <identity property="myid"/>




Now, in flex mxml page, you can access the destination myfds-spring by doing something like this:

<mx:DataService id="ds" destination="myfds-spring" result="getData1(event)"/>

And call the methods in the Spring beans by using ds.getItem({myid:2})    

If you run myDataServiceSpring.mxml, you can get data from different method by click on different button.

Here is the which incdules all the code.

How to get Single Managed Objects from a specified remote destination

Flex Campaign for Java Developers has launched on Monday, Feb. 13. This is good news for java developer who would like to make Flex app work with backend database.Christophe Coenraets  ’s 30 minute test drive  provides many examples about how to manipulate data with FDS. You can download the test drive server here.

Once you extracted , you can see flex samples that integrate with ActiveMQ , Spring 2 , Hibernate 3.2 , and HSQLDB 1.8 .  Sample 8 under testdrive folder demonstrated how to retrieve/create/update/delete data using FDS. The flex client code displays the collection managed objects retrieved from backend. However, users may have difficulty to get Single Managed Objects from flex app. It may not be clear how the identity is passed to the method. I was asked to create a sample to get Single Managed Objects from a specified remote destination. I am putting a simplified version of the example here to demonstrate how to do that.

1. Create java Assembler

1). Create your bean (
First you create your bean with the data field you needed, and set/get method for each of them. 
2). Create for your methods
For simplicity,  I have only defined two methods:
     getProducts()  – retrieve all data, returns a list
     getProduct(int myid) — retrieve data with myid as identity,  returns a single Object.
3). Create an Assembler (
<The assembler extends AbstractAssembler class which is defined in flex-messaging.jar

public class MyAssembler extends AbstractAssembler {
        public Collection fill(List fillArgs) {
                      MyService service = new MyService();
                      return service.getProducts();
public Object getItem(Map identity) {
                      MyService service = new MyService();
                      MyBean mybean =  service.getProduct(((Integer) identity.get("myid")).intValue());
                      return mybean;

As we can see, fill() method calls getProducts(), and getItem() calls getProduct() from MyService.
Note,  MyBean mybean =  service.getProduct(((Integer) identity.get("myid")).intValue());
Here myid is the identity field.  It must match the identity property in your destination configuration:
<identity property="myid"/>

2. Compile your java code.
As we mentioned before, MyAssembler extends AbstractAssembler which is defined in flex-messaging.jar. So when you compile the java code, you must include flex-messaging.jar in your classpath.  This jar is included in your fds flex app’s \WEB-INF\lib directory.  For example:
C:\flex\jrun4\servers\default\samples2\WEB-INF\classes>javac -classpath ./;C:\fds-tomcat\webapps\ROOT\WEB-INF\lib\flex-messaging.jar -Xlint myfds/*.java

3. Mapping client-side objects to Java objects
This is a very important step, but easy to forget. Here are some key points from doc:
1). To represent a server-side Java object in a client application, you use the [RemoteClass(alias=" ")] metadata tag to create an ActionScript object that maps directly to the Java object. You specify the fully qualified class name of the Java class as the value of alias. This is the same technique that you use to map to Java objects when using RemoteObject components.
2).You can use the [RemoteClass] metadata tag without an alias if you do not map to a Java object on the server, but you do send back your object type from the server. Your ActionScript object is serialized to a Map object when it is sent to the server, but the object returned from the server to the clients is your original ActionScript type.
3). To create a managed association between client-side and server-side objects, you also use the [Managed] metadata tag or explicitly implement the interface. The [Managed] metadata tag ensures that the managed Contact object supports the proper change events to propagate changes between the client-based object and the server-based object.
See for code details.

4. configure destination in data-management-config.xml
add the following into your data-management-config.xml, parallel to other destination definition.
<destination id="myfds">
        <adapter ref="java-dao" />
                <identity property="myid"/>
                <paging enabled="false" pageSize="10" />
                <throttle-inbound policy="ERROR" max-frequency="500"/>
                <throttle-outbound policy="REPLACE" max-frequency="500"/>
Note: source should point to the full qualified class name of your assembler.
         Identity should match the identity you are passing in Assembler:
         MyBean mybean =  service.getProduct(((Integer) identity.get("myid")).intValue());

5. create flex page to display the data (myDataSerivce.mxml)
1).  Retrieve data
        <mx:ArrayCollection id="mydata1"/>
        <mx:DataService id="ds1" destination="myfds" result="getData(event)"/>
        <mx:Button  id="bt1" label="Get data from fill method" click="ds1.fill(mydata1)"/> 
        <mx:Button  id="bt2" label="Get data from getItem method" click="ds1.getItem({myid:2})"/>
— We first define a DataService ds1 which is mapped to destination named myfds. This should match <destination  id="myfds"> in data-management-config.xml.
—We call ds1.fill(mydata1) to populates an ArrayCollection mydata1, and use it as dataProvider of the datagrid.
    <mx:DataGrid dataProvider="{mydata1}"  width="300" height="100%" >
—We use ds1.getItem({myid:2}) to get single Object based on the dentity myid  we passed into getItem.
2). We use a result handler getData(event) to handle the data we retrieved from DataService. This will make sure that your event is trigged after the data has returned.  
Now let’s look at resulte handler getData():
   private function getData(event:ResultEvent):void{
           if(myButton == "bt1"){
                       prodId.text = event.result[1].prodID;
                       firstName.text = event.result[1].firstName;
                       lastName.text = event.result[1].lastName;
                        prodId.text = event.result.prodID;
                        firstName.text = event.result.firstName;
                        lastName.text = event.result.lastName;    
Because fill() method returns an ArrayCollection, getItem() returns a single object, so we have to treat it differently. To figure out which method is called by the user, we add EventListener to the button, and record the button id.
     private function init():void{
      private function clickHandler(event:MouseEvent):void{
               myButton =;
Now, when you click different button, different data will be displayed in "User Details" TitleWindow.

6. To test the sample:

1).  Unzip to your machine . Put myfds folder under your flex app’s WEB-INF/classes directory. Put myDataService.mxml and under you flex app’s root directory.
2). Double check the step 4 mentioned above. Restart your flex app server if needed.
3). Run myDataService.mxml, click on the two buttons and see different data displayed.

7. Troubleshooting

If there are no erros client side, but can’t get data to retrun from the server side, check the following:

1). double check step 4 mentioned above, make sure your destinatio id, sourceand identity property are defined correctly. Also, make sure your database connection is valid and qurey statement are correctly retrieving data.

2). Trun on server side debug bysetting log level to debug in services-config.xml:

<target class="flex.messaging.log.ConsoleTarget" level="Debug">

Flex builder silent install

My colleague Nick Watson put the instruction together, I am just posting his work here without changing any words.


· These steps are for silent installations on Windows – InstallAnywhere doesn’t support silent installation fully on OS X.

· There are two installers nested within the Flex Builder win installers, so they must be run in series for a silent operation: first the metainstaller, and then the individual installer (either standalone or plugin).

· One easy way to install silently is with a batchfile, as shown in the example below.

Create a properties file for each installer

· For a standalone installation the properties file must be named

· For a plugin installation the properties file must be named

· To run a standalone installation using the batchfile attached, place the file in the same folder with the batchfile and the installer

· The simple properties file example:


# Player installer choices

Sample batch file for silent installation

REM Place this batchfile in the same folder with the PFTW installer.
@echo off
mkdir %TMP%
mkdir %TMP%\installprops

copy %TMP%\installprops\

REM Extract the FB archive – match the exe filename below with the actual installer
FLXB_2.0_Win_WWE.exe /s /f%TMP% /a -i silent

Running the batchfile

· Make sure the batchfile is in the same folder as the FB installer, along with the properties file you created earlier

· Simply double-click the batchfile to run it

· Alternatively, you can open a cmd window to the folder that contains the batchfile, and run it by typing “silent” to invoke it

· Idiosyncrasies:

o The batchfile will appear as if it is complete before the installer is really finished

o You’ll know the silent install has really completed when the ColdFusion folder opens at the end.

The switches below are specifically for use with Package from the Web download:

/s tells FB to run silently
/f tells FB where to unpack its archive
/a allows FB to pass arguments to the next installer in the series: the InstallAnywhere metainstaller.

The next set of args are aimed at InstallAnywhere:
-i silent tells InstallAnywhere to run silently, resulting in the default Standalone installation selection in the metainstaler.

Tips for using Flex Builder 2 (part 2)

1. Install FB 2 on Vista get "Power User permissions required" error, even while logged on as admin

This was an issue in FB2 but it’s fixed in FB 2.0.1. Just in case you encounter this problem, here is a Workaround:

1). Click the OK button in the "Power User permissions required"   dialog to cancel & dismiss the installer

2). "Program Compatibility Assistant" dialog will appear

3). Select the first option, "Re-install using recommended settings" to re-launch the installer

For other installation problem, check the following first:

–Check account privilege, including read-write permission

–Check java version on the system. FB install includes a JRE; you don’t have to have JRE/JDK installed previously. However, if you have an existing JRE/JDK which is not a valid version for FB on the system, then it can cause problem during the installation. Use “java -version” command to verify the version of Java your system is using. The installer has to be able to find a valid jre/jdk installation.

–Check Direct X version . If the installation hangs, see

2. Flex builder silent install

See instruction here

3. xerces conflict when running FB with IBM JVM.

When using FB with WebSphere Development environment or IBM RSA 7.0,  xerces conflict may cause the service not start correctly.  To use the IBM jvm1.4.2 with the Flex Builder compiler and the Flex command-line compilers, you must ensure that the JVM loads the version of xerces supplied with Flex instead of the one in the IBM JVM. To do this, add the following JVM argument to the FlexBuilder.ini (Eclipse.ini in the plug-in configuration) file:

Standalone example:
-Xbootclasspath/a:C:/Program Files/Adobe/Flex Builder 2/Flex SDK 2/lib/xercesImpl.jar

Plug-in example:
-Xbootclasspath/a:C:\Program Files\Adobe\Flex Builder 2 Plug-in\Flex SDK 2\lib\xercesImpl.jar

4. Install FB 2.0.1 with IBM RSA/
RAD 7.0

1). FB plugin should be installed on top of the existing RSA/Eclipse configuration.

One potential workaround, for people who have already installed FB ahead of RSA, would be to disable com.adobe.feature.core using Eclipse Configuration Manager before installing RSA, and then re-enable it afterwards.

2). You may see error like the following:

java.lang.IllegalAccessError: cannot access superclass org/apache/xerces/util/XMLAttributesImpl$Attribute from class org/apache/xerces/util/XMLAttributesMMImpl$AttributeMMImpl

See #3 for xerces conflict issue.

3). if
RSA is installed as standalone with FB plugin on top of it, then you have to
launch with IBM’s shortcut icon (which uses IBM JVM).

If you install RSA’s plugin and FB plugin on top of Eclips, then you can launch it with either IBM shortcut icon or FB shortcut icon.

4). To make RAD 7.0 work with FB 2.0.1, See .

5. Eclipse Help trouble
Sometimes you may see error:”Help cannot be displayed. The embedded application server could not run help web application. Check the log for details.”
This is a log4j conflicting issue. See

6. Location of FB log file
The easiest way to find the log file is from FB Help.
Go to Help–>product details.. –>Configuration details –>view error log
If “view error log” is inactive, that means there is no error log exist. The error log will only be created after FB compiler found error in the code.
Here are the location of my log file on Window:
For standalone:
C:/Documents and Settings//My Documents/Flex Builder 2/.me
For plugin
On Mac:
/Documents/Flex Builder 2/.metadata/.log

If you don’t see .metadata folder on Mac, you can do the following to show hidden files:
In the Terminal type in:
defaults write AppleShowAllFiles TRUE
killall Finder

Flex 2 and Accessibility

One improtant thing to keep in mind is that Accessibility support doesn’t happen automatically. You have to tell flex you want Accessibility support in your app, and you need to implement it accordingly. Here are all the relevant links regarding Accessibility.

Enabling Application Accessibility
There are multiple ways to enabling application accessibility. See here for details. If you are using flex builder 2 to compile your app, from Flex builder, go to project—>properties —> flex compiler, check the box “generate accessible SWF file”.

Flex Accessibility Best Practices
Flex includes 22 components with built-in accessibility support. But this does not mean you can simply compile you app with accessibility enabled, and your app will meet all the requirement. You need to make sure you have taking care of Controlling Reading Order, Providing Instructions , Ensuring Keyboard Access, Providing Captions, Providing Text Equivalents, and Using Color Wisely.

Using Flex with JAWS

In order to most effectively use the JAWS screen reader with an Adobe Flex application, users must download and install scripts.

Example of Designing Loosely Coupled Flex 2 Components — pass data from main to child component

There is a good article regarding Designing Loosely Coupled Flex 2 Components. This is a good place to learn about different ways to design your components in Flex 2. On the third page of this article, it demonstrated how to Create Custom Event ActionScript Classes for sending complex data with an example. This example shows how to send data to the parent page by dispatch an event from the child component. What if you want to dispatch the event from the parent page, and pass the data into the child? Here is a simple example to show how we can accomplish that.

1. create a customer event ActionScript class:

In order to pass extra data via event, a customer event class is needed. We do this by extends existing Flex event classes and inherit all the events of the base class.  Here we create to pass selectedAlbum with the event.

     import mx.core.Application;

    public class myEvent extends Event
            public var myAlbum:String;
            public function myEvent(selectedAlbum:String,type:String) {
                     this.myAlbum = selectedAlbum;
           public override function clone():Event{
                    return new myEvent(myAlbum,type);

2.  Create the main application:

The main application has a datagrid. The goal is to be able to display data in a new state based on selected row in the datagrid. The follwoing two handlers are the most improtant:

1).datagrid’s itemClick event handler itemClickEvent():  this will get the selected row and value of selectedAlbum.

2).eventHandler(): this will display the new state, dispatch event myEvent (must make sure the event is dispatched after the child is created), and pass selectedAlbum to the child component. We reference the child component as <v:looselyCoupledChild />.

Note, eventObj = new myEvent(selectedAlbum,"passID");

Here, passID is the event name we will define in the Metadata of the child component:

[Event(name="passID", type="myEvent")]

main flex page looselyCoupled.mxml:

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="" xmlns:v="*" layout="vertical">

<!–This example passes selectedAlbum to child.mxml by listening  to myEvent –>        





                      import mx.collections.ArrayCollection;


                      public var selectedAlbum:String;

                      public var eventObj:myEvent;


                      private var initDG:ArrayCollection = new ArrayCollection([

            {Artist:'Pavement', Album:'Slanted and Enchanted', 

                      Price:11.99, SalePrice: true },

            {Artist:'Pavement', Album:'Brighten the Corners',   

                      Price:11.99, SalePrice: false }


        private function itemClickEvent(event:ListEvent):void {


                                    eventObj = new myEvent(selectedAlbum,"passID");




                             private function eventHandler(stateView:String):void{

                             //the stateView must be created before the event dispatch.

                                    this.currentState = stateView;



                      private function dispatchEvt():void{

                                    eventObj = new myEvent(selectedAlbum,"passID");





<mx:Label id="lb"  text="show selectedAlbum — from myEvent"/>

<mx:Label id="lb1"  text="show selectedAlbum — from eventObj.myAlbum"/>

<mx:DataGrid  id="dg" dataProvider="{initDG}"  itemClick="itemClickEvent(event)">


<mx:Button x="117" y="240" label="dispaly Album"  id="bt" click="eventHandler(‘child’)" />


                        <mx:State name="child">

                                      <mx:AddChild position="lastChild">

                                                                <v:looselyCoupledChild />





3. create the child component:

In the child component, we need to add event listener to listen to passID as following:   Application.application.addEventListener("passID", passIDHandler);


<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="" width="400" height="300" initialize="initHandler()" >
[Event(name="passID", type="myEvent")]

import mx.core.Application;
import myEvent;
private function initHandler():void{
Application.application.addEventListener("passID", passIDHandler);

private function passIDHandler(event:myEvent):void {
tinput.text = event.myAlbum;


<mx:Label text="Album you selected from event:" x="26" y="10"/>
<mx:TextInput x="107" y="8" id="tinput" />
<mx:Label x="291" y="10" text="Album you selected from selectedAlbum:"/>
<mx:TextInput x="372" y="8" text="{Application.application.selectedAlbum}"/>


Note, Application.application.addEventListener("passID", passIDHandler);
  This means we will always have a reference to the child. If you are concerned about memory issue, you should check and destroy the event when it is done. If you don’t want to destroy the event, you can set weakRef to true in addEventListener.

To test the sample,

1). run, and select a row. You will see the Album name displayed on top of the datagrid.

2). click on "dispaly Album" Button, you will see the Album name has passed into the child component.

3). select another row in the datagrid, you will see the value in the child component is changed as well.

Links to nice flex 2 examples

1. Design loosely coupled Flex 2 components

2. Export datagrid to Excel:
If manfully copy from a datagrid and paste to Excel is sufficient , see:
If you need the application to generate the excel for you , see:

3.Internationalizing Flex Apps

4. Coloring the Background of Cells

Scaling an image with smoothing

6. Unicode support
In order for it to work, you have to make sure
1).your font must support those characters.
2). you need to set the correct fontFamily,
3). you need to set character ranges

Here are couple of simple examples: to come ….