Creating your first Adobe Air Application

Adobe Air is a great extension to the Adobe Flex framework that allows almost anyone to create rich internet applications for the desktop. With Adobe Air the same applications will run on Microsoft Windows, Mac OS X and Linux with pretty much no operating system dependent code. There are some exceptions though but that we will discuss later.

This tutorial is the first part of a tutorial series on how to build a File Manager using Adobe Air’s out of the box components. This file manager will have Drag & Drop capabilities, within the file manager itself, to copy or move files between directories. It will have native drag & drop capabilities to copy files from the desktop directly to the file manager. Or the other way around. Finally we will also add a navigational menu to the file manager to demonstrate some more useful out of the box Adobe Air components.

But before we go into all that let’s create our first “Hello World” Adobe Air application.

Step 1

Create a new project in Flex Builder but this time select the radio button that says ‘Desktop Application’

Depending on how you named your project you will see two files in your project. For example if you named it AirFileManager you will see an AirFileManager.mxml file and a AirFileManager-app.xml. The mxml file is the file where you will put the initial code.
Notice the WindowedApplication top level node that is created. This is the Adobe Air equivalent of the Application component in Flex. The main difference being that a WindowedApplication is not restricted to run in a browser, it runs on a desktop, and provides some extra features.

AirFileManager-app.xml file is an application descriptor file where you will configure certain parameters related to your Adobe Air Application. Parameters like transparency, system chrome, name, filename, copyright, window initial size and icon will be configured in this file.

Step 2

Add the following code:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
 <mx:Button label="Click me" click="mx.controls.Alert.show('I have just created my first Adobe Air App!')"/> 
</mx:WindowedApplication>

Step 3

Execute the Air app by clicking on the run method.

Congratulations! You have just created & executed your first Adobe Air app. But don’t go out to celebrate yet… that was just to break the ice.

Let’s make some modifications to the application descriptor.
Notice the systemChrome and transparency property. The systemChrome property tells Adobe Air whether to use the operating system native chrome or not. The transparency property is used to determine if the application window will be transparent or opaque. Note however that transparency is only supported if you set the systemChrome to none. If you set systemChrome to standard the operating system chrome is used and therefore Adobe Air can’t support transparency as it is outside its control.
Note that the default value for the systemChrome is standard.

To test this feature add a backgroundAlpha of 0.5 to the WindowedApplication component.
And modify AirFileManager-app.xml to:

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://ns.adobe.com/air/application/1.5">
 <!-- The application identifier string, unique to this application. Required. -->
 <id>AirFileManager</id>

 <!-- Used as the filename for the application. Required. -->
 <filename>AirFileManager</filename>

 <!-- The name that is displayed in the AIR application installer. 
      May have multiple values for each language. See samples or xsd schema file. Optional. -->
 <name>AirFileManager</name>

 <!-- An application version designator (such as "v1", "2.5", or "Alpha 1"). Required. -->
 <version>v1</version>

 <!-- Settings for the application's initial window. Required. -->
 <initialWindow>
  <content>[This value will be overwritten by Flex Builder in the output app.xml]</content>
  <systemChrome>none</systemChrome>
               <transparent>true</transparent>
 </initialWindow>
</application>

Run the Adobe Air application and see the difference in the application window. It should look transparent now.

Deploying Adobe Air Applications

Now that you have created your first Adobe Air application, you should package it into an AIR file. If you are using Flex Builder:

  1. Right click your project folder and select Export
  2. In the next screen choose Release Build and click Next
  3. If you want to include the source code with your release click on Enable View Source and then click Next.
  4. In this screen you are asked for a digital certificate to include with your Adobe Air application. You can either specify a digital signature provided by a third party like Verisign or Thawte. If you don’t have one then click Create to create your own self-signed digital certificate. Although you can can create your own digital certificate, it is not the best option as it doesn’t provide assurance to the users that your application is safe or that it hasn’t been tampered.
  5. Type your digital certificate password and click next
  6. Select the files you want to include in your package and then click finish.
  7. Your AIR installation package should have been created in the same directory as your project. Use this file to distribute your application.

That will be all for now. In the next part of this tutorial we will start adding the file manager components with which we will create a simple but yet powerful file manager in Adobe Air.




Click here to go to the next part of our tutorial.

The DisplayObject Blend Mode

The blend mode controls what happens when one display object is on top of another. The default setting in Adobe Flex is that the pixels of a display object override those that are displayed in the background. However you can change this behavior by modifying the blendMode setting. Read the language reference entry for DisplayObject. There you will find a detailed description of each blend mode.
In a nutshell the different blend modes available are:

  • BlendMode.NORMAL
  • BlendMode.LAYER
  • BlendMode.MULTIPLY
  • BlendMode.SCREEN
  • BlendMode.LIGHTEN
  • BlendMode.DARKEN
  • BlendMode.DIFFERENCE
  • BlendMode.DARKEN
  • BlendMode.OVERLAY
  • BlendMode.ADD
  • BlendMode.SUBTRACT
  • BlendMode.INVERT
  • BlendMode.ALPHA
  • BlendMode.ERASE
  • BlendMode.SHADE

Use the following flex code to try the different blend modes:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:core="*" xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" height="600" width="600" horizontalAlign="left">
 <mx:ArrayCollection id="blendModes">
  <mx:Array>
   <mx:Object label="Normal" data="normal"/>
   <mx:Object label="Layer" data="layer"/>
   <mx:Object label="Multiply" data="multiply"/>
   <mx:Object label="Screen" data="screen"/>
   <mx:Object label="Lighten" data="lighten"/>
   <mx:Object label="Darken" data="darken"/>
   <mx:Object label="Difference" data="difference"/> 
   <mx:Object label="Overlay" data="overlay"/>
   <mx:Object label="ADD" data="add"/>
   <mx:Object label="Subtract" data="subtract"/>
   <mx:Object label="Invert" data="invert"/>
   <mx:Object label="Alpha" data="alpha"/>
   <mx:Object label="Erase" data="erase"/>
  </mx:Array>
 </mx:ArrayCollection>
 <mx:Canvas height="200" width="400">
  <mx:VBox height="100" width="100" backgroundColor="{color1.selectedColor}" backgroundAlpha="1" blendMode="{blendMode1.selectedItem.data}" />
  <mx:VBox height="100" width="100" backgroundColor="{color2.selectedColor}" backgroundAlpha="1"  x="50" y="50" blendMode="{blendMode2.selectedItem.data}"/>
 </mx:Canvas>
 <mx:Panel title="Blend Modes" layout="horizontal">
  <mx:ComboBox id="blendMode1" dataProvider="{blendModes}" />
  <mx:ComboBox id="blendMode2" dataProvider="{blendModes}"/>
 </mx:Panel>
 <mx:Panel title="Colors">
  <mx:ColorPicker id="color1"/>
  <mx:ColorPicker id="color2" selectedColor="blue"/>
 </mx:Panel>
</mx:Application>




Click here to try the example.

Integrate Adobe Flex and JBOSS using BlazeDS – Part II

In the first part of this tutorial I showed you an example on how to integrate flex with JBOSS using BlazeDS. In this example we used RemoteObject in Actionscript to create a new instance of uk.co.spltech.remote.RemoteService and call the callMe() method remotely. The method returned a list of strings that we used to populate a datagrid.
In the second part of this tutorial we will do something slightly more useful. This time we will be invoking an EJB 3.0 bean managed by the application server.

Step 1

To be able to invoke EJB 3.0 from flex you need to download and copy FlexEJBFactory.jar to $JBOSS_HOME/server/default/lib. Or you can copy it to a local directory in your project separate from JBOSS e.g. example7/jbosslib and add the following line to $JBOSS_SERVER/server/default/conf/jboss-service.xml:

<classpath codebase="/usr/java/eclipse/workspace/example7/jbosslib" archives="*"/>

Previously all the BlazeDS jars were located in the WAR:WEB-INF/lib directory. But this is not going to work now because we need to see the jars within the context of the entire EAR. For that reason we need to move all those jars to to $JBOSS_SERVER/server/default/lib(or to a local directory inside your project e.g. jbosslib):

flex-ejb-factory.jar
flex-messaging-common.jar
flex-messaging-core.jar
flex-messaging-opt.jar
flex-messaging-proxy.jar
flex-messaging-remoting.jar
backport-util-concurrent.jar

Step 2

Because we will be invoking EJB 3.0 components we need to change the build process so that it creates an EAR file instead of a WAR. We add the following lines to the createjars target:

<jar jarfile="build/example7.jar">
 <fileset dir="${build.classes.dir}">
    <include name="uk/co/spltech/remote/*.class" />
 </fileset>
       
    </jar>

    <zip zipfile="build/example7.ear">
 <zipfileset dir="build">
  <include name="example7.war" />
 </zipfileset>
 <zipfileset dir="${build.dir}/resources" prefix="META-INF">
  <include name="application.xml" />
 </zipfileset>
       <zipfileset dir="build">
  <include name="example7.jar" />
 </zipfileset>
     </zip>

Step 3

Add the new ejb3 factory to flex/services-config.xml:

<factories>
     <factory id="ejb3" class="com.adobe.ac.ejb.EJB3Factory"/>
 </factories>

Step 4

Inside the uk.co.spltech.remote package create the following classes:

package uk.co.spltech.remote;

import java.util.List;

/**
 * This is an example of an interface where you can
 * declare all the methods that you want to call remotely
 * 
 * @author Armindo Cachada
 *
 */
public interface RemoteService {
 /**
  * I am not doing anything useful except to just show that I can be invoked remotely
  * from Adobe Flex using RemoteObject.
  * 
  */
 public List<String> callMe();
}

And the implementation of the interface:

package uk.co.spltech.remote;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;

/**
 * This remote service is called using BlazeDS/LiveCycle DS from Flex
 * 
 * @author Armindo Cachada
 *
 */
@Stateless(name = "remoteService")
@Local(RemoteService.class)
public class RemoteServiceImpl implements RemoteService {

 
 /**
  * I am not doing anything useful except to just show that I can be invoked remotely
  * from Adobe Flex using RemoteObject.
  * 
  */
 public List<String> callMe() {
  System.out.println("I was invoked!");
  List<String> result = new ArrayList<String>();
  result.add("Michael Jackson");
  result.add("Beatles");
  result.add("Tina Turner");
  return result;
 
 }
}

Step 5

Add the new destination to flex/remoting-config.xml:

<destination id="remoteService" >
        <properties>
              <factory>ejb3</factory>
              <source>example7/remoteService/local</source>
              <scope>application</scope>
         </properties>
   </destination>

There are two differences in the destination declaration:

  • The factory node indicates that we want to use the EJB3Factory declared in services-config.xml
  • The source instead of referencing a class name is changed to reference an EJB3 bean via JNDI.

Step 6

We are going to use the same mxml code as the one for Part I of this tutorial but we need to change the flex compiler settings:

-services "/usr/java/eclipse/workspace/example7/resources/flex/services-config.xml" -context-root "/example7" -locale en_US

After you have followed all these steps you should be good to go!




Download source code for JBOSS+Adobe Flex+BlazeDS project Part II

To save bandwidth I didn’t include all the jars needed:

flex-ejb-factory.jar
flex-messaging-common.jar
flex-messaging-core.jar
flex-messaging-opt.jar
flex-messaging-proxy.jar
flex-messaging-remoting.jar
backport-util-concurrent.jar

Copy these jars to the jbosslib directory inside the project. Don’t forget to change jboss-service.xml to reference this directory. Otherwise nothing will work.

Good luck!

Integrate Adobe Flex and JBOSS using BlazeDS – Part I

In this tutorial I will give you step by step instructions on how to integrate Adobe Flex and JBOSS using BlazeDS.
Although in this tutorial I am addressing BlazeDS, the steps in this tutorial should also apply to Adobe Flex LiveCycle Data Services. The only difference are the jars that you copy to your WEB-INF/lib directory. For those who want to integrate BlazeDS with Struts 2, the instructions in this tutorial should also be helpful.

In the Java Backend:

Step 1

Download blazeds.war from http://opensource.adobe.com/wiki/display/blazeds/Downloads

Step 2

Unzip blazeds.war. Copy the files in WEB-INF/lib and WEB-INF/flex to your web project under the same path in your web app.

Step 3

Edit web.xml and add the following lines:

    <!-- Http Flex Session attribute and binding listener support -->
    <listener>
        <listener-class>flex.messaging.HttpFlexSession</listener-class>
    </listener>

    <!-- MessageBroker Servlet -->
    <servlet>
        <servlet-name>MessageBrokerServlet</servlet-name>
        <display-name>MessageBrokerServlet</display-name>
        <servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
        <init-param>
            <param-name>services.configuration.file</param-name>
            <param-value>/WEB-INF/flex/services-config.xml</param-value>
       </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>MessageBrokerServlet</servlet-name>
        <url-pattern>/messagebroker/*</url-pattern>
    </servlet-mapping>

Step 4

Create a simple java class with a simple method that we will invoke from Adobe Flex:

package uk.co.spltech.remote;

import java.util.ArrayList;
import java.util.List;

/**
 * This remote service is called using BlazeDS/LiveCycle DS from Flex
 * 
 * @author Armindo Cachada
 *
 */
public class RemoteService { 
 /**
  * I am not doing anything useful except to just show that I can be invoked remotely
  * from Adobe Flex using RemoteObject.
  * 
  */
 public List<String> callMe() {
  System.out.println("I am being invoked!");
  List<String> result = new ArrayList<String>();
  result.add("Michael Jackson");
  result.add("Beatles");
  result.add("Tina Turner");
  return result;
 }
}

Step 5

Create a new destination in remoting-config.xml:

<destination id="remoteService" >
   <properties>
        <source>uk.co.spltech.remote.RemoteService</source>
        <scope>application</scope>
   </properties>
</destination>

The source of the destination can be a fully qualified class name, a jndi reference or a spring bean. We will discuss that in a later post. For this example we just specify a class name.

The scope of the destination can be one of:

  • application – there is only one instance of the class for the entire application(i.e. global in atg, singleton in spring)
  • session – there is one instance per user session
  • request – for each http request a new instance of the class is created

In Adobe Flex:

Step 1

Create a new project in Adobe Flex. Please make sure that the Application Server type is set to none.
Why? Fair question to ask since most instructions say to do exactly the opposite. I found those instructions not really helpful in the case of JBOSS since they assume I can provide the directory containing the application after it is deployed to JBOSS. That works quite well for tomcat because it simply extracts the war file under webapps. The path is always the same. In the case of JBOSS the path to the application changes after each deployment…

Step 2

The only reason Adobe Flex asks you for the path to the root folder of your web application is so that it can provide two arguments to the flex compiler:

  • services – The path to the Adobe flex data services configuration file
  • context-root – The context root of your web application

After you create your web application add the following arguments to the flex compiler:

-services "/usr/java/eclipse/workspace/example6/resources/flex/services-config.xml" -context-root "/example6"

Step 3

Let’s create a very simple flex application that invokes the callMe() method in uk.co.spltech.remote.RemoteService. This method returns an ArrayList with a list of items:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" >
<mx:Script>
 <![CDATA[
  import mx.collections.ArrayCollection;
  import mx.controls.Alert;
  import mx.rpc.events.ResultEvent;
  import flash.utils.getQualifiedClassName;
  
  
  /**
   * Populates the data list using the results returned by callMe()
   */
  private function populateList(event:ResultEvent):void {
   var result:ArrayCollection= ArrayCollection(event.result);
   singerList.dataProvider= result;
  }
 ]]>
</mx:Script>
 <mx:RemoteObject id="myService" destination="remoteService" result="populateList(event)"/>
 <mx:List id="singerList" >
  
 </mx:List>
 <mx:Button click="myService.callMe();" label="Call Remote Function"  />
</mx:Application>

Step 4

Compile the flex app and copy all the generated swf/html/js to your jboss web app.

Step 5

Deploy the war file to JBOSS and test it under http://localhost:8080/example6

If you click in the “Call Remote Function” button you should see a list of results returned by the method callMe().

Download source code for JBOSS+Adobe Flex+BlazeDS project

Note that, in order to make the zip smaller, I didn’t include the BlazeDS jar files. You need to manually copy them to the lib directory before generating the war file.

Click here to read Part II

How to use verticalCenter and horizontalCenter in a container with absolute layout

In this tutorial I will explain how you can use the verticalCenter and horizontalCenter constraints in a container with absolute layout.

At this stage you probably already figured out how to use the left, right, top, bottom constraints. But what about horizontalCenter and verticalCenter?

horizontalCenter is the distance from the center of the container in the horizontal where you want your component to appear. If you give it a positive value, the component will show up in the right half of the container. If you give it a negative value the component will appear in the left half.

<mx:Canvas width="500" height="500">
   <mx:Button horizontalCenter="200" label="Right half of the container"/>
   <mx:Button horizontalCenter="-200" label="Left half of the container"/>
</mx:Canvas>

If you try to combine horizontalCenter with left or right constraints, they will always be ignored as the horizontalCenter constraint always takes precedence.

<mx:Canvas width="500" height="500">
   <mx:Button horizontalCenter="200" left="400" label="Button 1"/>
   <mx:Button horizontalCenter="200" right="200" label="Button 2"/>
</mx:Canvas>

In the example above the two buttons will overlap because the value of the left and right coordinate is ignored.

verticalCenter is the distance from the center of the container in the vertical where you want your component to appear. If you give it a positive value, the component will show up in the bottom half of the container. If you give it a negative value the component will appear in the top half.

<mx:Canvas width="500" height="500">
   <mx:Button verticalCenter="200" label="Bottom half of the container"/>
   <mx:Button verticalCenter="-200" label="Top half of the container"/>
</mx:Canvas>

If you try to combine verticalCenter with top or bottom constraints, they will always be ignored as the verticalCenter constraint always takes precedence.

<mx:Canvas width="500" height="500">
   <mx:Button verticalCenter="200" top="400" label="Button 1"/>
   <mx:Button verticalCenter="200" bottom="200" label="Button 2"/>
</mx:Canvas>

In the example above the two buttons will overlap because the value of the top and bottom constraint is ignored.

The code below shows possible combinations of horizontalCenter and verticalCenter that you can use to layout your components:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" height="520" width="520">
<mx:Button label="Left Center" horizontalCenter="-200" verticalCenter="0">
</mx:Button>

<mx:Button label="Center" horizontalCenter="0" verticalCenter="0">
</mx:Button>

<mx:Button label="Right Center" horizontalCenter="200" verticalCenter="0">
</mx:Button>


<mx:Button label="Top Left" horizontalCenter="-200" verticalCenter="-200">
</mx:Button>

<mx:Button label="Top Center" horizontalCenter="0" verticalCenter="-200">
</mx:Button>

<mx:Button label="Top Right" horizontalCenter="200" verticalCenter="-200">
</mx:Button>

<mx:Button label="Bottom Left" horizontalCenter="-200" verticalCenter="200">
</mx:Button>

<mx:Button label="Bottom Center" horizontalCenter="0" verticalCenter="200">
</mx:Button>

<mx:Button label="Bottom Right" horizontalCenter="200" verticalCenter="200">
</mx:Button>


<mx:Button label="Ignored right constraint" right="10" horizontalCenter="-200" verticalCenter="50">
</mx:Button>

<mx:Button label="Not ignored right constraint" right="10" verticalCenter="50">
</mx:Button>

<mx:Button label="Ignored top constraint" top="10" horizontalCenter="-200" verticalCenter="-50">
</mx:Button>

<mx:Button label="Not Ignored top constraint" top="10" horizontalCenter="-200">
</mx:Button>

</mx:Application>




Click here to try the example above

Recording a video stream with Red5

In this post I will show how simple it is to create an Adobe Flex client to record a video stream to a server running Adobe Media Server or Red5. Not only that I will also provide you with the code that you need to play the stream after you record it

Step 1

Connect to the Adobe Media Server or Red5 using NetConnection.connect()

private function connect():void {
   nc = new NetConnection();
   nc.addEventListener(NetStatusEvent.NET_STATUS,netStatusHandler);
   nc.connect("rtmp://localhost/vmspeak");
  ...   
}

In the case above we added an event listener to the NetConnection. Whether we are able to connect or not the method netStatusHandler is called. This method checks if the connection attempt is succcessful and enables/disables the record button based on that.

/**
  * When the connection is successful we can
  * enable the record button.
  * 
 */
private function netStatusHandler(event:NetStatusEvent):void
{
        trace(event.info.code);
 if(event.info.code == "NetConnection.Connect.Success")
 {
  this.recordButton.enabled=true; 
 }
 else {
  mx.controls.Alert.show("Failed to connect!");
 }
}

Step 2

Request access to the web camera and microphone:

   mic =Microphone.getMicrophone();
   mic.setUseEchoSuppression(true);
   mic.setSilenceLevel(0);
   cam = Camera.getCamera();

When executing this code Flash will show you a popup window requesting permission to access the video and microphone.

Step 3

To start recording you need to create a NetStream object using as argument the NetConnection you created in the step before.

  var ns:NetStream = new NetStream(nc);

Step 4

Attach the video and the camera to the NetStream and start recording.
You can also attach the camera to a Video object in order to see what the
camera is capturing during the recording. To record a stream one calls ns.publish(“stream-name”,”record”). It is also possible to create a live stream, and in that case one would call ns.publish(stream-name, “live”);

    ns.publish("test","record");
    ns.attachAudio(mic);
    ns.attachCamera(cam);
    this.video.attachCamera(cam);

Step 5

To stop the recording just call:

  ns.close();

Step 6

To play what you have just recorded:

private function playRecording():void {
 this.ns.play("test");
        this.video.attachNetStream(ns);
}

It looks really easy doesn’t it? The hardest part is to configure the media server in the backend.




Source for Video recorder with Red5 example

P.S. Before you can try the example you need to change the rtmp url to point to your media server.

Add a combo box to a DataGrid with automatic sorting

Here I am posting a solution for a problem I had to solve for one of my projects. I needed to add a combo box to one of the columns in a DataGrid. Not only that, based on the value of the combo box, the elements in the DataGrid should re-order.
To add the combo box to one of the columns we need to set that column as editable and we need to add an item editor(in this case an inline item editor):

<mx:itemEditor>
    <mx:Component>
 <mx:ComboBox  editable="false" dataProvider="{outerDocument.sequenceNumbers}">
                        
 </mx:ComboBox>
    </mx:Component>
</mx:itemEditor>

To sort the data grid based on the column you need to apply a SortField to the
ArrayCollection that holds the elements of the DataGrid.

   /**
    * Sort list of questions by sequence
    */
   private function sortQuestions():void {
    var sort:Sort= new Sort();
       var sequence:SortField= new SortField("Sequence",false,false);
       sort.fields=[sequence];
       this.questions.sort=sort;
       this.questions.refresh();
   
   }

The full code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationComplete()">
 <mx:Script>
  <![CDATA[
   import mx.collections.Sort;
   import mx.collections.SortField;
   [Bindable]
   public var sequenceNumbers:ArrayCollection;
   
   /**
    * Prepare the data
    */
   private function creationComplete():void {
    this.initSequenceNumbers();
    this.sortQuestions();
   }
   
   /**
    * Sort list of questions by sequence
    */
   private function sortQuestions():void {
    var sort:Sort= new Sort();
       var sequence:SortField= new SortField("Sequence",false,false);
       sort.fields=[sequence];
       this.questions.sort=sort;
       this.questions.refresh();
   
   }
   
   /**
    * We initialize the sequence numbers taking into account the number of questions
    */ 
   private function initSequenceNumbers():void {
    this.sequenceNumbers= new ArrayCollection();
    for (var i:int=0; i<questions.length; i++ ) {
     sequenceNumbers.addItem(i+1);
    }
   }
  ]]>
 </mx:Script>
      <mx:DataGrid width="300" rowCount="4" editable="true">
             <mx:ArrayCollection id="questions">
           <mx:Object>
              <mx:Sequence>1</mx:Sequence>
              <mx:Question>Who is the queen of England?</mx:Question>
           </mx:Object>
           
               <mx:Object>
              <mx:Sequence>3</mx:Sequence>
              <mx:Question>Who is the king of pop?</mx:Question>
           </mx:Object>
           
           <mx:Object>
              <mx:Sequence>2</mx:Sequence>
              <mx:Question>Who is the king of Spain?</mx:Question>
           </mx:Object>
 
         </mx:ArrayCollection>
 
             <mx:columns>
                 <mx:DataGridColumn id="sequenceColumn" dataField="Sequence" headerText="Sequence" editable="true" editorDataField="value" sortable="false" >
               <mx:itemEditor >
                   <mx:Component>
                       <mx:ComboBox  editable="false" dataProvider="{outerDocument.sequenceNumbers}"  >
                        
                       </mx:ComboBox>
                   </mx:Component>
               </mx:itemEditor>
           </mx:DataGridColumn>
                 <mx:DataGridColumn dataField="Question" headerText="Question" editable="false" sortable="false"/>
             </mx:columns>
         </mx:DataGrid>
</mx:Application>



Click here to see the Combo box in a DataGrid example in action

Creating a countdown clock with Timer

Are you trying to find a quick and easy way of creating a countdown clock in Adobe Flex. Don’t look any further. I’ll go straight to the point:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationComplete()">
 <mx:Script>
 <![CDATA[
  import mx.controls.Alert;
  [Bindable]
  private var n_seconds_left:int=30;
  private var timer:Timer;
   
  /**
   * Initialises the timer
   */
  private function creationComplete():void {
  this.timer= new Timer(1000,n_seconds_left);
                      timer.addEventListener(TimerEvent.TIMER,decrementSeconds);   
  timer.start();
  }
   
  /**
   * Decrements the number of seconds left if it still is
   * bigger than 0. Otherwise stop the timer.
   * 
   */
  private function decrementSeconds(event:TimerEvent):void {
   n_seconds_left--;
  }
   
  ]]>
 </mx:Script>
 <mx:Label text="Final Countdown: {n_seconds_left}" fontSize="18"/>
</mx:Application>

The constructor for the Timer class in Adobe Flex takes two arguments:

  1. delay– Time interval in milliseconds for generating a TimerEvent. In our example, we set that value as 1000 milliseconds=1 second as you would expect for a clock.
  2. count – number of times that a TimerEvent will be generated before a TimerEvent.TIME_COMPLETE is generated. In our example it was 30. This means that our countdown clock only runs for 30 seconds. If you don’t specify this value the Timer will run forever and the TimerEvent.TIME_COMPLETE will never be dispatched

If we don’t specify the second argument when creating a Timer we still can achieve the same results:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationComplete()">
 <mx:Script>
  <![CDATA[
  import mx.controls.Alert;
  [Bindable]
  private var n_seconds_left:int=30;
  private var timer:Timer;
   
  /**
   * Initialises the timer
   */
  private function creationComplete():void {
   this.timer= new Timer(1000);
   timer.addEventListener(TimerEvent.TIMER, decrementSeconds); 
   timer.start();
  }
   
  /**
   * Decrements the number of seconds left if it still is
   * bigger than 0. Otherwise stop the timer.
   * 
   */
  private function decrementSeconds(event:TimerEvent):void {
     if (this.n_seconds_left>0) {
   n_seconds_left--;
     }
     else {
        timer.stop();
      }
  }
   
  ]]>
 </mx:Script>
 <mx:Label text="Final Countdown: {n_seconds_left}" fontSize="18"/>
</mx:Application>

The biggest difference to the previous code is that we use Timer.stop() to interrupt the timer to prevent another TimerEvent from being called so that our countdown clock doesn’t go below 0.


Click here to see our countdown clock in action

Adobe Flex with Struts 2 using HttpService

Using HttpService is the easiest way in which you can integrate Adobe Flex and Struts 2. As an example I will show you how you can create a registration form in Adobe Flex which calls a struts 2 action to create new users. Note that this example is very simple and for demonstration purposes. I am not adding any validation in flex and not even creating the users in a database. All I show you is how you can pass data between flex and struts.

First let me show you the steps you need to perform in Adobe Flex:

Step 1

Create the registration form in mxml:

<mx:Form label="Registration Form">
 <mx:FormHeading label="Registration Form">
 </mx:FormHeading>
 <mx:FormItem label="First Name">
  <mx:TextInput id="firstName">
  </mx:TextInput>
 </mx:FormItem>
 <mx:FormItem label="Last Name">
  <mx:TextInput id="lastName">
  </mx:TextInput>
 </mx:FormItem>
 <mx:FormItem label="Email">
   <mx:TextInput id="email">
  </mx:TextInput>
 </mx:FormItem>
 <mx:FormItem label="Username">
  <mx:TextInput id="username">
  </mx:TextInput>
 </mx:FormItem>
 <mx:FormItem label="Password">
  <mx:TextInput id="password" displayAsPassword="true">
  </mx:TextInput>
 </mx:FormItem>
 <mx:FormItem>
  <mx:Button label="Register" click="registerUser()"/>
 </mx:FormItem>
</mx:Form>

Step 2

Create the HttpService object:

<mx:HTTPService id="registerService" showBusyCursor="true" useProxy="false" url="register.action" resultFormat="e4x" method="POST" result="registerConfirmation(event)" fault="registerFailed(event)"/>
  • register.action is the Struts 2 action that registers the user
  • registerConfirmation(event) is the function that is called if the http service call is successful.
  • registerFailed(event) is the function that is called if an error occurs. For example if the server is down. The event object gives you access to any xml/html that might be returned upon the call of the action.
  • resultFormat specifies in which format you want to view the results. It can be text, xml or an object. There are 5 possible values for this field:
    • object – An XML object is returned and is parsed as a tree of ActionScript objects
    • xml – Returns literal XML in an XMLNode object
    • e4x – Returns literal XML that can be accessed using ECMAScript for XML(E4X) expressions.
    • flashvars – The result is text in flashvars format, value pairs separated by ampersands. Flex returns this result in an actionscript object
    • array – The result is XML that is returned in an Array even if there is only one top level node.

Step 3

Write the actionscript call to submit the form:

public function registerUser():void {
      var params:Object = { 'user.firstName': firstName.text,'user.lastName': lastName.text, 'user.email':email.text, 'user.password':password.text }; 
      this.registerService.send(params);
}

Step 4

Create registerConfirmation(). This method checks whether the registration was successful. We can know that by inspecting the XML that is returned.

private function registerConfirmation(event:ResultEvent):void {
        var xml:XML=XML(event.result); 
 if (xml != null && xml.item == true) {
  mx.controls.Alert.show("Registration Successful!");
 }
 else {
  mx.controls.Alert.show("The registration was not successful.");
 }
 }}

Step 5

If we can’t call the action on the server because of some networking issue we also should give some feedback to the user.

   
/**
 * Display a message to the user explaining what went wrong
 */
private function registerFailed(event:FaultEvent):void {
 mx.controls.Alert.show(event.fault.message);
}

Now let’s create our Struts 2 Action:

Step 1

Create RegisterAction.java

package uk.co.spltech.web.actions;

import uk.co.spltech.beans.User;

import com.opensymphony.xwork2.ActionSupport;

/**
 * Creates a new user
 * 
 * @author Armindo Cachada
 *
 */
public class RegisterAction extends ActionSupport {

 private User user;
 
 private Boolean success;
 
 public Boolean getSuccess() {
  return success;
 }

 public void setSuccess(Boolean success) {
  this.success = success;
 }

 public User getUser() {
  return user;
 }

 public void setUser(User user) {
  this.user = user;
 }

 /**
  * Registers a user
  * 
  * @return
  */
 public String register() {
  System.out.println("Checking user");
  if ( this.getUser()!= null) {
   User u = this.getUser();
   if (u.getEmail()!= null && !u.getEmail().equals("") && u.getPassword()!= null 
     && !u.getPassword().equals("") ) {
    System.out.println("Successfully registered user with email=" + u.getEmail());
    this.success=true;
   }
   else {
    this.success=false;
    System.out.println("Error registering user");
   }
  }
  else {
   this.success=false;
   System.out.println("Error registering user");
  }
  
  return SUCCESS;

 }
 
}

Step 2

Add action name=’register’ to struts.xml

<package name="user" extends="struts-default">
        <action name="register" method="register" class="uk.co.spltech.web.actions.RegisterAction">
           <result type="xslt">   <param name="exposedValue">{success}</param></result>
        </action>
</package>

Source for “Adobe Flex with Struts 2 using HttpService” Example


To compile this example you will need to copy the following libraries to the lib folder:

commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging.jar
freemarker-2.3.13.jar
ognl-2.6.11.jar
struts2-core-2.1.6.jar
xwork-2.1.2.jar
struts2-convention-plugin-2.1.6.jar

Integrating Adobe Flex with Struts 2

I have noticed a lot of people on the internet are searching for information on how to integrate Struts 2 with Adobe Flex. It is not as complicated as most think and there’s more than one way of doing it.

Ways in which you can integrate Adobe Flex and Struts:

1. Use HttpService in Adobe Flex to call actions in Struts. In Struts, instead of returning a jsp file change the return type of your action to XSLT. In this way the contents of your action are automatically converted to XML. You can use the XML result in Adobe Flex to determine the result of the action that you invoked using HttpService.
This technique is by far the easiest of the three.
The main advantages are:

  • It is quite simple to use compared to the other techniques
  • You get complete control on the information that you transfer between Adobe Flex and Struts

There are disadvantages though:

  • The more information you transfer between Flex and Struts the more code you have to write for parsing/converting/… data

You can easily use HttpService to register a user using a struts action or to authenticate a user. Or you can use HttpService to retrieve information from the database through struts. In my next post I will give you an example on how to implement a registration system using HttpService.

2. Use Soap Web Services

Use Soap WebServices to connect to the Struts 2 backend. If you use an EJB 3 compliant application server you can easily create a web service by adding the @WebService annotation to an EJB 3 bean interface.
If you don’t have an EJB 3 compliant application server we recommend you to use Apache Axis 2 or Enunciate. The advantage of Enunciate is that you can publish your service not only for use with SOAP, it also creates endpoints for REST, AMF and JSON. We will exemplify this approach in a later post.

The advantages of using Web Services are:

  • Automatic class generation: With a few mouse clicks and the WSDL that describes your web service, Flex generates all the classes needed to access your web service.
    This is done via the ported version of Apache Axis.
  • The conversion of data from/to XML is done automatically for you. You only deal with objects and method calls.

The major disadvantage of using web services are circular references. An example of a circular reference is one where the child node of an object references its parent.

A —-> B
B —-> A

You need to deal with this by using annotations or by manually deleting the circular reference. Otherwise you will get a nasty marshaling/unmarshaling exception when calling the web service.

3. Using BlazeDS, from Flex it is possible to invoke methods on java objects deployed in an application server. This is done using AMF a message protocol developed by Adobe. This is a similar method to using SOAP. The only difference is that all the information is transferred in binary format. Performance wise this is probably the best option available to integrate Java/J2EE and Adobe Flex. Read my post on Integrate Adobe Flex and JBOSS using BlazeDS for more information.