Java on Google App Engine is a very important step. Since I graduaded i hear most of friends bringing up ideas but not trying to built them, mostly because of the costs of Java hosting. Java is a elegant and sophisticated platform which is very 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 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 intoduction 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 specially for starting GWT but not usefull 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 persistamce 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;
@PersistenceCapable
public class Entry {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
Long id;
@Persistent
private String name;
@Persistent
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();
//..
persistenceManager.makePersistent(entry);
//..
persistenceManager.newQuery(query).execute();
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;
@SuppressWarnings("serial")
public class FlexServiceImpl extends HttpServlet {
//persistanceManager
private static final PersistenceManagerFactory pmfInstance = JDOHelper.getPersistenceManagerFactory("transactions-optional");
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
//PrintWriter to return and receive data from flex client
PrintWriter writer=resp.getWriter();
writer.println("\n");
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();
entry.setName(name);
entry.setPhone(phone);
persistenceManager.makePersistent(entry);
writer.println("
//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
writer.println("
for (Entry entry : entries) {
writer.println("
writer.println("
writer.println("
writer.println("
}
writer.println("
}
}
}
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 confusint 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}">
<mx:columns>
<!--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"/>
</mx:columns>
</mx:DataGrid>
<!--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="">
<operation>{command}</operation>
<name>
{nameTxt.text}
</name>
<phone>
{phoneTxt.text}
</phone>
</mx:request>
</mx:HTTPService>
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
[Bindable]
private var command:String;
[Bindable]
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"){
callService("get");
}else{
phonebook=xml;
}
}
}
public function callService(command:String):void{
this.command=command;
httpXmlDataService.send();
}
]]>
</mx:Script>
</mx:Application>
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

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 ;)
p.s. While waiting, start coding your dreams for free and keep in mind if you are interested in depth details of Flex, eteration offers a new training course which i also act part in the preperation.
Hi Murat, since I had lots of work, I was not able to find time to search about this topic.
ReplyDeleteThis research will be the first step for me to start a development of a Flex application with Google Engine. Thank you :)
Interesting article that you have posted. I'm very happy to read this. thanks.
ReplyDeleteHtml5 Training in Chennai
html course in chennai
html course fees in chennai
Html5 Training
Html5 Training in Velachery
DOT NET Training in Chennai
QTP Training in Chennai
LoadRunner Training in Chennai
ReplyDeleteGreat info. The content you wrote is very interesting to read. This will loved by all age groups.
Angularjs Training in Chennai
Angularjs Course in Chennai
Ethical Hacking Course in Chennai
Tally Course in Chennai
Angular4 Training in Chennai
ux design course in chennai
Angularjs Training Center in Chennai
Angularjs Training Chennai
web designing training in chennai
Tally Course in Chennai
This is a very helpful blog for one who needs to learn in a short span of time.
ReplyDeleteSpoken English Classes in Chennai
Best Spoken English Classes in Chennai
Spoken English Class in Chennai
Spoken English in Chennai
English Speaking Classes in Mumbai
English Speaking Course in Mumbai
IELTS Coaching in Chennai
IELTS Coaching Centre in Chennai
IELTS Classes in Mumbai
IELTS Coaching in Mumbai