-J2EE Developer at Turkiye Is Bankası Core Banking Exchange project -Java-Flex Developer in TAV IT. Built softwares for several international airport (istanbul, ankara, izmir, tblisi, batumi, emfidha) with JPA/Spring/CXF/BlazeDS on server side and Flex on rich clients. -JavaEE&Process Project Laader at HSBC. -Presenter at Eclipsist 2008, on Rapid Rich Internet Application Development. Murat has posted 8 posts at DZone. View Full User Profile

Flex Remoting on Google App Engine

05.29.2009
| 26240 views |
  • submit to reddit

I'm not personally related to Adobe, Google nor Sun but I like to code in Java. I am happy to see that 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 it offers, otherwise you can do this tutorial with any other web framework and still achieve our goal in this article.

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 the real world you wouldn't want this and would probably use xstream or any other parser to convert our objects to xml. But wouldn't it be great to call a Java backend from our Flex client with remoting and using objects without xml serilization. Well in 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;
@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;
}
//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
.getPersistenceManagerFactory("transactions-optional");
PersistenceManager persistenceManager;
@Override
@Transactional
public boolean addEntry(Entry entry) {
try {
//check if the id is 0 which is same as null
if (entry.getId().intValue()==0){
entry.setId(null);
}
//get manager
persistenceManager = pmfInstance.getPersistenceManager();
//save our entry
persistenceManager.makePersistent(entry);
return true;
} catch (Exception e) {
return false;
}
}
@Override
@Transactional
@SuppressWarnings("unchecked")
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 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
{
[Bindable]
[RemoteClass(alias="org.flexjava.server.Entry")]
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 have 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="http://www.adobe.com/2006/mxml" 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:columns>
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Phone" dataField="phone"/>
<mx:DataGridColumn headerText="Record Id" dataField="id"/>
</mx:columns>
</mx:DataGrid>
<mx:RemoteObject id="ro" result="showEntryList(event)" destination="FlexDestination" endpoint="http://localhost:8080/messagebroker/amf"/>
<mx:Script>
<![CDATA[
import mx.binding.utils.BindingUtils;
import org.flexjava.client.Entry;
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;
[Bindable]
public var phonebook:ArrayCollection;
public function init():void{
ro.getEntryList();
}
public function saveEntry():void{
var entry:Entry=new Entry();
entry.name=nameTxt.text;
entry.phone=phoneTxt.text;
ro.addEntry(entry);
}
public function showEntryList(event:ResultEvent):void{
if (event.result!=null){
if (event.result==false){
Alert.show("record could not be added");
}else if (event.result==true){
Alert.show("added to your phone book");
ro.getEntryList();
}else{
phonebook=event.result as ArrayCollection;
}
}
}
]]>
</mx:Script>
</mx:Application>

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 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/webAppContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>testdrive</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>testdrive</servlet-name>
<url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>

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

 

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:flex="http://www.springframework.org/schema/flex"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/flex
http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<flex:message-broker>
<flex:message-service
default-channels="my-streaming-amf,my-longpolling-amf,my-polling-amf" />
<!-- <flex:secured /> -->
</flex:message-broker>

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

This will make our FlexServiceImpl class available as 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. These files are quite standard so if you have downloaded Christophe's example or got them any other way, you may just copy those files instead of creating them. You can also get them under my project export.

 

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.

 

antlr-3.0.1.jar
aopalliance.jar
appengine-api-1.0-sdk-1.2.0.jar
aspectjrt.jar
aspectjweaver.jar
backport-util-concurrent.jar
cglib-nodep-2.1_3.jar
commons-codec-1.3.jar
commons-httpclient-3.0.1.jar
commons-logging.jar
concurrent.jar
datanucleus-appengine-1.0.0.final.jar
datanucleus-core-1.1.0.jar
datanucleus-jpa-1.1.0.jar
flex-messaging-common.jar
flex-messaging-core.jar
flex-messaging-opt.jar
flex-messaging-proxy.jar
flex-messaging-remoting.jar
geronimo-jpa_3.0_spec-1.1.1.jar
geronimo-jta_1.1_spec-1.1.1.jar
gwt-servlet.jar
jackson-core-asl-0.9.9-6.jar
jdo2-api-2.3-SNAPSHOT.jar
org.springframework.aop-3.0.0.M3.jar
org.springframework.asm-3.0.0.M3.jar
org.springframework.aspects-3.0.0.M3.jar
org.springframework.beans-3.0.0.M3.jar
org.springframework.context-3.0.0.M3.jar
org.springframework.context.support-3.0.0.M3.jar
org.springframework.core-3.0.0.M3.jar
org.springframework.expression-3.0.0.M3.jar
org.springframework.flex-1.0.0.RC1.jar
org.springframework.jdbc-3.0.0.M3.jar
org.springframework.jms-3.0.0.M3.jar
org.springframework.transaction-3.0.0.M3.jar
org.springframework.web-3.0.0.M3.jar
org.springframework.web.servlet-3.0.0.M3.jar
spring-security-acl-2.0.4.jar
spring-security-catalina-2.0.4.jar
spring-security-core-2.0.4.jar
spring-security-core-tiger-2.0.4.jar
spring-security-taglibs-2.0.4.jar
xalan.jar

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.
at com.google.apphosting.utils.jetty.StubSessionManager$StubSession.throwException(StubSessionManager.java:67)

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 go to your SecondProject.mxml file and change the endpoint value with your app url(in mine; endpoint="http://flexjava2p.appspot.com/messagebroker/amf"). 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 “. This not very cool, the development environment differs from actual runtime and we are facing a problem which we did not face in development.

When I search for this error I found another good resource by Martin Zoldano. 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 a bit 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 attachment below. 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. Even in this early stage we managed to make GAE work with Flex via Blaze.

I remember reading the following on Yakov Fain's blog;
He was saying; “99% of the people who reject using the software until it gets open sourced, neither plan nor will look at its source code.  “
My Comment was;
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 a car don't forget to get a one with airbags even if you feel you don't need them. By the way want to see the finished app in the cloud... http://flexjava2p.appspot.com/

Murat Yener

www.flexjava.org

 

Legacy
Published at DZone with permission of its author, Murat Yener.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Greg Brown replied on Fri, 2009/05/29 - 2:40pm

You should check out Pivot. It is a platform for building RIAs in Java:

http://incubator.apache.org/pivot/

The UI markup is similar to MXML, and the programming language is Java (or any other JVM scripting language).

Murat Yener replied on Sun, 2009/05/31 - 1:55am in response to: Sekhar Ravinutala

I had used graniteDS before but not lately. Blaze has good integration and is really supported by spring. Since this is app engine granite might be a better idea, i ll try and see which one is better.

Murat Yener replied on Sun, 2009/05/31 - 2:00am in response to: Greg Brown

I dont think pivot can offer similar functionality and maturity as flex (which is about to be version 4, pivot is incubator...) and actually if i want to use only java, i would prefer JavaFx. Did you try pivot on app engine? if so why dont  you write a tutorial so people can compare and see pros and cons...

anurag gupta replied on Fri, 2009/09/18 - 3:44am

Hi all, i have flexUI that uses remote serives and remote service provide is blaze ds. i am able to execute my application in my local machine. after uploading this application in app engine. i am not able to access remote service, i am getting below errors in app engine log. can you please help me how to resolve that issue thanks in advance anurag gupta - india failed MessageBrokerServlet java.lang.NoClassDefFoundError: java.lang.management.ManagementFactory is a restricted class. Please see the Google App Engine developer's guide for more details. at com.google.apphosting.runtime.security.shared.stub.java.lang.management.ManagementFactory.(ManagementFactory.java) at

Curtis George replied on Fri, 2009/10/16 - 1:30pm

I was wondering if someone could help me.  I am able to run the first or second project with no errors but I do get a warning:

BlazeDS]No login command was found for 'Google App Engine Development/1.2.5'. Please ensure that the login-command tag has the correct server attribute value, or use 'all' to use the login command regardless of the server.  The server is running at http://localhost:8080/

 Anyhow, the application runs but when I enter data nothing happens.  I have also deployed the second project under http://curtgeorflexjava2p.appspot.com/ with no success.  I have also tried the first project leviathonflextest.appspo.com/ with the same results.

 It is something I am doing wrong with both but I can't figure it out.

 

Thanks 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.