Integrating Flex and Spring based JMS applications

DZone 's Guide to

Integrating Flex and Spring based JMS applications

· Integration Zone ·
Free Resource

This article explains the essentials of leveraging the Spring BlazeDS project to integrate Spring based JMS systems with Flex powered rich internet applications (RIAs).  The fundamental concepts involved in the integration of Spring and Flex are explained and the role of the Spring BlazeDS project and its mechanics are illustrated. In addition to a theoretical explanation, a simple example is included to show how such a stack can be setup and used.

Spring is a popular open source enterprise Java framework for building robust and scalable applications whereas Adobe Flex is an open source framework for creating rich and engaging interfaces.  Adobe BlazeDS is an open source application that allows Flex applications to connect with Java server side applications via remote procedure calls and message exchanges. 

Flex applications can connect with Spring server sides, using any of the following four mechanisms:

•    HTTP based requests and responses
•    Web Services
•    Remote procedure calls
•    Message Exchanges

The first two of the above listed four options, namely HTTP based requests and responses and web services, are agnostic to the server side technology and so the integration of Flex and Spring using these techniques involves no special considerations beyond the standard support for HTTP and the web services protocol and the availability of data through these endpoints.  Usually text based payload exchanges, especially XML, are common when HTTP services and web services are used. When using HTTP service or web service, BlazeDS or any such intermediary is not required, unless the security restrictions do not allow you to fetch data from the remote sources. Considering the relevance of BlazeDS is limited when using these two methods, I will not discuss the use of these methods any further in this article.

For remote procedure calls to server side objects and message exchanges, BlazeDS and similar intermediary products, play a critical role. These types of interactions and specifically message based exchanges are the focus of this article.

Prior to the existence of the Spring BlazeDS project, an Adobe supported SpringSource project, using BlazeDS to connect with Spring based Java servers involved use of a custom factory to access the Spring Beans. This is because Spring Beans and the objects instantiated by standard BlazeDS reside in separate namespaces. Not only did one need a custom factory, one could not use Spring style configuration to wire-up the BlazeDS artifacts. One had to use the BlazeDS specific xml based configurations to set it up. With Spring BlazeDS integration much of the tedious coupling between Spring and BlazeDS has been reduced to simple uniform configuration and first class support for Spring Beans as remoting destinations. Besides, Spring messaging related goodies like the JMSTemplate and the Message Driven POJOs, Spring security and the rest of its framework components become available as server side counterparts for Flex applications.

In the next few sections, I will explain how you could use Spring BlazeDS to integrate Flex and Spring based JMS systems. As I do that I will assume that you have essential knowledge of the Spring framework, Flex framework and even BlazeDS. If these assumptions don’t hold true for you, you may benefit from getting yourself up to speed with the fundamentals of Spring, Flex and BlazeDS, before you proceed further. That way you will get the most out of this article.

A few recommended resources for quick knowledge acquisition on the basics of Spring (especially Spring MVC based web application development), Flex and BlazeDS are:

Downloading and Setting Up the Software Stack

To get started download, install and configure all the following required pieces of software:

The list of software to install is long but I assume you will have a few of these already setup. At minimum I assume you will have the JDK installed on your machine. If not, then that’s the first piece of software you need to get.

Once Java is installed, go ahead and download ActiveMQ, JBoss AS, Spring Framework, Eclispe, Flex Builder Eclipse Plugin and the Spring-flex distribution. Go to the URL listed against the name of the software, in the list above, to get to the specific website. In each of the cases you will easily be able to locate the link to download the latest release build for the particular software. All pieces of software in the list, except the Flex Builder Eclipse plug-in are open source. You can get a 60-day trial version of the Flex Builder Eclipse plug-in, if you choose to get familiar with the tool before you plan to buy it. The preferred versions of the tools are listed against their respective names. It’s advised that you stick to those versions to avoid any additional configuration and integration complexities.

Walking through the installation and configuration of each of these pieces of software is beyond the scope of this article but you will find ample resources online to help you out in this regard. Here, I will point to a few important installation steps and configuration details only. You will have to piece the rest of it together, although I don’t anticipate you should have much trouble doing that.

Once you have JBoss AS and ActiveMQ downloaded and installed, which on most platforms translates to expanding the archive file to a folder, you should spend a little while configuring the two to work together. A great resource that explains the fundamental nuances of JBoss AS and ActiveMQ integration in a step-by-step manner is available online at http://activemq.apache.org/integrating-apache-activemq-with-jboss.html. The explanation is for version 4.x of ActiveMQ but it applies to the versions 5.x as well. The only step missing in this document is the inclusion of the core spring framework JAR file in the activemq-ra.rar folder that resides in the “deploy” folder of the JBoss AS. If this statement is not making much sense now, follow along the step-by-step instructions to integrate JBoss AS and ActiveMQ and then add the spring framework JAR file as a step before you run your tests to confirm that the integrated setup.

The next step should be to setup the IDE, namely Eclispe and the Flex Builder plug-in. Eclipse can be installed simply by expanding the archive distribution. The Flex Builder plugin-in installs with the help of a step-by-step wizard. If you choose to use Flex Builder 3.x use Eclispe 3.4. With Flash Builder 4 Beta (the new version of Flex Builder) you could use either Eclispe 3.4 or 3.5.

Last of all, download the Spring framework and Spring Flex distributions and expand the downloaded archive file to a folder in your file system. You will need a few JAR files from these distributions to make Flex work with Spring JMS.

Essential Spring-Flex Configuration for Messaging

In this section you will learn the essentials of Spring-Flex configuration, especially those that relate to message based interactions between the two. To keep things lively and in context, I will use the help of a simple example application that you can build along as you read this and the following sections.

As a first step open Flex Builder (now called Flash Builder) and create a new Flex project. Choose a Java EE (J2EE) server side and opt to create a combined Java/Flex project using Web Tools Platform (WTP). You will have the choice to leverage WTP only if you have the corresponding Eclipse plug-in installed. I name my project: “FlexSpringJMSExample”. You can use the same name or any other that you like. Your screen should look like Figure 1.

Once you click “next” the Flex Builder project creation wizard will take you to the next screen where you will be required to provide the following pieces of information:

  • Target runtime – the application server where the application will be deployed. In my case, a local JBoss instance is configured. If you don’t have once configured, click the “New” button next to this form field and follow along to create one.
  • Context root – The “context root” of a web application determines which URLs are handled by your web application. It’s the root of your web application.
  • Context folder – The folder where all the web content resides.
  • Flex WAR file – Old names sometimes stick for too long! LifeCycle Data Services (LCDS) and its open source extract BlazeDS, emerge from an earlier Adobe product called Flex Data Services, which was packaged under the name of flex.war. This form field expects you to point to the blazeds.war file in your file system.
  • Compilation options – You have a choice to compile locally, which I would recommend for development, or compile on the server.
  • Output folder – The folder where you want the compiled Flex output of your application to reside.

Look at Figure 2 to see what the corresponding screen for me looks like.

Clicking “next” at this second screen will take you to the last and final screen of the Flex Builder project creation wizard. In the last screen you will need to specify the following:

  • Main source folder – usually the default value of flex_src suffices in most cases.
  • Main application file – This is the name of the main Flex application file. Usually the default value is the same as the name of the application with “.mxml” appended to it. I like to keep it small and simple and stick to the convention of calling it main.mxml.
  • Output folder URL – the URL to access the application. Default works in this case.

Once you click “Finish” on this screen, the Flex/Java project with your required initial configuration is setup. The project folder structure as viewed in the “Flex Development” perspective should be as shown in Figure 3.

So far the project creation and setup has shown default behavior and not included anything specific to Spring or the Spring Flex project.

Modifying Configuration for Spring Flex Integration

The first file you want to modify is web.xml, which resides in the WebContent/WEB-INF/ folder of your project. The web.xml file is a file all Java web developers are familiar with. If you aren’t a Java web developer, let me in a single statement attempt to explain what this file does. The web.xml file is an essential piece of configuration, often referred to as the deployment descriptor, that defines how a web application should be deployed in a servlet container. When you create a Flex project with a Java EE (J2EE) server side, connected via LCDS or BlazeDS, a default web.xml file is created for you. To make your application work with Spring you need to modify this file. The new entries in the file should be as shown in Listing 1.

Listing 1: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

<display-name>Spring Flex Remoting Example</display-name>









 The salient configurations in the listed web.xml are:

  • The Spring MVC DispatcherServlet is configured. The DispatcherServlet acts as a front controller that dispatches incoming requests to commands. The DispatcherServlet in Spring BlazeDS dispatches all relevant requests to the BlazeDS MessageBroker.
  • All requests that include “/messagebroker/” in the URL are handled by the DispatcherServlet
  • The context loader loads a couple of config files in the /WEB-INF/config folder. These configure the Spring web application
  • Both index.html and main.html are treated as the starting point if no explicit html file is specified as a part of the URL. You may recall that I named my Flex applications’s main application as main.mxml. The html-temnplate generates a corresponding main.html file that wraps the Flex application within it. Therefore pointing the browser to http://localhost:8080/FlexSpringJMSExample will load the Flex application.

In Spring MVC applications each servlet with a name “servlet-name” has a corresponding configuration file named “servlet-name-servlet.xml” in its WEB-INF folder. This is a convention. However, as in the example you can choose not to put any configuration in this file and keep it fairly empty except the XSD defintions.
The primary Spring and Spring BlazeDS related configuration for the example application is in /WEB-INF/config/web-application-config.xml. The BlazeDS xml files remain in addition to this configuration. The values in the BlazeDS services-config.xml and its included xml files is left to its default entries.

Listing 2 shows the contents of web-application-config.xml. This file contains the Spring beans definition to instantiate and configure the following:

  • BlazeDS MessageBroker bootstrapped by Spring container.  Default configuration is applied, which is why a couple of lines alone do the job.
  • Connection to the ActiveMQ broker, which was setup with JBoss AS
  • JMS topic to allow messages exchanges
  • Spring Flex JMS destination for the defined JMS topic  to allow conversation between Flex and the server side JMS entities

 Listing 2: web-application-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

<!-- Embedded ActiveMQ broker-->
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp:(broker:(tcp://localhost:61616)?persistent=false)?marshal=false"/>

<!-- JMS Topic -->
<bean id="jmsTopic" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="sampletopic.inbound"/>

<flex:secured />

<flex:jms-message-destination id="jmsMsgDestination" jms-destination="jmsTopic" />


 That’s pretty much it! A few more details of the configuration are discussed in the section titled: “Message Service Integration”, later in this article.

With all the configuration done for now, there is one more step before you are ready to exchanges some messages using this setup. The missing step is to copy all the Spring and Spring Flex related JAR files to allow all the Spring beans based configuration to work.

Copying the Spring and Spring Flex JAR files

The following files in WEB-INF/lib are part of the regular BlazeDS distribution:

  • backport-util-concurrent.jar
  • cfgatewayadapter.jar
  • commons-codec-1.3.jar
  • commons-httpclient-3.0.1.jar
  • commons-logging.jar
  • concurrent.jar
  • flex-messaging-common.jar
  • flex-messaging-core.jar
  • flex-messaging-opt.jar
  • flex-messaging-proxy.jar
  • flex-messaging-remoting.jar
  • xalan.jar

In addition to these, add at minimum following JAR files to the WEB-INF/lib folder:

  • spring-framework-2.5.6.SEC01/dist/spring.jar
  • spring-flex-1.0.0.RELEASE/dist/org.springframework.flex-1.0.0.RELEASE.jar

For a smooth and quick start, I recommend you also add all the dependent spring module JAR files. Without all dependencies your application will not deploy and work. An alternative to bulk import of all Spring dependency JAR files is to selectively identify the required dependencies and add them in. In some cases, the dependencies are not obvious and you will only realize what’s required when you deploy the application to an application server (in my case JBoss) and the application server complains of the missing files.

With all setup and configuration done, you are ready to now exchange a few messages between Flex and JMS server side elements using your new infrastructure.

Simple Exchange of Messages

To exchange messages using our new installation, I will create a simple Java server side standalone program and a Flex based client. The Java program will send simple messages to a JMS topic and the Flex client will subscribe to the same topic. The messages will therefore flow from the Standalone program to the Flex application.

Messages can be sent either way and Java programs that act as JMS message producers and consumers can be managed entirely by Spring but for simplicity I will stick to a one way communication from a standalone Java producer to a Flex consumer. On the way the interception and transfer is enabled by BlazeDS, which is managed and configured with the help of Spring.

The Flex client includes a simple message consumer and adds all incoming messages to a simple TextArea. The code for the Flex client is shown in Listing 3.

Listing 3: Simple Flex JMS Consumer

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


import mx.messaging.messages.IMessage;

private function messageHandler(message:IMessage):void
messageLog.text += message.body + "\n";


<mx:ChannelSet id="channelSet">
<mx:AMFChannel url="http://localhost:8080/messagebroker/amflongpolling"/>
<mx:AMFChannel url="http://localhost:8080/messagebroker/amfpolling"/>

<mx:Consumer id="consumer" destination="jmsMsgDestination" channelSet="{channelSet}" message="messageHandler(event.message)"/>

<mx:Panel title="JMS Consumer" width="100%" height="100%">
<mx:TextArea id="messagelog" width="100%" height="100%"/>



The JMS producer is equally simple. It connects to the same JMS topic as the consumer and sends simple text messages on it. The JMS provider in our case is ActiveMQ. Include the activemq-all-5.2.0.jar in your standalone Java program’s classpath to make the JMS and ActiveMQ classes available to it.

 Listing 4: TopicProducer.java

package com.treasuryofideas;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.TextMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQMapMessage;

public class TopicProducer {

private final String url = "tcp://localhost:61616";

    private Connection connection;

    private Session session;

    private Topic topic;

    private MessageProducer producer;
* @param args
public static void main(String[] args) {
new TopicProducer();
// TODO Auto-generated method stub

public TopicProducer() {
try {

            ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(this.url);
            this.connection = factory.createConnection();
            this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            this.topic = this.session.createTopic("sampletopic.inbound");

            this.producer = this.session.createProducer(this.topic);
            for(int i=0; i<1000; i++) {
             TextMessage textMessage = this.session.createTextMessage("test message");
                MapMessage message = this.session.createMapMessage();
                message.setString("userId", "user");
                message.setString("chatMessage", "passoword");
                System.out.println("Message sent" + i);


        } catch (JMSException e) {

To run your example, first deploy the Flex Spring BlazeDS application and access the Flex client and then start the JMS producer. This sequence is necessary as the Flex client sets itself up as a consumer only on the creationComplete event of the application.

Although the example is elementary, it shows clearly how simple and easy Spring BlazeDS makes the JMS interactions between Flex and Spring. In the next section a brief survey of the message service integration provides additional details on how message exchanges could be established effectively between Flex and a Spring based application.

Message  Service Integration

Spring BlazeDS defines the following three message service components on the server side:

  • Native built-in BlazeDS AMF messaging
  • JMS messaging using the Spring-specific JMS components
  • Spring BlazeDS messaging integration

The messaging infrastructure in the Flex framework imposes little restriction on the messaging protocol or messaging domain on the server side. Therefore multiple types of messaging services, as enumerated above, can be used. Let’s explore the three types of message service components a bit more to understand what they bring to the table.

Native built-in BlazeDS AMF messaging

BlazeDS supports an ActionScriptAdapter for simple message routing between two or more Flex clients. The communication between the two or more Flex clients happens via a server-side destination. This messaging adapter is limited in its functionality. The core of the messaging adapter is the two methods that help route messages. These two methods are:

  • pushMessageToClients — Delivers message to all clients connected to a server
  • sendPushMessageFromPeer — Delivers messages to peer servers in the cluster, which in turn deliver the message to connected clients

To use this adapter, you will typically configure a server-side destination and assign the ActionScriptAdapter as the adapter to use. In addition, you would also configure a messaging channel, probably a polling AMF channel. In standard BlazeDS such configuration resides in the messaging-config.xml configuration file. The messaging-config.xml file is included in the services-config.xml file by reference.

In Spring BlazeDS such a messaging adapter is configured with only a few lines of configuration as follows:

channels="my-polling-amf, my-secure-amf"

Just <flex:message-destination id="myTopic" /> is enough if you are using the default adapter and the default channel.

JMS messaging using Spring specific JMS components

The Spring framework defines a couple of components to interact with JMS message domains: queues and topics. It includes a template-based solution, JmsTemplate, to send and receive JMS messages. The JmsTemplate eliminates much of the boilerplate code associated with opening and closing connections and sessions and sending and receiving messages. It also transforms the JMSException into part of Spring’s runtime exception hierarchy. JMSException is converted to org.springframework.jms.JmsException. Spring simplifies access to and programming with many resources such as JDBC, JNDI, and JMS by defining templates that help eliminate much of the boilerplate code and let you focus on core tasks.

While a JmsTemplate simplifies sending and receiving messages, receiving messages using the JmsTemplate is synchronous. Synchronous message listeners are not efficient, as they involve blocking operations. Resources like threads wait until a message arrives. In asynchronous operations such threads could gainfully carry out other operations in this waiting time. To address this situation (where synchronous messaging listeners blocked resources), MessageDriveBeans (MDBs) were introduced into Java EE. EJB containers could then listen to JMS destinations and trigger an MDB when a message arrived. The Spring framework extended this concept to POJOs and, therefore, makes it easy to have asynchronous message listeners without the need for EJB containers. Spring’s counterparts of a MDB are a Message Driven POJO (or MDP). You can also write an asynchronous JMS message listener without Spring, although MDPs are a robust set of asynchronous message listeners that you could readily use.

You have seen a simple usage of the Spring BlazeDS JMS configuration in the simple example earlier in this article.

Spring BlazeDS Messaging Integration

Spring BlazeDS defines org.springframework.flex.messaging.integration.IntegrationAdapter, which enables sending and receiving of messages via Spring BlazeDS’s message channels. Complicated message routing could be established using this adapter. You will also be able to connect to FTP and email endpoints using the integration adapter.

As an example a Spring extension project, called SESIA, provides an FTP adapter that works with the integration adapter. You can get more information on the SESIA project online at http://opensource.atlassian.com/confluence/spring/display/INTEGRATE/SESIA.


With a brief overview of the available message exchange options its time to wrap this article up. I assume this article has familiarized you with the way you could combine Flex and Spring JMS applications. With your whetted appetite you may be enthusiastic to learn more and explore the advanced configuration. Many interesting details are covered in my book Professional BlazeDS (Wiley, 2009) that you may want to get hold of. In addition, keep an eye on more articles on the topic that I intend to write as my time permits.



Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}