Flex Meets Google App Engine

DZone 's Guide to

Flex Meets Google App Engine

· Java Zone ·
Free Resource

Adobe did a very good job with Flex and they are far ahead of their rivals in RIA area. Meanwhile Google is doing great with several Java projects (such as Guice, GWT) and bringing Java support to Google App Engine. Actually Google even has an open source Flex component library called flexLib.

Java on Google App Engine is a very important step. Since I graduated I've heard most of friends bringing up ideas but not trying to build them, mostly because of the costs of Java hosting. Java is a elegant and sophisticated platform which is fun to work on but never offers cheap and easy hosting alternatives like PHP. Google App Engine can finally change this. It offers zero cost startup, flexible payment options as your project grows and also provides a very easy development environment. All you need is just to install the Eclipse plugin and start coding. Even when a new GAE project is created, a basic GWT example is already included.

I really like the scene where Obi-wan Kenobi meets Anakin Skywalker in Episode I. Qui-Gon introduces Anakin and says “Anakin Skywalker meet Obi-Wan Kenobi”. It is an important scene bringing two different people together for a very long time. This post will be an introduction of Flex to Google App Engine. Two great but totally different worlds. We will build a very basic servlet to feed data to our Flex application, and use Google's datastore to easily persist the data. Before starting the tutorial I assume GAE plugin and Flex builder plugin is already installed to your Eclipse instance.
You must have noticed the new three buttons on toolbar. Just click the “New Web Application Project”.

Next give a package and project name.

You must have noticed the wizard already added GreetingService, GreetingServiceImpl and a GWT class with the name of your project (in this case “FirstProject”). This is a good start especially for starting GWT but not useful for us. Just leave them there and open web.xml file under war/WEB-INF and add a servlet description.

We are ready to create a servlet to feed our Flex Client. Right click org.flexjava.server package and add a new class file extending HttpServlet as shown below.

Now its time to design our backend service. I don't really like hello world projects so even if we are coding a basic project lets find a real (but still basic) phonebook project worth to code. For the basic functionality we need retrieve the list of the contacts stored in the datastore and we also need to add new ones.

We need an Entity for our contacts. Lets create a new Class named Entry and add the annotations to make our Entry class persistance capable.


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) {
this.id = id;
// Add all getter/setters...

GAE's datastore is quite easy to use. Just create a persistanceManager and use makePersistant or newQuery methods to save or retrieve data.

PersistenceManager persistenceManager = pmfInstance.getPersistenceManager();

Lets start coding our servlet using those.

package org.flexjava.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FlexServiceImpl extends HttpServlet {
private static final PersistenceManagerFactory pmfInstance = JDOHelper.getPersistenceManagerFactory("transactions-optional");

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//PrintWriter to return and receive data from flex client
PrintWriter writer=resp.getWriter();
PersistenceManager persistenceManager = pmfInstance.getPersistenceManager();
//reading parameters from http request
String operation = req.getParameter("operation");
String name = req.getParameter("name");
String phone = req.getParameter("phone");
//if adding new contact is requested
if (operation.equalsIgnoreCase("save")){
Entry entry=new Entry();
//if retrieving all contact list is requested
}else if (operation.equalsIgnoreCase("get")){
//Query to retrieve all Entry data
String query = "select from " + Entry.class.getName();
List entries = (List) persistenceManager.newQuery(query).execute();
for (Entry entry : entries) {

Our GAE code is ready, now we can move on to Flex. To enable our project Flex compatible, right click project and select add Flex Project Nature.

Click next to continue.

Select war folder as the output folder so the build files will be deployed to server.

Since we just added Flex nature and created a mxml file, Flex Builder finds it confusing to prepare the HTML wrapper files for the SWF build. To make Flex builder's life easier go to errors tab, right click the error and select recreate HTML Templated. If there are no errors just skip this and continue.

Now we are free to design our own user interface. Switch to design view drag and drop 2 labels, 2 text boxes, a button and a datagrid component.

Now we can switch to source mode to code. We are going to use very little coding, most of the work will be done by auto XML parsing and binding the data between components and variables.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="callService('get')">
<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="callService('save')"/>
<!-- datagrid is directly binded to phonebook variable -->
<mx:DataGrid x="29" y="138" dataProvider="{phonebook.entry}">
<!--datafields determine which property belongs to that column-->
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Phone" dataField="phone"/>
<mx:DataGridColumn headerText="Record Id" dataField="@id"/>
<!--HTTPService can easily post and receive xml data-->
<mx:HTTPService id="httpXmlDataService" url="http://localhost:8080/firstproject/flex" resultFormat="e4x" result="resultHandler(event)" useProxy="false">
<!--xml request will be automatically formed with bindings-->
<mx:request xmlns="">
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
private var command:String;
private var phonebook:XML;
//xml var to hold the received data,note bindable attribute
//to enable binding

public function resultHandler(event:ResultEvent):void{
if (event.result!=null){
var xml:XML=event.result as XML;
if (xml.result=="success"){
public function callService(command:String):void{

So little and our client is ready, right click the project and select run as Web Application. 

GAE Plugin adds an embedded datastore and a server to your project to test. Whenever you click run the embedded services will be running and even an internal browser will run your client. Since our project name and mxml file has the same name, the default page on web.xml file point to our Flex application. Please dont forget to modify in your web.xml file if yours differ.

Easy? Well yes but still this does not release the real power and integration of Java and Flex. Next time we will focus on BlazeDs to make Flex to talk to Google App Engine. Stay tuned ;)


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}