Flex apps are beasts that thrive on a healthy serving of server-side XML. How exactly you go about feeding any given app depends on your client's environment and practices, as well as your skill set and comfort level with the different preferred technologies.
My personal background lies mainly in Java development and the server-side technologies I have used most often are SOAP and servlets (i.e. plain old servlets, Struts and Spring). While I can acknowledge the value of SOAP, pay me a buck for every time I've heard someone complain about
the overhead of creating/using SOAP-based services and I'd be rich enough not to be
writing this. On the other hand, using servlets to satisfy the voracious appetite of a healthy Flex app has its own draw-backs.
I've suspected for some time that there is a more elegant, more lightweight way to write Flex-friendly XML-producing server-side Java code. I was therefore excited when asked to explore the world of Java RESTful web services during the lead-in to a new project here at 4Point. What follows is a summary of the many promising things I have learned in the past few days -- things that have led me to ask: "Is it finally time to scrub out SOAP?"
REST in a nutshell
REST
stands for "Representational State Transfer", but frankly, the name doesn't
really say much about what it really is. REST is a means of
exposing a resource to outside interaction through a combination of
a URI and an HTTP method (i.e. one of POST, GET, PUT and DELETE). These
methods are mapped (roughly) to the classic CRUD operations, allowing you to create, read, update and delete data.
| HTTP | CRUD | ||
|---|---|---|---|
| POST | Create | ||
| GET | -- Equivalent --> | Read | |
| PUT | Update |
||
| DELETE | Delete |
In order to invoke an operation on a REST resource, you simply invoke the appropriate URL using the appropriate HTTP method ...and voilĂ !
e.g.
Create a new resource:POST http://www.myserver.org/myResource (with the new contents of the resource as the POSTed payload)
Get the resource with ID=2:GET http://www.myserver.org/myResource/2
Update the resource with ID=2PUT http://www.myserver.org/myResource/2 (with the new contents of the resource as the PUT payload)
Delete the resource with ID=2DELETE http://www.myserver.org/myResource/2
Client Agnostic
Though I have no personal experience with this, some of my colleagues
have faced many frustrating hours working through the differences
between Microsoft-flavoured SOAP vs Java-flavoured SOAP.
One of the great benefits of using the foundational tools of HTTP to implement the protocol is that REST is client agnostic. That is to say that as long as the client-side technology can handle submitting HTTP requests and recieving HTTP responses, it can interact with a REST service. Period.
Plus, since you are in control of the format of the response, you can structure your "payload" XML in whatever way you'd like and not have to worry about extra XML getting wrapped around it against your will. In fact, the response doesn't even have to be XML, as in our example.
Enter: RESTEasy
When I was first given this discovery task, I was pointed to RESTEasy, a fully certified implementation of the Java specification for RESTful web services (JSR311). I was quickly won over.
The beauty of RESTEasy is that it allows you to turn POJOs into fully RESTful Resources without writing any
boilerplate code or XML configuration files. You don't have to extend any special classes or implement any obscure interfaces, leaving the classes you create decoupled from RESTEasy.
In order to expose
your Java methods to outside invocation, just add an annotation indicating the relative path under which it
will be found and register it as a Singleton in your JAX-RS Application (one line of code). The methods inside the Resource that do the actual work are also annotated, usually with an HTTP method (i.e. @GET, @POST) and a path (i.e. @Path("somePath"). Other annotations include what is consumed or returned (i.e. @Consumes, @Produces). It is just that simple. The RESTEasy servlet takes care of the rest.
e.g.
My initial practical introduction to RESTEasy was this excellent tutorial by Petrus Pelser over at Assertion Error. I suggest that you try it out before moving onto the Flex side of this exercise.import com.fourpoint.rest.model.Entry;@Path("/myNewResourcePath")public class MyExampleResource {
@POST
@Consumes("application/xml")
public Response createEntry(InputStream is) {
Entry newEntry = createEntryFromXMLStream(is);
Long id = myDAOLayer.addEntry(newEntry);
return Response.created(URI.create("/myNewResourcePath/" + id)).build();
}
@DELETE
@Path("id")
public void deleteEntry(@PathParam("id") Long id) {
myDAOLayer.removeEntry(id);
}
// More code goes here...
}
Shortcomings of the Flex HTTPService
Once
you have a RESTful web service running on the server side, you might
be tempted to use the good, old, reliable HTTPService to invoke your new Resource URIs. Unfortunately, as I have
discovered, HTTPService doesn't support
the full HTTP method set (i.e. our REST "verbs"). In fact, it only supports the GET and
POST methods. While it is possible to map all of your "CRUD"
operations to these two methods by adding on appropriate URL
parameters, that wouldn't really be REST development, now would it?
RestHttpService to the rescue
Thankfully, Dustin Calloway (an accomplished developer and published author, I might add) has developed a polished, developer-friendly open-source Flex class called restHttpService that provides easy access to six HTTP methods: GET, POST, PUT, DELETE,
HEAD and OPTIONS.
RestHttpService supports secure and insecure connections and can
be invoked through both pure ActionScript and MXML. Though it only supports text responses, it is ideal for our needs (we're just dealing with XML here).
Using restHttpService is almost identical to using HttpService.
Given this service:
<rest:RestHttpService
id="postHttpService"
host="localhost"
port="8080"
method="{RestHttpService.METHOD_POST}"
path="/myResource"
contentType="application/xml"
result="myResultHandler(event)"
fault="myFaultHandler(event)"/>
Invoking it thus:
postHttpService.send(<myData>This is my data</myData>);
Will post:
The new "myData" XML payload to the /myResource singleton.
It's just that simple. On his Google Code page, Dustin provides a more complete example of how restHttpService is used, including both MXML and ActionScript code. In case you're wondering how it works, restHttpService makes clever use of the lower-level control provided by the flash.net.Socket class.
(Note: Among other things, Dustin also wrote this excellent primer on REST web services. It's definitely worth reading, if not bookmarking.)
Unit Testing?
Again, I have no practical experience with this (yet), so I can only infer from what I've read and seen in the tutorials.
On the server-side: RESTEasy provides an embeddable server implementation to simplify junit testing. To make life even easier, example unit test code that makes use of the embedded server is provided in the distribution. Also, because the Resource classes aren't coupled to RESTEasy, they should be simpler to test overall.
On the client-side: By using vanilla HTTP, REST makes the prospect of mocking out server responses for the purpose of Unit Testing a lot less daunting.
As for the REST...
(Sorry, I had to make my bad pun quota.)
So where from here? Well, if you're anything like me, you're itching to try this all out in a practical way. Before doing so, I'd suggest again that you try out the tutorials/examples that I've linked to from this page. I found them easy to follow and quick to get through.
I'll post my thoughts once I've had a chance to make more practical use of RESTEasy and restHttpService. I welcome any comments that you might have on this topic, especially if you've had a chance to use these technologies. I'd particularly like to know what the best practices are for unit testing RESTEasy resources and a RESTful Flex client.
Oh, and can someone please clarify the difference between REST and RESTful for me?
Thanks for reading!

Surely, if you are integrating with some existing application that has a REST API or if you wanted to expose a REST API to other client applications, you would go this route. But if you are building an application from scratch with no plans for other clients, would you still build it RESTfully rather than using BlazeDS and RemoteObjects?
Just curious.
Hi Rob. Thanks for your comment.
This article is strictly relevant to text-based services (presumably XML-based, really). Indeed there are more efficient ways for Flex to access server-side data (i.e. objects) than to use RESTful services and XML. In some cases, though, that's all you really need.
In answer to your question, we are primarily a LiveCycle shop and tend to use LiveCycle DS (my guess would be that in many cases, our clients already have licenses). My personal preference would be to use BlazeDS for leveraging remote objects, since LCDS seems like overkill to me and I tend to lean towards open-source tools generally.
Part of my research into REST is related to an upcoming XML-heavy project. Also, in another recent project, the client made liberal use of SOAP web services with which we had to integrate. It was less than fun, so looking into RESTful web services has been a breath of fresh air.
Hey thanks for the information....but i need an example of the same....
it would be helpful for me to debug and get a hold on things as to how it works...will appreciate it if u can guide me through this...
Thanks for the quick intro to REST in Flex. The RestHTTPService open source component makes REST + Flex seem doable. I often wonder why Adobe has not provided some of the components that are so often desired (i.e. no PDF display inside a Flash app).
@Rob, a REST service architecture seems to be good practice when following the KISS principle. Also, for a .NET backend, LCDS/Blaze is not available.
You're welcome, Jim. I'm right smack in the crunch time of a large-ish project based on this stack and have lots more to post on it based on (many) lessons learned.
We are building a system with an Oracle DB, Hibernate ORM, RESTEasy and XStream (for XML marshalling/unmarshalling). On the Flex side, we are using Mate as our dependency injection MVC framework, Chimp for role-based view management and RestHttpService for implementing all the needed HTTP methods.
In a nutshell, here are some quick take aways:
The Good
- Hibernate is awesome... once you get it configured and running properly, that is
- RESTEasy is so easy to get going that it makes you *almost* feel guilty
- XStream is ridiculously easy to use and takes care of all the heavy lifting of reading/writing XML/Objects. No xsds, no descriptors. Annotations are used for anything you need to tweak.
- After some digging in the Mate site, I was able to modify RestHTTPService quite easily to create a RestHTTPServiceInvoker for Mate that is indistinguishable from "native" Mate service invokers
The Bad
- Hibernate is a hog when you have a large inheritance hierarchy. We have one class with about 80 sub-classes (don't ask). I have come up with some clever workarounds/optimizations, though. Once we've load-tested this we'll know more.
- XStream doesn't play well with cyclical relationships (bi-directional associations being the simplest and most obvious example of this). If you stop to think about it, it's obvious that XML will have problems representing a circular relationship: picture a user object that "owns" a telephone number object that has a reference to its "owner" user object. In XML that is an infinite structure. XML is great for representing trees but cyclical object graphs... not so much. On the plus side, with some clever XStream annotations and Proxy objects, you can circumvent this issue most of the time.
- Since Flex doesn't support all HTTP methods, we had to use RestHTTPService, which uses sockets to implement the missing methods. We've been having some "invalid socket" errors we've yet to nail down. Hopefully this will get cleared up soon.
My conclusion at this point is: this stack is great for smaller projects. You can have all your layers up and going in no time at all. It is cheap and is really easy to debug (for GETs, just hit a URL with your browser). For larger projects with complex, circular data models, having to pass your objects through XML can be problematic. It isn't fatal, but requires some thoughtful design work.
I'll surely have a lot more to post on this once the project starts to wind down. For now, it's da#$ the torpedoes, full steam ahead.
Oh, and one other thing, Jim: you *can* technically display a PDF document inside a Flash app, if you use an iFrame. You are correct that Flash doesn't "natively" support PDF display per se. To "talk" to the iFrame, you have to go outside the Flash app through the external interface and use Javascript in the browser... but that's for a whole other blog posting on another day.
Hi Taylor,
I have been working on a version of a UrlLoaderInvoker for Mate to allow me to query REST services. This seems much easier. Do you have your code up anywhere for RestHTTPService?
Thanks,
Brian
Specifically, when you call the RestHTTPService.send method, how do you tell Mate to go off and run your result handlers or fault handlers?
Specifically on Mate RestHTTPServiceInvoker, after you call the send method, how does Mate know to run your result handlers or fault handlers?
Hi Brian,
I do have an answer to your question, though I am up against a deadline right now and working feverishly to avoid catastrophe. I'll post a new blog entry on how this is done as soon as I can and will send you a heads-up.
I based my code on this article: reading this (well hidden) article from the Mate site: http://mate.asfusion.com/page/how-to/extend-mate
In a nutshell, the keys are:
- Create a new Invoker class that extends AbstractServiceInvoker and implements IAction
- Give your new Invoker an instance of the service you will will be using (i.e. that you will be "wrapping")
- Implement a run() method and set the "current" instance attribute from AbstractAction to point to "this"
Once it's all wired up, your Invoker will be indiscernible from a "native" Mate Invoker.
Thanks for visiting the blog. I'll be in touch when I get to writing the Invoker entry.
Hi Brian,
I've hacked away at my version of RESTHttpService and there may be code in there that isn't useful to another codebase. Try the latest from http://code.google.com/p/resthttpservice/downloads/list
If I get a green light from my boss to open-source our version, I'll gladly make it available, along with the Mate Invoker that wraps it.