Sunday, 24 May 2009

Flex Remoting on Google App Engine

I'm not personally related to Adobe, Google nor Sun but I like to code in Java, I am happy to see what Adobe filling the gap which Sun left years ago with applets. Java is the perfect choice to use on Google App Engine. So can Flex also be a good choice to use with both? Last episode we let Anakin meet Obi Wan Kenobi, now time to see how they do together in harder missions. Lets dive deeper and see...

I assume you have basic knowledge about GAE and its eclipse plugin, if not go back to the previous article and do some coding because this part will be tough. I also assume you know what is Flex (or at least RIA) and what does it offer else you can do this tutorial with any other web framework and still achieve what we will.

Last article we managed to code a very basic servlet which returns and receives xml from our Flex client which had hard coded tags as strings. Of course in real world you wouldn't want this and probably use xstream or any other parser to convert our objects to xml but wouldn't it be great to call Java backend from our flex client with remoting and using objects without xml serilization. Well this episode we are going to build some spring beans on GAE and make them available as BlazeDS remoting for our Flex client.

Again if you didn't try the previous post or not comfortable with GAE go and try it.
Lets make a Head First style intro, our boss and clients were happy with the phonebook project we built in last part but soon they will be demanding better performance and more functionality so lets refactor our previous project and turn it into a more sophisticated one.
Create a new GAE project just like the previous one this time lets name it SecondProject.

Again the plugin created an example for us, lets forget about them and start with our entity. Create a Java class under org.flexjava.server package.
package org.flexjava.server;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

public class Entry {
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
Long id;

private String name;

private String phone;

public Long getId() {
return id;
public void setId(Long id) { = id;
//getters setters

Create a new interface FlexService under org.flexjava.server package with following method declarations.

package org.flexjava.server;

import java.util.List;

public interface FlexService {
public boolean addEntry(Entry entry);
public List <Entry> getEntryList();

This two methods will be enough to achieve our goal. Now under the same package create FlexServiceImpl class and add the methods with the knowledge we gained from our previous application.

package org.flexjava.server;

import java.util.List;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.annotations.Transactional;

public class FlexServiceImpl implements FlexService {
//persistance manager
private static final PersistenceManagerFactory pmfInstance = JDOHelper
PersistenceManager persistenceManager;

public boolean addEntry(Entry entry) {
try {
//check if the id is 0 which is same as null
if (entry.getId().intValue()==0){
//get manager
persistenceManager = pmfInstance.getPersistenceManager();
//save our entry
return true;
} catch (Exception e) {
return false;

public List<Entry> getEntryList() {
//get persistance manager
persistenceManager = pmfInstance.getPersistenceManager();
//our query which is a select * in this case
String query = "select from " + Entry.class.getName();
//return the result
return (List<Entry>) persistenceManager.newQuery(query).execute();

Compared to the last tutorial our server side code is much more simpler. Before going into dungeons of configuration files lets code the flex end. Click on the project and add Flex nature. Do not forget to change the output folder to “war” folder of the project. To use remoting we need the ActionScript counterpart of our Entry object. Create a new ActionScript object under org.flexjava.client package.

package org.flexjava.client
public class Entry
public var id:int;
public var name:String;
public var phone:String;
public function Entry()


The remote class alias must be pointing exactly to your Java object. Since we done this we are ready to finish our Flex client. It will be very similar to the previous phonebook application.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="" layout="absolute" initialize="init()">
<mx:TextInput x="114" y="20" id="nameTxt"/>
<mx:TextInput x="114" y="60" id="phoneTxt"/>
<mx:Label x="29" y="22" text="Name"/>
<mx:Label x="29" y="62" text="Phone"/>
<mx:Button x="332" y="60" label="Save" click="saveEntry()"/>
<mx:DataGrid id="grid" x="29" y="138" dataProvider="{phonebook}">
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Phone" dataField="phone"/>
<mx:DataGridColumn headerText="Record Id" dataField="id"/>
<mx:RemoteObject id="ro" result="showEntryList(event)" destination="FlexDestination" endpoint="http://localhost:8080/messagebroker/amf"/>
import mx.binding.utils.BindingUtils;
import org.flexjava.client.Entry;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
public var phonebook:ArrayCollection;

public function init():void{
public function saveEntry():void{
var entry:Entry=new Entry();;;
public function showEntryList(event:ResultEvent):void{
if (event.result!=null){
if (event.result==false){"record could not be added");
}else if (event.result==true){"added to your phone book");
phonebook=event.result as ArrayCollection;

This way the Flex client looks simpler too. We are done with coding and it was still quite easy. Lets do the spring and blaze configuration. If you ever googled Flex-Java and Blaze you probably ended up at Christophe Coenraets blog. He was one of first people I heard and learned flex from. He offers great examples and a zipped and configured tomcat with everything necessary (from blaze, activemq, database, spring etc..). Spring source also offers a great documentation about Spring-Blaze integration. We will definitely need this two to continue.

Locate web.xml under war\WEB-INF folder and add the following inside the web-app tags.

 <!-- Spring -->



Now create a webAppContext.xml next to web.xml.

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

default-channels="my-streaming-amf,my-longpolling-amf,my-polling-amf" />
<!-- <flex:secured /> -->

<bean id="flexBean" class="org.flexjava.server.FlexServiceImpl"/>
<!-- Expose the productDAO bean for BlazeDS remoting -->
<flex:remoting-destination destination-id="FlexDestination" ref="flexBean" />


This will make our FlexServiceImpl class available a Spring bean called flexBean. Next we enable this spring bean as a blaze remoting destination with the id of FlexDestination. FlexDestination will be the name exposed to outer world to call our service class with remoting.

Now create a folder named flex under WEB-INF and add the following four flex xml configuration files. Those files are quite standart so if you had downloaded Christophe's example or got them any other way, you may just copy those files instead of creating.

Finally the jar list. Actually I just copy the jars Christophe's server, I know most of the jars we won't be using (specially database one) but still I took them all to be able to add new functionality to my project.

So far we did everything as we are instructed so we expect everything to run smoothly. Right click and run your project as Web Application.

"Channel.Connect.Failed error NetConnection.Call.Failed: HTTP: Status 500: url: 'http://localhost:8080/messagebroker/amf'"
Ok, we weren't expecting this but if we check our server logs we will notice a clue;
WARNING: /messagebroker/amf
java.lang.RuntimeException: Session support is not enabled in appengine-web.xml. To enable sessions, put true in that file. Without it, getSession() is allowed, but manipulation of sessionattributes is not.

Great! Google even tells us what to do, this is what I expect from a framework. Open the appengine-web.xml file and add ”true” just before the system-parameters tag. Lets re run the server and our application works! Well not that hard, actually it is time to deploy our code in to the Google Cloud and see it working there.
First goto your SecondProject.mxml file and change the endpoint value with your app url(in mine; endpoint=""). Click the Deploy App Engine project button, and enter your email and password. Of course if you don't have an GAE account first create one.

The plugin recompiles and deploys our project. Now open a browser and type your url. Ok this was the first real suprise GAE introduced to me. So far GAE offered a reliable and stable development and production environment but now we face an error which we can not reproduce in our development environment “flex.messaging.request.DuplicateSessionDetected “.
When I search for this error I found another good resource. In this post Martin tells us about the problem and how he solved by editing flex-messaging-core.jar. This incident cools down my excitement about GAE/Flex but still you can see how important it is to work with open source frameworks. I asked Martin to send me his custom jar and (thanks to him) I included the jar in the project export. Besides the custom jar file, go to services-config.xml and add "<manageable>false</manageable>" just after the system tag.
Feel lost? Do not.. GAE Java is just in the early stage and even getting to this point with even Flex which is totally out of Java environment is still a great success. As long as we have the opened source we will have solutions like Martin Zoldano's.
I remember reading the following on Yakov Fain's blog;
“99% of the people who reject using the software until it gets open sourced, neither plan nor will look at its source code. “

I agree most people do not look at the source code even if they need but I post a comment saying;
“Well probably same amount of people who buy cars equipped with airbags also don'use the airbags (so far i didn't) but it can be very helpful if you are in need “.

So when choosing your car don't forget to get a one with airbags even if you feel you don't need them.

1 comment: