Monday, August 3, 2009

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 read the next part of this tutorial

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

Monday, June 29, 2009

Configuring JBOSS to support UTF-8 characters in the URL

The problem I have experienced this week. When I have chinese characters as part of the URL, the characters show up as garbage in the page. I mean request.getParameter("chineseCharacter") returns garbage characters. This problem happened in JBOSS 4.2.3 GA with Apache 2.0(mod_jk).

Fortunately the solution is simple:

Edit JBOSS_HOME/server/${SERVER_NAME}/deploy/jboss-web.deployer/server.xml

Add URIEnconding="UTF-8" to the HTTP connector and AJP connector:


<Connector port="8080" address="${jboss.bind.address}"
maxThreads="250" maxHttpHeaderSize="8192"
emptySessionPath="true" protocol="HTTP/1.1"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8"/>

<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" address="${jboss.bind.address}" protocol="AJP/1.3"
emptySessionPath="true" enableLookups="false" redirectPort="8443" URIEncoding="UTF-8"/>

Now restart your server and you should have no more problems with having non-latin characters in the URL.

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>

Sunday, June 21, 2009

SEO Urls/Hierarchical Actions with struts 2.1

I have added a working struts 2.1 project that gives you a working example on how to create SEO optimised urls for struts 2.1. You can find the previous post here.

Monday, June 15, 2009

Minifying CSS and JS with Yahoo YUI Compressor

In my previous blog post I explained how to use Ant to concatenate javascript and css files in a way to minimize the number of http requests.
Another recommendation by yahoofor building high performance websites is to minify JS and CSS files. The reasoning is that the smaller the size of the javascript/css, the less time it takes for them to be interpreted.

Yahoo provides a great utility - yahoo yui compressor that minifies both javascript and css.

We can therefore improve our build script and add the following task:


<!-- this compresses all the css and js in the static folder -->
<target name="js.minify">
<property
name="yui-compressor.jar"
location="lib/yuicompressor-2.4.2.jar" />
<property
name="yui-compressor-ant-task.jar"
location="lib/yui-compressor-ant-task-0.3.jar" />

<path id="task.classpath">
<pathelement location="${yui-compressor.jar}" />
<pathelement location="${yui-compressor-ant-task.jar}" />
</path>

<taskdef
name="yui-compressor"
classname="net.noha.tools.ant.yuicompressor.tasks.YuiCompressorTask">

<classpath refid="task.classpath"/>
</taskdef>

<yui-compressor warn="false" charset="UTF-8" jsSuffix="-min.js" cssSuffix="-min.css" fromdir="${build.dir}/static" todir="${build.dir}/static">
<include name="**/*.js" />
<include name="**/*.css" />
</yui-compressor>


<move todir="${build.dir}/static" includeemptydirs="false">
<fileset dir="${build.dir}/static">
<include name="**/*-min.css"/>
</fileset>
<mapper type="glob" from="*-min.css" to="*.css"/>
</move>
<move todir="${build.dir}/static" includeemptydirs="false">
<fileset dir="${build.dir}/static">
<include name="**/*-min.js"/>
</fileset>
<mapper type="glob" from="*-min.js" to="*.js"/>
</move>

</target>


First we copy all the javascript and css files to the build/static folder and then we use yahoo compressor to minify all the files in this directory.

Click here to download an example.

Sunday, June 14, 2009

Minimizing number of http requests by concatenating all the CSS and Javascript files

If you have installed yslow in your browser you will know all about yahoo's high performance rules for a website. One of the most important rules is to minimize the number of http requests. There are several ways of doing that. I will cover one of them in this post - minimizing the number of http requests by concatenating all the javascript files and css files into two big files.

Apache Ant makes the task of concatenating files together extremely easy by using concat.

<concat destfile="${build.dir}/concatenated.js">
<filelist dir="${src.dir}/js"
files="one.js, two.js"/>
</concat>


This is a simple solution but I chose not to use it for the following reasons:

1. I don't always want every single javascript/css to be included for all pages.
You could create multiple concatenated files with different combinations but that would be too messy.

2. We are creating a dependency between the jsps and the ant build script. Do you really want to do that?

3. Javascript, css can be notoriously difficult to debug, so for development purposes
it is useful not to do any concatenation.

Ant has a neat feature that allows to do string replacement on any file by using a filterset.

<copy file="${build.dir}/version.txt" toFile="${dist.dir}/version.txt">
<filterset>
<filter token="DATE" value="whatever"/>
</filterset>
</copy>

You can specify the string that you want to be replaced at build time by surrounding it with ampersands. So in the template jsps instead of including javascripts/css in the normal way, I did the following:

@IncludeCSS css/file1.css css/file2.css ...@
...
@IncludeJS js/jquery.js js/thickbox.js js/vmSlider.js js/blockUI.js@


Then I created the following ant task:

<ExtendedFileTransform concatenate="true" propertiesfile="${build.dir}/static.mapping.properties" >
<jspfileset refid="jspFileset">
</jspfileset>
<staticfileset dir="${static_content.dir}">
<include name="**/*.js" />
<include name="**/*.css" />
<include name="**/*.png" />
<include name="**/*.jpg" />
<include name="**/*.jpeg" />
<include name="**/*.gif" />
<include name="**/*.PNG" />
<include name="**/*.JPG" />
<include name="**/*.GIF" />
</staticfileset>
</ExtendedFileTransform>
ExtendedFileTransform is a custom task I created, based on Julien Lecombte's File Transform.
This custom task inspects all the jsps and searches for javascript(IncludeJS) and css includes(IncludeCSS). If concatenated="true" we concatenate the files specified within the IncludeXXX directory and we replace it with a valid html javascript/css include to the generated files. If concatenated="false", i.e. for development, there is no concatenation and the IncludeXXX directory is replaced with an include for each javascript/css file.

The full ant target that you could use for production looks like this:


<target name="-copy.static.files-prod">
<taskdef name="ExtendedFileTransform" classname="uk.co.simpletech.ant.ExtendedFileTransform" classpath="${build.dir}/classes" />

<mkdir dir="${build.dir}/staticpre" />

<!-- we copy all jsp files to a temporary location -->
<copy todir="${build.dir}/jsppre">
<fileset dir="jsp" includes="**/*" />
</copy>

<fileset dir="${build.dir}/jsppre" id="jspFileset">
<include name="**/*.jsp" />
</fileset>
<!-- we concatenate the files together -->

<ExtendedFileTransform concatenate="true">
<jspfileset refid="jspFileset">
</jspfileset>
<staticfileset dir="${build.dir}/static">
<include name="**/*.js" />
<include name="**/*.css" />
</staticfileset>
</ExtendedFileTransform>



<delete dir="${build.dir}/jsppre" />=
</target>

Here is an example project where you can see the css/js concatenation in action.

Case insensitive search in hibernate

It is very simple to do case insensitive search in hibernate.
Here is an example HQL query:


Query q = this.entityManager.createQuery("SELECT * FROM User u where lower(u.firstName)=:firstName");
q.setParameter("firstName", firstName.toLowerCase());


In this case lower() will convert the firstName property to lower case allowing you to do case insensitive search.

Saturday, June 13, 2009

Creating hierarchical actions in struts 2.1

Struts 2.1 doesn't directly support hierarchical actions. Nonetheless I still was able to implement them at visualmandarin.
Notice how the podcasts and exercises urls are all organized into folders and even the lesson title is present in the url: Lesson - Can I have a menu please?

If you are interested in SEO optimized urls for your website this kind of feature is a MUST. But how to do it struts 2.1? In short the steps you need to follow are:

Step 1

If you are running on struts 2, migrate to struts 2.1

Step 2

Make sure you are using the convention plugin

Step 3

Ensure that all your actions have an explicit namespace. If you don't you might find that those actions are being called when they shouldn't.

Step 4

Create a wildcard action in the namespace that you want to be hierarchical. In my case I have created one in namespace /lessons:


<action name="*" namespace="/lessons" method="execute" class="lessonsLocator">
<result name="lister"></result>
<result name="ResourceNotFoundException" type="chain">404</result>
</action>



Your lessons locator action should inspect the uri to determine which resource to display. In my case I was dealing with lessons but you could be dealing with categories and products or anything else. It shouldn't make any difference.

Step 5

Extend org.struts2.impl.StrutsActionProxy and override the following prepare() method:

@Override
protected void prepare() {
String profileKey = "create DefaultActionProxy: ";
try {
UtilTimerStack.push(profileKey);
// we backtrack the namespace until we find an action that matches
this.findActionByBacktracking();

if (config == null && unknownHandler != null) {
config = unknownHandler.handleUnknownAction(namespace, actionName);
}
if (config == null) {
String message;

if ((namespace != null) && (namespace.trim().length() > 0)) {
message = LocalizedTextUtil.findDefaultText(XWorkMessages.MISSING_PACKAGE_ACTION_EXCEPTION, Locale.getDefault(), new String[]{
namespace, actionName
});
} else {
message = LocalizedTextUtil.findDefaultText(XWorkMessages.MISSING_ACTION_EXCEPTION, Locale.getDefault(), new String[]{
actionName
});
}
throw new ConfigurationException(message);
}

resolveMethod();

if (!config.isAllowedMethod(method)) {
throw new ConfigurationException("Invalid method: "+method+" for action "+actionName);
}

invocation.init(this);

} finally {
UtilTimerStack.pop(profileKey);
}
}

/**
* Returns a list of all possible namespaces. The one with biggest length
* is top of the list up to /xxx... bottom of a list. Note that we don't backtrack until
* the empty namespace
*
* @param namespace
* @return
*/
private String [] getAllPossibleNamespaces(String namespace) {
List<String> namespaces = new ArrayList<String>();
// e.g. /lessons/hsk/.../1 ->
String [] tokens = namespace.split("/");
tokens=removeEmptyStrings(tokens);
if (tokens != null && tokens.length >= 0) {
for (int i=0; i< tokens.length; i ++) {
String gnamespace="";
for (int j=0;j<tokens.length- i;j++) {
gnamespace += "/" + tokens[j] ;
}
namespaces.add(gnamespace);
}
}
return namespaces.toArray(new String[0]);
}

private String [] removeEmptyStrings(String [] tokens) {
List<String> result = new ArrayList();
for (String token: tokens) {
if (token == null || token.equals("")) {

}
else {
result.add(token);
}
}
return result.toArray(new String[0]);
}

/**
* Searches for the given action in one or more namespaces
*
*/
private void findActionByBacktracking() {
if (namespace != null && !namespace.equals("") && !namespace.equals("/")) {
String [] namespaces =this.getAllPossibleNamespaces(namespace);

for (String namespace: namespaces) {

config = configuration.getRuntimeConfiguration().getActionConfig(namespace, actionName);

if (config != null ) break;
}

}
else {
config = configuration.getRuntimeConfiguration().getActionConfig(namespace, actionName);
}

}



Step 6

Extend org.apache.struts2.impl.StrutsActionProxyFactory.

My implementation as an example:

public class HierarchicalActionProxyFactory extends DefaultActionProxyFactory {
@Override
public ActionProxy createActionProxy(ActionInvocation inv, String namespace, String actionName, String methodName, boolean executeResult, boolean cleanupContext) {

HierarchicalActionProxy proxy = new HierarchicalActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);
container.inject(proxy);
proxy.prepare();
return proxy;
}
}


Step 7

Finally the last step: override the property struts.actionProxyFactory
in struts.properties and point to your implementation of the proxy factory.

My implementation was:

struts.actionProxyFactory=com.visualmandarin.web.config.HierarchicalActionProxyFactory


If you have followed these steps correctly you should be able to have the same kind of urls that I have in visualmandarin.com website. If there's something that you don't understand don't hesitate to ask!

You can find a working example here. This war file was tested in jboss 4.2.3 but should work in any compliant application server.

What you need to get this example working:

  • Add the struts 2 library files to the lib directory

  • Add the convention plugin jar file to the lib directory

  • Specify the correct path to your application server

Once you build the war file and deploy it, you can access the example at http://localhost/example3 or http://localhost:8080/example3
 
Software