Showing posts with label flex 3. Show all posts
Showing posts with label flex 3. Show all posts

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!

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

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

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.

Thursday, June 25, 2009

Adding an event listener function with arguments using Actionscript

This might come handy whenever you can't use directly mxml and you need to add an event listener function that needs one or more arguments.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="myInitialize()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;

private function myFunction(arg:String):void {
mx.controls.Alert.show("Received call with argument=" + arg);
}

private function myInitialize():void {
myButton.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void{
var someArg:String="an_argument";
myFunction(someArg);
});
}
]]>
</mx:Script>


<mx:Button id="myButton" label="Click me!"/>
</mx:Application>


See this code in action here

Wednesday, June 24, 2009

Adobe Flex 3 UI Components Lifecycle

In adobe flex 3 there are certain events that are called when a component is created.
These events are raised in the following order:

1) preInitialize: This event is raised when the component has just been created but none of the child components exist.

2) initialize: This event is raised after the component and all its children have been created but before any dimensions have been calculated.

3) creationComplete: This even is dispatched after all the component and its children have been created and after all the layout calculations have been performed.

4) applicationComplete: Dispatched after all the components of an application have been successfully created

Events 1) to 3) are dispatched in the order mentioned above for all visible components.
Note however that for components that are not visible on the screen by default, none of these events will be raised. This is because depending on the creation policy the hidden components might not exist yet.
For example in a TabNavigator only the components that are inside the default tab are created because they are visible. If you do change to another non-visible tab then Flex creates the components one by one. In that case the events mentioned above are raised.

We have created a simple example to demonstrate this. The DataGrid shows you a list of the events that have been raised during the lifecycle of the main application window. If you change to the second tab you will see additional entries in the list due to the creation of a Label UI component.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" preinitialize="preInitialise()" initialize="initialise()" applicationComplete="applicationComplete()" creationComplete="creationComplete()" viewSourceURL="srcview/index.html">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;

[Bindable]
private var eventsCalled:ArrayCollection=new ArrayCollection();

public function preInitialise():void {
eventsCalled.addItem({label:"preInitialise called",event:"preInitialise"});
}

public function initialise():void {
eventsCalled.addItem({label:"initialise called",event:"initialise"});
}

public function creationComplete():void {
eventsCalled.addItem({label:"creation complete called",event:"creationComplete"});
}


public function applicationComplete():void {
eventsCalled.addItem("applicationComplete called");
}

]]>
</mx:Script>
<mx:TabNavigator width="400" height="400">
<mx:Canvas label="tab1">
<mx:DataGrid id="datagrid" dataProvider="{eventsCalled}" top="10" left="10" width="300" />
</mx:Canvas>
<mx:Canvas label="tab2">
<mx:Label text="This label is created only when it is displayed" creationComplete="creationComplete();" preinitialize="preInitialise();" initialize="initialise();" />
</mx:Canvas>

</mx:TabNavigator>
</mx:Application>


To see this example in action click: here

You can change this behavior by setting the creationPolicy attribute, for example in the application mxml node. This attribute is only valid for containers.

There are 4 possible values for this attribute:

1) creationPolicy="auto" - the container delays creating some or all of its descendants until they are needed. This is known as deferred instantiation

2) creationPolicy="all" - the container immediately creates all its descendants even if they are not selected.

3) creationPolicy="queued" - all components inside a container are added to a creation queue. The application waits until all children of a container are created before moving to the next container.

4. creationPolicy="none" - all components inside a container are never created. Whoever decides to go with this strategy needs to manually create all items inside a container.

For example to change the behavior seen above we could set the creationPolicy="all":


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationPolicy="all" preinitialize="preInitialise()" initialize="initialise()" applicationComplete="applicationComplete()" creationComplete="creationComplete()" viewSourceURL="srcview/index.html">
...
</mx:Application>
 
Software