Thursday, July 30, 2009

Adobe Flex: 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.

Friday, July 24, 2009

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!

Sunday, July 19, 2009

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

Monday, July 13, 2009

Adobe Flex: 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

Adobe Flex: How to apply effects to components inside containers with automated layout

In this tutorial I will explain how to apply a tween effect to a component inside a container with automated layout.

Containers like VBox, HBox, Panel(except for layout=absolute), Grid, ... automatically position items for you.

Lets try to apply a Move effect to a Button inside a VBox:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" height="500" width="500">
<mx:Script>
<![CDATA[
/**
* This method runs an effect on a button to move it
* to the right side.
*
*/
public function moveButton(button:Button):void {
this.moveEffect.target= button;
this.moveEffect.play();
}
]]>
</mx:Script>
<mx:VBox id="box" clipContent="false" backgroundAlpha="1" backgroundColor="red">
<mx:Button id="button1" label="Button 1" click="moveButton(button1)"/>
<mx:Button id="button2" label="Button 2" click="moveButton(button2)"/>
<mx:Button id="button3" label="Button 3" click="moveButton(button3)"/>
</mx:VBox>
<mx:Sequence id="moveEffect">
<mx:Move duration="5000" xBy="300" yBy="300"/>
<mx:Move duration="5000" xBy="-300" yBy="-300"/>
</mx:Sequence>
</mx:Application>

Click here to run our example

In the example above we set clipContent to false to enable the button to be visible outside the VBox container after it moves.

To start the move effect you need to click in one of the buttons. You will then see the button you clicked move to the right bottom corner and then return to its original position. This example is not completely correct, but it works for this simple example.

To understand why it might not work lets add a Resize effect to the VBox to go along with the button Move effect:

<mx:Parallel id="moveEffect">
<mx:Sequence>
<mx:Move duration="5000" xBy="300" yBy="300"/>
<mx:Move duration="5000" xBy="-300" yBy="-300"/>
</mx:Sequence>
<mx:Sequence>
<mx:Resize target="{box}" duration="5000" heightBy="300" widthBy="300"/>
<mx:Resize target="{box}" duration="5000" heightBy="-300" widthBy="-300"/>
</mx:Sequence>
</mx:Parallel>

At the same time that we move the button to the right bottom corner and then back to its origin, we also increase the size of the VBox and then decrease it back to its original size. Note here the use of Sequence and Parallel. These two effects allow us to run a list of child effects in sequence or in parallel as you probably guessed.

Click here to try the example above

Did you notice anything wrong with the example above? Now the Move effect doens't work anymore. This is because every time we change the size of the VBox, Flex needs to re-position the items inside the VBox. Because of this the x and y values of the button are re-calculated thus ruining our Move effect.
The solution to this problem is to set autoLayout="false" immediately before the start of the effect:

<mx:VBox id="box" clipContent="false" backgroundAlpha="1" backgroundColor="red">
<mx:Button id="button1" label="Button 1" click="moveButton(button1)"/>
<mx:Button id="button2" label="Button 2" click="moveButton(button2)"/>
<mx:Button id="button3" label="Button 3" click="moveButton(button3)"/>
</mx:VBox>

Click here to see the full working solution in action

Thursday, July 9, 2009

Adobe Flex: 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.

Adobe Flex: Add a combo box to a DataGrid that re-orders its elements

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

Adobe Flex: 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

Sunday, July 5, 2009

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

Saturday, July 4, 2009

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.

Thursday, July 2, 2009

Flex 3: Sorting an ArrayCollection using SortField

You can use ArrayCollection and SortField to sort a list of items based on one or more fields:


this.names= new ArrayCollection();
names.addItem({first:"John",last:"Travolta"});
names.addItem({first:"Miguel",last:"Nunes"});
names.addItem({first:"Christina",last:"Aguilera"});
names.addItem({first:"Michael",last:"Jackson"});
var sort:Sort= new Sort();
sort.fields=[new SortField("last",true,true), new SortField("first",true,true)];
names.sort=sort;
names.refresh();


You can try the adobe flex example here. View source is enabled.

Wednesday, July 1, 2009

Uploading a file with Flex 3 and Struts 2

In my previous post I taught you how to upload a file using Struts 2. In the example I gave you, both the presentation layer and the code that received the file were done in Struts 2.
But what if you want to upload a file via Adobe Flex? How can you do it?

The FileReference flex class allows you to upload files from a client to a server. In our case a server running Struts 2. FileReference shows a dialog box that allows the user to select which file to upload.
Enough of theory. Below is an example of the code that you can use to upload a file to a server running struts 2:

Step 1

First you need to create the dialog box that will allow the user to select a file to upload by clicking the button "Browse".


<mx:VBox width="100%" left="10" top="10" >
<mx:HBox>
<mx:Label text="Image to upload:"/> <mx:TextInput disabledColor="black" enabled="false" id="fileName" width="200" />
<mx:Button width="80" label="Browse" click="browseFiles()" />
</mx:HBox>
<mx:Button id="uploadButton" label="Upload" enabled="false" click="upload()"/>
<mx:ProgressBar labelPlacement="center" source="{fileRef}" label="%3%%" minimum="0" maximum="100" color="blue" height="13" width="100" id="progressBar" visible="false" includeInLayout="false" />

</mx:VBox>


Step 2

Create an object of type FileReference and add event listeners to track progress of the upload:


fileRef = new FileReference();
fileRef.addEventListener(Event.COMPLETE, completeEvent);
fileRef.addEventListener(Event.SELECT, selectEvent);
fileRef.addEventListener(IOErrorEvent.IO_ERROR, showError);
fileRef.addEventListener(ProgressEvent.PROGRESS, progressEvent);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, showError);


Step 3

Write the actionscript code that opens a dialog that calls the native "Open File Dialog" in the user's operating system.


private function browseFiles():void {
var validFiles:Array= new Array(new FileFilter("Images (*.jpg,*.png,*.gif,*.jpeg)", "*.jpg;*.png;*.gif;*.jpeg"));
this.fileRef.browse(validFiles);
}


Step 4

Write the actionscript code that uploads the file to the server.
In our previous example the struts 2 action for the upload is "/fileUpload".
Therefore we use the following url to upload the file: ${baseUrl}/fileUpload

/**
* Uploads a file to the server
*
*/
private function upload():void {
mx.controls.Alert.show("Starting upload.");
var sendVars:URLVariables;
var request:URLRequest;
sendVars = new URLVariables();
request = new URLRequest();
request.data = sendVars;
request.url =baseUrl + "/fileUpload";
request.method = URLRequestMethod.POST;
fileRef.upload(request,"file",false);
}


You can find sample code to upload a file here. Note however that
the example only works with a server to receive the file.

Uploading a file with Struts 2

Uploading a file with Struts 2 is really simple with the help of the FileUploadInterceptor. The steps required to upload a file using Struts 2 are:

Step 1

Create the Struts 2 Action class. In our example we have called it FileUploadAction.java

An example of an action to upload a file:


package uk.co.spltech.web.actions;

import com.opensymphony.xwork2.Action;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


/**
* Uploads a file using Struts 2
*
* @author Armindo Cachada
*/
public class FileUploadAction extends ActionSupport {
private static final long serialVersionUID = 12323232L;
private File file;
private String fileFileName;
private String fileContentType;


public String execute() {

return Action.SUCCESS;
}

public File getFile() {
return this.file;
}

public void setFile(File file) {
this.file = file;
}

public void setUpload(File file) {
this.file = file;
}
/**
* This method is called by the action.
* Here you can do whatever you want with the uploaded file
*/
public String upload() throws IOException {
File uploadedFile =this.getFile();
// you can do whatever you want with the file
return Action.SUCCESS;
}


public String getFileFileName() {
return fileFileName;
}

public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}

public String getFileContentType() {
return fileContentType;
}

public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}

public String getFileUrl() {
return fileUrl;
}

public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
}


Step 2

Create the action in struts.xml


<action name="fileUpload" class="uk.co.spltech.web.actions.FileUploadAction" method="upload">
<result>/success.jsp </result>
<result type="error">/upload.jsp</result>
</action>


Step 3

Create the jsp. For example:


Please select the file you want to upload:

<s:form action="fileUpload" method="post" enctype="multipart/form-data" theme="simple">
<s:actionerror cssClass="errorMessage"/>
<s:fielderror cssClass="error"/>
<s:file name="upload" label="File"/>
<s:submit/>
</s:form>


Step 3

The default maximum file size that struts 2 allows you to upload is only 2 megabytes. You can increase this size by specifying in struts.properties the struts.multipart.maxSize. This value is in bytes.
For example:

struts.multipart.maxSize=20480


Finally you can download the code for this example here.

Note that I didn't include the required struts2 library files with the example.
The files you need are:

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

Click here to learn how to upload a file with Adobe Flex
 
Software