YOUR FEEDBACK
cautionyou wrote: I agree with that the biggest change is the breadth of the projects that are hap...
Cloud Computing Conference
March 22-24, 2009, New York
Register Today and SAVE !..


2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TODAY'S TOP SOA & WEBSERVICES LINKS


JMS and XSLT for E-Business Messaging
JMS and XSLT for E-Business Messaging

XML is the new lingua franca of interapplication communication and a very rich language for describing complex business data in a heterogeneous way. Today's business environment requires building new systems that exchange XML transactions between a diverse set of applications across physical domains and corporate boundaries. Manufacturers, buyers, and suppliers have the luxury of participating in a variety of global trading exchanges to participate in a supply chain.

Java Message Service (JMS) and XML are an ideal marriage in that JMS provides a simple yet robust way of transporting XML data between applications. XML by itself doesn't have a reliable transport mechanism. Unreliable wire protocols such as HTTP and SMTP require the complex overhead of application-level error handling to deal with failure scenarios of data transmission. JMS has all the semantics of failure scenarios built in via a loosely coupled disconnected operation, persistent messaging, internal acknowledgment of message receipt, and rules of engagement regarding transactional recovery and message redelivery. For these reasons some e-marketplaces, such as those powered by Commerce One, have chosen to use JMS as the underlying communications protocol for connecting a global e-marketplace in a secure, reliable, and highly scalable fashion (see Figure 1).

Just as JMS is ideal for plugging together business partners in a trading exchange, it also provides a single common infrastructure for connecting diverse applications within an enterprise. Within your corporation you likely have a diverse set of applications that deal with procurement, billing, and fulfillment.

While XML is excellent for describing complex business documents used by these types of applications, there are still many conflicting models for how it describes these documents. As a manufacturer supplying goods in a supply chain, you may have your own suppliers that feed into your business processes. As illustrated in Figure 2, this will likely involve multiple trading exchanges - each will have its own way of describing common business objects, such as a purchase order. You may have chosen to use one set of standards for internal XML documents, yet have a need to communicate with another organization that uses a different standard. For these reasons the ability to translate XML documents from one form to another is required.

This article explains why JMS is the premier solution for connecting applications in a diverse B2B environment. It explains how XSLT and XPATH can play a critical role in the data translation process by showing how an XSLT-based data transformation engine can be used as a pluggable component in a JMS system to perform these translations. Specifically, I'll use the Apache XALAN XSLT processor as a specialized JMS client to translate between a Commerce One xCBL purchase order document and a RosettaNet purchase order document. Before we get into that, a brief description of JMS is in order.

The Java Message Service
JMS provides a standardized common API for applications to communicate with each other. The API is simple yet flexible. There are three fundamental concepts to understand when using a JMS system: connect, send, and receive. If you understand these concepts, then you're well on your way to becoming a JMS programmer.

JMS is not just a server-based event service. It's a stand-alone enterprise middleware in its own right, on equal footing with other RPC-like communications, such as CORBA, RMI, and EJB. In addition, it can be complementary to those types of communication middleware through application server interfaces.

The base premise of JMS is that it provides a loosely coupled asynchronous communication layer. Senders and receivers (producers and consumers) are abstractly decoupled from each other. Senders construct self-contained messages (including, but not restricted to, XML documents) and send them to the JMS system. Receivers register their interest in those messages by subscribing to a set of publish-and-subscribe topics or by listening on a point-to-point queue. As illustrated in Figure 3, senders and receivers don't necessarily know about each other directly.

There are multiple messaging models supported by JMS. The publish-and-subscribe (pub/sub) model is well suited to a one-to-many broadcast of information. Senders publish information on a topic, and one or more receivers register their interest in that topic by subscribing to it. The point-to-point (P2P) queuing model is better suited for creating a "pipe" between two known end points. With either model, it's the responsibility of the JMS system to perform the routing and delivery of the messages to their intended destinations.

Both models allow for either an event-driven asynchronous receipt of messages through message handler callbacks or a synchronous receipt of messages through a more proactive "pull" model.

While JMS messaging is largely intended for passing autonomous messages between applications, there are also design patterns and helper classes for performing both synchronous and asynchronous requests/replies on top of pub/sub and point-to-point.

In addition to a simple API and the multiple messaging models, JMS also prescribes a common set of concepts and semantics for message delivery, including:

  • Once-and-only-once delivery
  • At-most-once delivery
  • Store-and-forward
  • Disconnected receivers
Once-and-only-once is the most stringent delivery mode, ensuring that regardless of failure and recovery conditions, a purchase order is guaranteed to get to its intended destination(s) and will get there only once. This is commonly referred to as guaranteed messaging. At-most-once is the least stringent delivery mode in that a message is allowed to be lost along its way due to failure conditions. An application that uses this delivery mode must be written so that it's capable of receiving duplicate messages and occasionally missing some of them. An example I like to use is a stock ticker broadcast - if one is lost, another one will be along in a matter of seconds.

JMS guaranteed messaging is accomplished through a store-and-forward mechanism. Store-and-forward means that a sender can deliver a message to the JMS system, which holds it in a persistent store until it's been successfully delivered to all of its intended recipients. This, combined with a strict set of internal rules for acknowledgment of message receipt, allows the message itself to survive any system failures. Failure scenarios not only include network and hardware failures or an untimely demise of a receiving application, but can also include a normal scheduled downtime of a receiving application. This allows applications within a distributed system to be taken down and brought back up at will, without affecting the overall health of the system. The JMS system will store all messages on behalf of a disconnected receiver until that receiver becomes available again, then forward all the messages missed while it was out of contact.

XML Translation as Part of a JMS-Enabled Business Process
When using a JMS-based communications layer, it's a simple and straightforward process to plug in a data translation engine that "intercepts" the communication line between two applications. As Figure 4 illustrates, an application may publish or send on a topic or queue that the translation engine listens on. In this example the translation engine listens on the "xCBL-PO" queue, performs the translation, then sends the message back out using the "Rosetta-PO" queue. The ERP system, which expects to receive purchase orders in a RosettaNet format, simply listens on the "Rosetta-PO" queue for incoming messages.

In practice, Figure 4 could be extended a bit more. Eventually, the initial PO may need to receive an application-level response. This means that the ERP system would route another message back to the translation engine, which would in turn convert it back into xCBL format.

Next we'll examine the purchase order documents, which are vastly different, and the XSLT stylesheet that performs the translation. For the purposes of this discussion, we'll hone in on a small portion of the translation to explain the concept. A full listing of the xCBL and RosettaNet purchase orders, the XSLT stylesheet, and the JMS application can be found at http://developer.sonicmq.com.

An excerpt from the xCBL purchase order (CBL_PO.xml) shows an address that will be translated (see Listing 1).

The excerpt from the RosettaNet purchase order (Rosetta_PO.xml) in Listing 2 is the resulting output.

The excerpt from the stylesheet (CBL2Rosetta_PO.xslt) in Listing 3 is what does the conversion. The CBL2Rosetta_PO.xslt file is a prime example of the fill-in-the-blanks XSLT design pattern. This style is similar to many dynamic Web page languages, such as JSP and ASP. It's most useful when the format of the input is predictable. When the input format becomes unpredictable, the stylesheet would be written in a rule-based manner.

XPath is used extensively throughout the stylesheet. Every select statement in the <xsl:value-of> elements is an XPath expression. The main constructs used are the abbreviated relative location path "/" and the abbreviated step ".". The "/" specifies an immediate child, while a "//" specifies any descendant. The "." is shorthand for the current node. For example: .//address/name is a name element that's the immediate child of an address element descended from the current node.

The idea behind this process is that the stylesheet most closely resembles the resultant output. This method is the most basic type of XSLT transformation. The input is structured in a way that's incompatible with that of the desired result; therefore, the data must be placed in the desired result structure. This is carried out by creating the desired result structure and plugging in <xsl:value-of> tags as place holders for the input data. These tags use XPath select statements to identify the input data that should be plugged in at runtime. This block uses two structures that differentiate it from the simplest case. The <xsl:variable> tag declares the buyer-Address variable to be the NameAddress element of the buyer. This allows the following select statements to use this element as opposed to specifying ".//BuyerParty//NameAddress" every time. Since the Address2 element is optional, this block makes use of the <xsl:if> element that tests for the existence of an element before plugging in the <addressLine2> values.

The data contained in the source is also different and must be programmatically transformed. This task is accomplished through the use of an Apache Xalan extension that allows you to make calls of arbitrary Java objects. These calls are all preceded by "java:" and reference methods in the PurchaseHelper class. The methods convert xCBL data types into RosettaNet types. The best example of these is the DateStamp. The input date in the xCBL format looks like this:

&ShipByDate>19990809T01:01:01</ShipByDate>
The output date in the RosettaNet format looks like this:
<requestedShipDate>
<DateStamp>
20990809Z
</DateStamp
> </requestedShipDate>
The tag in the stylesheet that does the transformation looks like this:
<requestedShipDate>
<DateStamp>
<xsl:value-of select="java:article.PurchaseHelper.cbl2RosettaDate(string($ship Date))"/>
</DateStamp>
</requestedShipDate>

When the XSLT processor encounters this tag, it invokes the following piece of Java code in the PurchaseHelper class:

public static String cbl2RosettaDate(String cblDate)
{
//Trim off the time because rosetta only wants date
String date=cblDate.substring(0, cblDate.indexOf("T"));

//the last six digits are in the correct format
String newDate=date.substring(2);

//Rosetta wants century as opposed to year, so add 1 to the first 2 digits
String century=""+(Integer.parseInt(date.substring(0,2))+1);
return century+newDate+"Z";
}

Finally, we'll show the JMS client application that receives the purchase order on a point-to-point queue, invokes the translator, and sends the newly translated purchase order back out on another queue.

First, the constructor initializes the JMS provider and the XSLT translator (see Listing 4). It takes as parameters the host name of the message server, the name of the queue to receive the PO on, and the name of the stylesheet to use for the transformation. It's important to note in this example that the host name of the message server is applicable only if the application uses the JMS provider's dynamic APIs to locate a JMS ConnectionFactory object. JMS prescribes the use of JNDI to store and retrieve a ConnectionFactory object. Most JMS providers support both JNDI access and a proprietary API for dynamic creation of ConnectionFactories.

The onMessage() callback is an event-driven message handler that gets invoked asynchronously by the JMS provider when a new message arrives. It's responsible for extracting the contents of the message, performing any business logic necessary, and possibly sending out new messages as a result of the processing. In our case it extracts the xCBL purchase order document using the msg.getText() method, then passes it on to the XSLT processor (see Listing 5).

As an alternative to the onMessage handler, we could have used the receive(), receive(long timeout), or the receiveNoWait() methods on the QueueReceiver object to proactively "pull" the messages from the queue.

The processPurchaseOrder() method, which is called by the onMessage() handler, simply sends the newly translated XML document on another queue to be processed by an application that expects to receive RosettaNet purchase orders. The message is sent persistently, with a default priority, and 30 minutes to expire.

public void processPurchaseOrder(String po)
{
TextMessage msg = qSession.createTextMessage(po);
queueSender.send(msg, // the message
javax.jms.DeliveryMode.PERSISTENT, // delivery mode
javax.jms.Message.DEFAULT_PRIORITY, // priority
1800000);// Time to live (30 minutes)
}
Initialize the XSLT processor:
private void xsltInit(String receiveTransform) {
this.receiveTransform=receiveTransform;
try {
processor = XSLTProcessorFactory.getProcessor();
}
catch(SAXException saxe) {
System.err.println("error - Cannot initialize xslt processor.\n");
saxe.printStackTrace();
System.exit(1);
}
}

Initialize the JMS provider. This involves obtaining a ConnectFactory object. The ConnectionFactory object may be obtained via a JNDI lookup().

private void jmsInit(String broker, String receiveQueueName, String sendQueueName) {
try {
Properties env = new Properties(); // specify the JNDI properties specific to the JNDI SPI being used
...
IntialContext jndi = new InitialContext(env);
QueueConnectionFactory factory = (QueueConnectionFactory)jndi.lookup(broker);
From the factory, obtain a connection object. From the connection, create a JMS Session object. The Session is responsible for managing the sending and receiving of messages. It creates senders and receivers and handles the various acknowledgment modes of JMS.
connection = factory.createQueueConnection();
qSession = connection.createQueueSession(false,
javax.jms.Session.AUTO_ACKNOWLEDGE);
}
catch (javax.jms.JMSException jmse) {
System.err.println ("error: Cannot connect to broker- " + broker + ".\n");
jmse.printStackTrace ();
System.exit(1);
}
Obtain a queue and create a receiver to listen for messages. In JMS, queues are also administered objects accessible through JNDI. Note that the call to setMessageListener(this) is what establishes this onMessage() callback to be associated with the receiver. The connection.start() is what tells the JMS provider that it's okay to start delivering messages to the onMessage() handler. Also, obtain a queue and a QueueSender to send the translated PO to.
try {
Queue receiveQueue=jndi.lookup(receiveQueueName);
Queue sendQueue=jndi.lookup(sendQueueName);
QueueReceiver receiver = qSession.createReceiver(receiveQueue);
QueueSender sender = qSession.createSender(sendQueue);
receiver.setMessageListener(this);
connection.start();
}
catch (javax.jms.JMSException jmse) {
System.err.println ("error: Cannot start connection.\n");
jmse.printStackTrace ();
System.exit(1);
}
}
To do a proper cleanup, close the connection. This allows the JMS provider to free up any
resources that are no longer needed.
public void finalize() {
try {
connection.close();
}
catch(JMSException jmse) {
System.err.println("error: Cannot close connection.\n");
jmse.printStackTrace();
}
}
public static void main(String[] args)
{
PurchasingApplication purchasingApplication1 =
new PurchasingApplication("localhost:2506", "CBL-PO",
"Rosetta-PO", "xml\\CBL2Rosetta_PO.xsl");
}
}

That's all you need to do!

In summary, XML is an ideal way to represent complex business data. An XSLT transformation engine is an excellent means of converting from one type of XML document to another. JMS is a simple yet flexible method of transporting XML documents between applications in a guaranteed fashion. So go to your favorite JMS vendor today, and get the message

About Dave Chappell
David Chappell is vice president and chief technologist for SOA at Oracle Corporation. Chappell has over 20 years of experience in the software industry covering a broad range of roles including Architecture, code-slinging, sales, support and marketing. He is well known worldwide for his writings and public lectures on the subjects of Service Oriented Architecture (SOA), the enterprise service bus (ESB), message oriented middleware (MOM), enterprise integration, and is a co-author of many advanced Web Services standards. Chappell is a regular contributor to SOAWorld Magazine and a speaker at the "SOA World Conference & Expo" since 1999.

XML JOURNAL LATEST STORIES . . .
A round-up of the many themes and topics of interest to infrastructure architects, developers and IT managers featuring at SYS-CON's Cloud Computing Expo being held November 19-21, 2008 at The Fairmont Hotel in San Jose, California. The conference is expecting a record turnout of senio...
SYS-CON Events announced today that the leading global SOA, Virtualization, Cloud Computing and Open Source technology provider FreedomOSS named "Gold Sponsor" of SYS-CON's SOA World Conference & Expo which will take place November 19-21, 2008, at the Fairmont Hotel in the heart of Sil...
Cloud Computing offers significant benefits over traditional solutions for deploying production systems as well as for conducting development and testing activities. This session will distill the unique characteristics of clouds and describe how to best think about deployments in the c...
Intel has just released Intel XML Software Suite 1.2. This latest release helps maximize XML performance, while minimizing the effort for any Enterprise, SOA, SaaS, and Web 2.0 based applications. Intel XML Software Suite 1.2 optimizes XML application performance, takes full advantage ...
SYS-CON Events announced today that the leading global SOA, Virtualization, Cloud Computing and Open Source technology provider Intel named "Gold Sponsor" of SYS-CON's SOA World Conference & Expo which will take place November 19-21, 2008, at the Fairmont Hotel in the heart of Silicon ...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS


ADS BY GOOGLE