BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage Articles Building Web and Desktop Applications with BlazeDS and AMF

Building Web and Desktop Applications with BlazeDS and AMF

This item in japanese

Applications that run on the desktop with Adobe AIR or in the browser with Flash Player usually connect to a server when they need to load or manipulate data. Developers building these applications with tools like Adobe Flex and Flash CS3 have a variety of options for enabling their applications to communicate with servers. The servers themselves can be running Java, ColdFusion, .Net, PHP, Ruby or any number of other server-side technologies. Regardless of the server-side technology in place, some sort of network communication is needed when the client-side application running in Flash Player or Adobe AIR needs to communicate with the server. Usually this communication happens over HTTP - the same protocol used by the web browser to load web pages and applications. But differences in how data is passed over HTTP can dramatically reduce application performance as well as developer productivity.

Many applications running in Adobe AIR or Flash Player use XML-over-HTTP technologies, such as SOAP or REST, to move data between the client and server. This method is simple and fairly easy to set up. Every server technology can easily speak XML since it is a text-based protocol. XML is perfect when protocol transparency is necessary. For instance, Flickr's web services use RESTful-style XML over HTTP. This allows any developer using any technology to easily interact with Flickr by sending simple text-based requests to Flickr. Flickr then responds with simple XML, which makes it easy for developers to easily parse and use the data. One downside to text-based protocols like XML is that the additional layer of data abstraction is usually cumbersome to write and maintain. In addition, this data abstraction layer consumes resources on the server-side and client-side when the data is serialized and deserialized (see Figure 1).

Figure 1. AMF reduces the layers for marshalling data over the wire

For some time, Flash Player has supported a transport protocol that alleviates the unnecessary bottlenecks associated with text-based protocols and provides developers a simpler method of communicating with servers. Called Action Message Format (AMF), this binary protocol for exchanging data can be used over HTTP in place of text-based protocols that transmit XML. Applications using AMF can eliminate an unnecessary data abstraction layer and communicate more efficiently with servers. To see a demonstration of the performance advantages of AMF, check out the Census RIA Benchmark application.

Over the past few years numerous open source projects emerged to provide AMF implementations similar to an old Macromedia product called Flash Remoting. These projects allowed developers using PHP, Java, and other technologies to use AMF in their applications. When Flex 1.0 was released it also included AMF capabilities. When Flex 2 was released it included XML and AMF capabilities, but the server-side AMF capabilities were moved into a new product called Flex Data Services. Flex Data Services became LiveCycle Data Services ES when it joined the Live Cycle product suite. While LiveCycle Data Services ES Express has been free for a single CPU server, the pricing for servers with more than a single CPU discouraged some developers from using AMF or caused them to choose other non-standard AMF implementations.

In December 2007, Adobe made two significant announcements which allow everyone to begin taking advantage of AMF. The first announcement is that the specification for AMF is now publicly available. Publishing the specification allows other projects to implement AMF based on the specification rather than reverse engineering the protocol. No matter what back-end technology developers use - Java, ColdFusion, PHP, .Net, Ruby, etc. - the implementation of AMF can be spec-compliant. The second significant announcement was that a portion of the LiveCycle Data Services ES technology was being open sourced as a project called BlazeDS.

BlazeDS includes a Java implementation of AMF which is used for remotely communicating with server-side Java objects as well as for passing messages between clients. BlazeDS remoting technology allows developers to easily call methods on Plain old Java objects (POJOs), Spring services, or EJBs. Developers can use the messaging system to easily send messages from the client to the server or from the server to client. BlazeDS can also be linked to other messaging systems such as JMS or ActiveMQ. Because the remoting and messaging technologies use AMF over HTTP they gain the performance benefits of AMF as well as the simplicity of not having to deal with an additional data abstraction layer. BlazeDS works with a wide range of Java-based application servers, including Tomcat, WebSphere, WebLogic, JBoss, and ColdFusion. In addition, BlazeDS can easily be used in Flex applications for the web (running in Flash Player) and the desktop (running in Adobe AIR).

Developers can begin using BlazeDS today by downloading the prerelease version from Adobe Labs. To get started, simply deploy the blazeds-samples.war file in any servlet container. This web application contains a number of preconfigured sample applications that can be accessed at http://localhost:8080/blazeds-samples/ (The port may vary depending on your application server and server configuration).

To begin using the BlazeDS Remoting Service in your applications, follow these simple steps:

  1. Create a new POJO Java class which exposes the methods you want to access from a Flex application.
  2. Configure a BlazeDS remoting destination in the remoting-config.xml file.
  3. Create a Flex application which uses the RemoteObject class.

To use the BlazeDS Messaging Service, follow these simple steps:

  1. Create a messaging destination in the messaging-config.xml file.
  2. Create a Flex application that uses the Producer and Consumer classes to send and receive messages.
  3. Begin listening for messages by subscribing to the Consumer's message feed.

That is all you need to do to efficiently make remote requests to your back-end Java objects and utilize the messaging system with BlazeDS! Let's walk through those steps in more detail using Eclipse and Flex Builder. You will need the following software installed:

To create a simple Remoting Application:

  1. Unjar the blazeds.war file from BlazeDS into your application server's deployment folder. For instance, on JBoss use <JBOSS_HOME>/server/default/deploy/blazeds.war
  2. Start Eclipse / Flex Builder
  3. Create a new Java Project that you can use to configure BlazeDS and add Java classes to your web application.
    1. Use a project name like "blazeds_server"
    2. Create the project from existing source; use the path of the WEB-INF directory of your deployed BlazeDS WAR, such as: <JBOSS_HOME>/server/default/deploy/blazeds.war/WEB-INF/
    3. Add the src directory to the build path
    4. Use the WEB-INF/classes directory as the output folder
  4. Create a new Java class called HelloWorld.java with the following code:
  5. public class HelloWorld {
    public String sayHello(String name) {
    return "hello, " + name;
    }
    }
  6. Configure BlazeDS to allow remoting requests to the HelloWorld class by adding a destination to the remoting-config.xml file found in the WEB-INF/flex directory. Use the following destination configuration:
  7. <destination id="HelloWorld">
    <properties>
    <source>HelloWorld</source>
    </properties>
    </destination>
  8. Start your application server and verify your web application is configured by going to the following URL (The port may vary depending on your application server configuration): http://localhost:8080/blazeds/
    (If your server is not configured to display directory contents, you might see a 404 error. This is OK.)
  9. Create a new Flex Project
    1. For the project name, type "testHelloWorld"
    2. Select "J2EE" as the Application Server Type
    3. Select "Use remote object access service" and LiveCycle Data Services
    4. Specify the Root folder to be to location of your deployed WAR file
    5. Specify the Root URL to be: http://localhost:8080/blazeds (Your port name may be different depending on your application server configuration)
    6. Specify the Context Root to be: /blazeds
    7. Verify the configuration and click Finish
  10. Create the Flex application by updating the testHelloWorld.mxml file with the following source code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:RemoteObject id="ro" destination="HelloWorld"/>
    <mx:TextInput id="n" change="ro.sayHello(n.text)"/>
    <mx:Label text="{ro.sayHello.lastResult}"/>
    </mx:Application>
  11. Run the application and test it by typing your name into the TextInput box. You should see "hello, <your name>" displayed beneath the TextInput like the image below.

Explanation: The Flex application is using the RemoteObject library to communicate with the BlazeDS-enabled server. When the user enters text in the TextInput box, the change event causes the RemoteObject to make a request to the server. The server then makes a request to the Java Class specified in the remoting destination configuration. This could also call a Spring service or EJB session bean, however this example just calls a POJO. In this example, the POJO's return value is simply the name string passed to it appended to "hello, ". When the object returns a value, that value is serialized into AMF and returned to the Flex application. The RemoteObject library then sets the ro.<method name>.lastResult property to the value that was returned. (In this case ro.sayHello.lastResult.) The result can also be obtained through a result event on the RemoteObject. Data Binding triggers the Label to display the string which was returned from the POJO. BlazeDS also supports passing typed Java objects back and forth.

Next we will build a new Flex application that uses the BlazeDS messaging system.

  1. Start by adding a messaging destination to the messaging-config.xml file found in the WEB-INF/flex directory. Add the following destination:

    <destination id="chat"/>

    A messaging destination allows the messaging system to relay messages to clients listening on that destination and it also allows messages to be sent to the destination. Messaging destinations can have durability and network parameters, and they can also be connected to other messaging systems like JMS.
  2. Restart your application server so that BlazeDS configures the new messaging destination.
  3. Create a new Flex Project
    1. For the project name, type "testChat"
    2. Select "J2EE" as the Application Server Type
    3. Select "Use remote object access service" and LiveCycle Data Services
    4. Specify the Root folder to be to location of your deployed WAR file
    5. Specify the Root URL to be: http://localhost:8080/blazeds (Your port name may be different depending on your application server configuration)
    6. Specify the Context Root to be: /blazeds
    7. Verify the configuration and click Finish
  4. To create a simple chat application that uses the messaging system, update testChat.mxml with the following code:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="cons.subscribe()">

    <mx:Script>
    import mx.messaging.messages.AsyncMessage;
    </mx:Script>
    <mx:Producer id="prod" destination="chat"/>
    <mx:Consumer id="cons" destination="chat" message="c.text += event.message.body.msg + '\n'"/>

    <mx:TextArea id="c" width="300" height="300"/>
    <mx:TextInput id="m"/>
    <mx:Button label="Send" click="prod.send(new AsyncMessage({msg: m.text}))"/>

    </mx:Application>
  5. Run the application. Enter a message in the lower TextInput box and click Send. Verify that the message is displayed in the upper box like the image below. Also verify that with multiple browser windows open that messaging works between all of them.

Explanation: The Producer object allows Flex applications to send messages into the message system. There is also a Java API (not used in this example) which allows messages to be sent into the message system on the server. With a custom adapter or the out-of-the-box JMS adapter you can also connect the message system to other messaging systems, however by default the message system runs standalone. When the user clicks the send button a new message is created using an anonymous object to set the msg property on the body of the message to the value in the TextInput. Because, the message type is an AsyncMessage, that class must be imported. The Consumer object allows Flex applications to listen for messages. When the application has initialized, it subscribes to the message system. Then when a message is received the event handler on the Consumer takes the chat message out of the body of the message and appends it to the TextArea.

Using BlazeDS and AMF will help to reduce your development time and will help your applications run faster. Give BlazeDS a try and let us know what you think! You can find out more about BlazeDS and the open AMF specification from the BlazeDS page in Adobe Labs.

About the author

James Ward is a Technical Evangelist for Flex at Adobe and Adobe's JCP representative to JSR 286, 299, and 301. Much like his love for climbing mountains he enjoys programming because it provides endless new discoveries, elegant workarounds, summits and valleys. His adventures in climbing have taken him many places. Likewise, technology has brought him many adventures, including: Pascal and Assembly back in the early 90's; Perl, HTML, and JavaScript in the mid 90's; then Java and many of its frameworks beginning in the late 90's. Today he primarily uses Flex to build beautiful front-ends for Java based back-ends. Prior to working at Adobe, James built a rich marketing and customer service portal for Pillar Data Systems. James Ward's blog can be found at http://www.jamesward.org.

Shashank Tiwari is the Chief Technologist at Saven Technologies, a Chicago based company that provides cutting edge technology driven business solutions for banking and financial service companies. Shashank is a prolific developer, author and speaker who is active in the JCP as an expert group member on the following JSRs - 274, 283, 299, 301 and 312. He actively programs in at least a dozen of languages, including Java, ActionScript, Python, Perl, PHP, C++, Groovy, JavaScript, Ruby and Matlab. He is a popular blogger on the O'Reilly Network. These days he is busy building web 2.0 applications using Flex and Java. More information about him can be obtained at www.shanky.org.

Rate this Article

Adoption
Style

BT