Tuesday, May 26, 2009

Now that we have the client side set up, let's prepare the server side, starting with the JPA entity that will store the data. For this example, I'm going to use just two fields: "key" (primary key) and "value." For those of you relational folks new to GAE/JPA, there is no "table" per se: you declare a JPA "entity," which is a Java class annotated to be persistent. Then, to "insert" a "row," you create a class instance and "persist" it. GAE/J will associate all the class instances together as if they were rows in a table.

As you can see, this is ridiculously simple. All you had to do to make persistent was to add the @Entity annotation for the class and an @Id to mark "key" as the primary key. You do need to add getters/setters however: making the fields public and directly manipulating them will NOT work! Eclipse can automatically generate getters/setters for you - use Right Click->Source on the Java source.

EntityManagerFactory

Next, we need to create a POJO to do create/read/update/delete on the JPA entity we just declared. The basic steps are as follows:

Get an EntityManagerFactory instance

Create an EntityManager

Get an EntityTransaction (if doing transactional work)

Do your thing

The first step (get EntityManagerFactory) you want to do through a singleton because the operation is VERY expensive (10-20 seconds is pretty typical). The way AMF works is that it has servlets running on the server listening for requests from Flex RemoteObject (see web.xml in Part II). It is VERY important that you define the scope for these servlets as "application," meaning the servlets start once and will continue to run till the next update (see services-config.xml in Part II). If you set the scope as "session" (or worse, "request"), the servlets will keep restarting, creating EntityManagerFactory afresh, severely reducing the responsiveness.

Create a Java class EMF.java in package com.acme.data with the below code.

The final step is to create POJO that GraniteDS will use to access the JPA entities. It's the methods in this POJO that your RemoteObject uses (see createData, readValue, updateValue, and deleteData in the Data.mxml RemoteObject tag in Part II).

package com.acme.data;

import javax.persistence.EntityManager;

import javax.persistence.EntityTransaction;

public class Data {

public void createData(String key, String value) {

EntityManager em = EMF.get().createEntityManager();

EntityTransaction tx = em.getTransaction();

DataItem dataItem = new DataItem(key, value);

try {

tx.begin();

em.persist(dataItem);

tx.commit();

} finally {

if (tx.isActive()) {

tx.rollback();

}

em.close();

}

}

public String readValue(String key) {

EntityManager em = EMF.get().createEntityManager();

return em.find(DataItem.class, key).getValue();

}

public void updateValue(String key, String value) {

EntityManager em = EMF.get().createEntityManager();

EntityTransaction tx = em.getTransaction();

DataItem dataItem = em.find(DataItem.class, key);

dataItem.setValue(value);

try {

tx.begin();

em.merge(dataItem);

tx.commit();

} finally {

if (tx.isActive()) {

tx.rollback();

}

em.close();

}

}

public void deleteData(String key) {

EntityManager em = EMF.get().createEntityManager();

EntityTransaction tx = em.getTransaction();

DataItem dataItem = em.find(DataItem.class, key);

try {

tx.begin();

em.remove(dataItem);

tx.commit();

} finally {

if (tx.isActive()) {

tx.rollback();

}

em.close();

}

}

}

There's really nothing to this code, it's quite self-explanatory. I've simplified it to the extent possible, and as you get familiar with the process, you can explore other APIs (like em.createQuery).

BUILD/PUBLISH

The final step is to build and publish to GAE. To build the release version of the Flex app, select the project name in the Eclipse left pane and Right Click->Export->Flex Builder->Release Build. Point "Export to folder" to your war/ directory.

Next, create a GAE app (if you haven't already) and deploy your code by clicking the little GAE logo on the top left in Eclipse (or click on the project name in the left pane and Right Click->Google->Deploy to App Engine). If you don't have GAE Java access (see Part I), this operation will fail with a somewhat cryptic message.

That's it. Open your app with http://yourapp.appspot.com/Data.html and see the magic. If there's no magic, may be I missed something, so please post back here so I can fix it. If there IS magic, please do post comments/opinions. Happy coding!

Add the Flex Builder plugin. Adobe offers a 60 day trial, if you're ready to buy.

Once you have those going, get the Google Plugin. You install plugins in Eclipse by going to Help->Software Updates and specifying the install URL through "Add Site." The link for Google Plugin is http://dl.google.com/eclipse/plugin/3.4.

Next, create a Google Project. Open File->New->Other (or Ctrl+N) and select Google->Web Application Project. Enter a Project name (e.g., "Data") and a Package name (e.g., "com.acme.data"). Uncheck "Use Google Web Toolkit" under "Google SDKs" because we're not going to use GWT.

Since we're going to also build a Flex app in this project we need to give it a Flex Project Nature. Select the project name in the Eclipse left panel and Right Click->Flex Project Nature->Add Flex Project Nature. This will automatically create a Data.mxml file (which we will edit later) in the src/ folder.

You will immediately see an error message "Cannot create HTML wrapper. Right-click here to recreate folder html-template." on the Problems tab in the bottom-right panel. Do that, and Flex Builder will create a template for generating Data.html.

Install the GraniteDS library. Get the latest rev from the download site, unzip to graniteds/, and copy granite.jar (we don't need anything else for this project) from graniteds/build/ to your project's war/WEB-INF/lib/.

Finally, get the Xalan-J version xalan-j_2_7_1 from the download site, unzip, and copy serializer.jar and xalan.jar from the root to your project's war/WEB-INF/lib/.

You now have all the software you'll need; next step is to configure it.

Configuration

For configuring, you need to mess with four files.

web.xml

This file is in war/WEB-INF/ and contains info about the servlets. Your GraniteDS installation has servlets that will run on GAE, and you need to add their info into web.xml. Copy/paste the below XML inside the <web-app> tag.

Create a flex/ directory under war/WEB-INF/ and make a Flex-specific file "services-config.xml" with the below contents. This file tells Flex how to direct the RemoteObject calls. We're naming the service Data with the Java class Data (which we will create later) under the package com.acme (change this as necessary).

By default, the Flex compiler will not know of this file, so you'll need to add "-services ../war/WEB-INF/flex/services-config.xml" to the compiler flags. To access the flags, select the project name on the left panel and Right Click->Properties->Flex Compiler.

Next, create a granite/ directory in your war/WEB-INF/, and copy the GraniteDS file "granite-config.xml" from graniteds/examples/graniteds_pojo/resources/WEB-INF/granite/ to it.

persistence.xml

JPA loads its configuration info (like persistence unit "transactions-optional" that the EMF class in Part III uses) from a "persistence.xml" file, but GAE currently doesn't automatically create it. So, make a persistence.xml file in src/META-INF/ with the following contents.

We're now set to create the Flex app. To illustrate the basic aspects of data access, I'm going to build a small app that does simple CRUD: create, read, update, and delete. Copy the below MXML to the Data.mxml file in your src/ folder. I've made this as simple as possible, and it should be self-explanatory. Note that Flex refers to the services-config.xml (see above) to figure out how to contact the service.

Tuesday, May 12, 2009

Cloud and RIA (Rich Internet Application) are probably the hottest buzzwords today in the web world. You can look at cloud as a virtual server that provides single-point access to a distributed (often across the globe) collection of hardware/software and coming in three shapes:

IaaS: Infrastructure as a Service. A good example is Amazon EC2, where you basically get a virtual machine (Amazon Machine Image) on which you install what you want.

PaaS: Platform as a Service. This adds infrastructure software to IaaS so you don't start from scratch. Examples are Google App Engine (GAE) and Salesforce Force.com.

SaaS: Software as a Service. Here, you get the full package that you tweak/customize to your needs. Best example of course is Salesforce.com.

Clouds have many benefits, most importantly:

You don't need to plan/invest in hardware/software upfront

Your infrastructure will scale as your business/needs grow

You system will be fault-tolerant and secure

You don't need to maintain/manage the setup

In this example, I'm using GAE (Java) for the cloud. Google had required developers to use Python for GAE till recently, when they announced a Java version. All references to GAE in this write-up refer to GAE (Java). GAE is free to get started; you will need a Gmail account.

An RIA is an advanced web (or desktop) front-end that's more sophisticated than traditional HTML/CSS/JavaScript web apps. The dominant web RIA today is Adobe Flex, although Microsoft Silverlight is gaining rapidly. Sun (Oracle) recently announced JavaFX that's gaining some traction in the Java community. We will use Flex as the RIA in this example; you will need Flex Builder (free trial for 60 days) and Eclipse.

Technology Choices

Once we've decided to hook up a Flex RIA to a GAE cloud, we need to look at some specifics. First, how do you represent the data on GAE? GAE (Java) does not allow saving to files on the server, so our only option is to save on the Google BigTable. In fact, it's a better option anyhow. Luckily, the new GAE has a standards-based Java persistence API (rather than the Google-proprietary API with Python): JDO and JPA. I'm using JPA for this example.

Next, the interchange data format. Popular message formats with Flex are: XML (SOAP or REST), JSON, and the Adobe-proprietary AMF. XML is verbose and although accesss through REST performs reasonably well, more succint representations like JSON are better for larger chunks of data. But the most efficient (and strongly typed) representation is with AMF, which is what we will use for this example. To employ AMF for the data exchange, we use the Flex RemoteObject.

Adobe has made the AMF spec public, and there are multiple free implementations, probably the most important of which are: BlazeDS, WebORB, and GraniteDS. I've tried all the three with GAE. BlazeDS never worked for me, and as of today I'm not aware of any official fixes, though there are blog reports of unofficial workarounds. WebORB kind of worked with their fix in the sense I could move data through POJO interfaces to data, but not the persisted classes themselves. I also had performance issues. GraniteDS worked like a charm, and that's what we'll use in this example. Do keep checking Will it play in App Engine for the latest info.