ebXML     Peter Komisar © Conestoga College  v.1.1  /  2005
references:  ebXML Technical Architecture Specification v1.04, Business
Process Specification Schema v1.01, Message Service Specification v2.0

http://ebxml.org/specs/index.htm


// This ebXML note is provided to provide background to how 'profiles' are

//
at supported in JAXM messaging. The following material is a cursory look
// ebXML specifications, which is the biggest yet, including several
// specifications in total numbering hundreds of pages. The following
// material regarding ebXML should be considered quoted from the ebXML
// specifications available at the ebXML.org site. This material is not a
// publication and has been prepared strictly for private academic use.



The Web Service Protocol Stack

We have discussed the basic Web service transport system, SOAP, the
service description layer, WSDL and the the discovery layer UDDI, which
abbreviates '
Universal Description, Discovery and Integration'. There are
two more layers envisioned to complete the Web service stack. There
is a 'Composition' layer represented by WSFL or Web Service Flow Language.
and a Conversation Layer which may be implemented using WSCL or
Web Service Converation Language.

The Conversation and Composition layers described in the following table
recognize that business interactions are typically more complex than simple
request responses or one-way messages and may involve many coordinated
steps to complete a given transaction.



Following is a depiction in table form of the Web Services Stack

 Stack Layer
 Language
 Description
 Conversation
 WSCL 
 Web Service Conversation Language -describes
 service interactions, transactions, requests
 responses etc.
 Composition
 WSFL
 Web Service Flow Language - composes
 complex services  from a collection of simpler
 services.
 
 Directory Lookup
 & Discovery
 UDDI
 Universal Directory - supplies a registry to find
 and discover services
 Service Description
 WSDL
contains three sub-layers the lowest is an interface
description, next up is a service implementation
and finally a web service endpoint sublayer is
used to add information about issues like quality
of service, (QoS) and security.
 Transport Layer
 SOAP
 XML 
 HTTP
 Simple Object Access Protocol is the carrier for
 the web service messaging system, is based on
XML support and carried over standard TCP/IP
 application layer protocols like HTTP, FTP or
 SMTP. 


While the layers described seems to be unambiguous, separating out 'flows'
and 'conversations' may be artificial abstractions, as many 'higher level' Web
service applications seem to incorporate many or all the features described
from SOAP up. The result may be many competing 'higher level' Web service
applications. Java's API for XML Registries actually anticipates this, ready
to serve as an umbrella for different Registries.

A parallel can be drawn betwen JDBC and JAXR where different registries
such as UDDI and ebXML act like databases that can be queried, and
manipulated all from within an all Java context. Registry-Specific Provider's
are like JDBC drivers. The JAXR vision of Web
services looks like the following.


JAXR Architecture 


         JAXR Client
          
// capabilities
              |
     JAXR Pluggable  Provider
// single abstraction represent a set of specific providers
     _______________|_______________
     |                          |                          |
ebXML       UDDI        Other     
Provider   Provider     Providers

     |                          |                          |
// ebXML /          UDDI /                   Other /
  
SOAP               SOAP                   SOAP
   |              |              |
 ebXML      UDDI        Other   

    


Simple Example Showing Complex Transaction

To bring the idea of why these higher level XML applications are needed,
consider, as an example, paying a bill using your bank account which
is accessed over the Internet. We might have to follow the follow steps
which may be thought of as a 'dance' or choreography. Another way to
describe such an exchange is in terms of a complex transaction.

Bank Bill Payment Over the Internet

1) Locate main page
2) Provide user name password  // presuming correct proceed otherwise try again
3) Select Action  // Bill Payment
4) Enter Who is being paid, how much on what account
5) Bank acknowledges and wishes you to confirm or change information
6) On confirmation transact against account // on change requires different a process
7) Bank returns confirmation of transaction information // perhaps print hard copy
8) Log off // clear cache!
 


High Level Web Services Languages

WSCL ( Web Service Conversation Language)  and WSFL (Web Service Form Language)
are a two of many attempts to create XML dialects that describe the more complex
business activites. One of these 'higher level' dialects is ebXML.
ebXML  supplies a
framework for describing complex exchanges of information in a standard manner so
that companies can make similar sorts of transactions.

Because ebXML is supported by JAXM we should take a brief look at ebXML.

The ebXML dialect is one of a few variations that describe how the highest
levels Web services stack may be used.  They describe 'transactions',
'flows' 'collaborations' and 'choreographies'. The main site for ebXML is at
the following URL.

ebXML
http://www.ebxml.org/ 

The site is hosted by OASIS so clearly ebXML is supported by them.
The specifcation covers several subtopics and is collectively hundreds
of pages in length. The following excerpts are from an interesting interview
that gives a good overview of what ebXML is about. The interview was
conducted by John Kirkley. The full article can be read at the following URL.

http://developers.sun.com/sw/building/tech_articles/ebxml.interview.html


Excerpts from "ebXML: An Interview with Sun Expert Ed Bratt", Sept. 18, 2002, by John Kirkley 

When Sun Microsystems acquired Forte, one of the people who made the transition was Ed Bratt, who had been responsible for Forte's EAI business process integration product. Today, as development manager for Sun ONE Business Integration Products, Bratt is keeping close tabs on ebXML and how it fits into the Sun ONE infrastructure.

Q:What is ebXML and why should developers care?
EB: ebXML is a collection of standards developers can use to collaborate with other businesses over the Internet. It is not a competitor to Web services and SOAP -- they solve different kinds of business collaboration problems. However, ebXML uses parts of the SOAP, WSDL, and UDDI infrastructure for a myriad of new component and application integration opportunities.

Q: What are ebXML's capabilities?

EB: The most basic and well-defined part of the ebXML specification is the messaging architecture. This is a reliable system for exchanging any kind of document using standard Internet protocols. The format consists of an XML document with the control information required to exchange the message, as well as a collection of attachments that are the actual business documents you wish to exchange. This is all wrappered in a SOAP package for transport. ebXML extends the SOAP protocol by adding support for attachments, security, and reliable delivery. One of the great things about ebXML is that anyone can build a messaging endpoint to send and receive these messages.

Q: Are there any limitations on the kinds of documents businesses can exchange?
EB: No, you can specify any kind of document -- it can be a text document, a spreadsheet, or an XML document -- ebXML doesn't care. You can even exchange traditional EDI messages. This allows partners using ebXML to be very flexible and exchange documents irrespective of their content.    . . . ebXML allows users to define the interactive collaboration between partners that allows them to conduct business that requires more than one step. This is defined by the Business Process Schema Specification (BPSS) and allows each party to understand the context and logical order of any particular business exchange.

For example, if I am going to send a shipping confirmation, I would like to know that I have a confirmed order before I send the goods. ebXML has the capability to define business processes
for specific exchanges as well as for long-term collaborations. The business process can also be defined as a class diagram of business objects in UML and business rules, exchanged in XML.

Another problem we are attempting to solve is the fact that most EDI documents are deeply siloed -- a purchase order from the medical industry and one from the automotive industry have little overlap in their schemas even though they have common elements such as customers, units, and pricing. So if I want to build a system, I really can't leverage what I get from separate sources. One of our jobs is to build a core components library -- a library of common terms and definitions. This Universal Business Language (UBL) will allow everyone to communicate.


// "ebXML aims to define in XML a core set of business components that form a library of common terms"

The above interview pointed out that ebXML is a messaging system focused
on exchanging business documents. ebXML aims to define in XML ( and UML )
a core set of business components that form a library of common terms
. These
terms are designed to serve in simple communications but also to allow more
complex sorts of transactions and exchanges of information. An important part
of the ebXML transport mechanism is the use of attachment to exchange actual
business documents.


ebXML Documents

The ebXML specification is described in a set of related documents.
They include ebXML specifications on the following topics:

  1. Requirements
  2. Business Process and Information Meta Model
  3. Core Components
  4. Registry and Repository
  5. Trading Partner Information
  6. Messaging Services
The specifications can be found at:

Overview of ebXML Goals

ebXML is focused on supplying a electronic business solution that improves
on EDI, (Electronic Data Interchange) while still taking advantage of the proven
business features that have been developed and are embodied in the EDI system.
The following quotes supply the classic criticisms of EDI followed by an explanation
of how ebXML seeks to supplant EDI without losing investment that may have been
made into EDI.

// ebXML seeks to improve on EDI while not losing a firm's EDI investment

"For over 25 years Electronic Data Interchange (EDI) has given companies the
prospect of eliminating paper documents, reducing costs, and improving efficiency
by exchanging business information in electronic form. Ideally, companies of all
sizes could conduct eBusiness in a completely ad hoc fashion, without prior
agreement of any kind. But this vision has not been realized with EDI; only large
companies are able to afford to implement it. . . . much EDI-enabled eBusiness is
centered around a dominant enterprise that imposes proprietary integration
approaches on its Trading Partners."   - ebXML Technical Architecture Overview

// in EDI biggest partners dictate terms of data communications


The ebXML Technical Architecture Specification provides an example scenario
that introduces the following key concepts and underlying architecture: Even
without looking at the example, it is instructive to consider these points as
a means of characterizing what ebXML does.

Key Features Underlying the ebXML Architecture

1. A standard mechanism for describing a Business Process
and its associated information model.  // Business Process Description

2. A mechanism for registering and storing Business Process
and Information Models so they can be shared and reused. // registration

3. Discovery of information about each participant including:   // discovery
             ·  The Business Processes they support.
             ·  The Business Service Interfaces they offer in support of the Business Process.
             ·  The Business Messages that are exchanged between their respective Business
                 Service Interfaces.
            ·  The technical configuration of the supported transport, security and encoding protocols.
 
4. A mechanism for registering the aforementioned information so
that it may be discovered and retrieved.   // registering discovery information

5. A mechanism for describing the execution of a mutually agreed upon business
arrangement  which can be derived from information provided by each participant
from above. (Collaboration Protocol Agreement   CPA)    // collaboration agreements

6. A standardized business Messaging Service framework that enables interoperable,
secure and reliable exchange of Messages between Trading Partners. // messaging service

7. A mechanism for configuration of the respective Messaging Services to engage
in the agreed  upon Business Process in accordance with the constraints defined
in the business arrangement.
// messaging service configuration


Summary of steps involved in Utilizing an ebXML Registry


Implementation and Registration


1 ) Company A - describes business process and builds a local system implementation.
                       - registers implementation details
                       - registers a company profile


Registering Business Process(es) and Company Profile

CompanyA ----- registers implementation details and Company A Profile -- >  ebXML Registry
// the ebXML Registry stores Business Scenarios and Business Profiles in XML descriptions


Search & Discovery

A Second company might do a search and query for Company A's profile.


Company Query and Subsequent Scenario & Profile Downloads

Company B
-- queries for Company A's profile -->   ebXML Registry
                    <-- downloads scenarios and profiles --<   
// Company B queries using an ebXML compliant application



Business Agreement

Company B contacts Company A and agree on a Business Arrangement.

Company B <-- direct communications establish business arrangement --> Company A


Business Transactions

B-2-B Business Transactions ensue.




The ebXML Registry, Interfaces & Messaging Service

       
Following is a diagram showing basic interaction between an ebXML Registry
Service and a Trading Partner.


Basic interaction between an ebXML Registry Service and a Trading Partner.


Trading Partner >--  Request   -->  ebXML
Registry
               <- Receive Update-<        |
                                      |___ Business Process & Information Models
                                      |___ Business Library
                                      |___ Core Library
                                      |___ Collaboration Protocol Profiles



Core Aspects of ebXML

ebXML Messaging: The query syntax used by the Registry access mechanisms is
independent of the physical implementation of the backend system.The ebXML
Messaging Service MAY serve as the transport mechanism for all communication
into and out of the Registry.

Business Process: Business Processes are published and retrieved via ebXML
Registry Services.

Core Components: Core Components are published and retrieved via ebXML Registry
Services.

Any item with metadata: XML elements provide standard metadata about
the item being managed through ebXML Registry Services. Since ebXML Registries
are distributed each Registry MAY interact with and cross-reference another ebXML
Registry.

Registry Items and their metadata MAY also be addressable as XML based URI
references using only HTTP for direct access.

ebXML Messaging Service

The ebXML Message Service mechanism provides a standard way to exchange
business Messages among ebXML Trading Partners. The ebXML Messaging Service
provides a secure, consistent and reliable mechanism to exchange ebXML Messages
 between users of the ebXML infrastructure over various transport Protocols
(possible examples include SMTP, HTTP/S, FTP, etc.).

The ebXML Messaging Service does not place any restrictions on the content of the
payload. The ebXML Messaging Service supports simplex (one-way) and request/response
 (either synchronous or asynchronous) Message exchanges.

The ebXML Messaging Service performs all security related functions including:
The ebXML Messaging Service provides ebXML with an abstract Interface whose functions,
at an abstract level, include:

ebXML Message Service Protocol Core Functionality

Packaging Specification -  A description of how to package an ebXML Message and its
associated parts into a form that can be sent using a communications protocol such as
HTTP or SMTP.

ebXML SOAP Envelope Extensions
- A specification of the structure and composition
of the information necessary for an ebXML Message Service to generate or process an
ebXML Message

Error Handling   A description of how one ebXML Message Service reports errors it
detects to another ebXML Message Service Handler

Security   Provides a specification of the security semantics for ebXML Messages (sectio

SyncReply   Indicates to the Next MSH whether or not replies are to be returned
synchronously.

ebXML Message Structure Using SOAP

The ebXML Message Service Specification defines a set of namespace-qualified SOAP
Header and Body element extensions within the SOAP Envelope. These are packaged
within a MIME multipart to allow payloads or attachments to be included with the SOAP
extension elements.

Core Extension Elements include
Additionally there are a large sets of Security, Message Reliability and Error elements that
may be used in an ebXML Messages.

The following example shows a sample of a ebXML message. Notice in this example
the body is empty and all the messaging is included in a MessageHeader element
that is enclosed in the SOAP Header element. If the SOAP body is used in ebXML
it is used for holding additional ebXML header information. If a Manifest element was
present it would contain reference elements that would point to 'payload' data carried
as MIME attachments.


Ping ebXML Message Example From the ebXML Messaging Service Specification

<?xml version="1.0" encoding="UTF-8"?>
<SOAP:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/"
xsi:schemaLocation="http://schemas.xmlsoap.org/soap/envelope/
http://www.oasis-open.org/committees/ebxml-msg/schema/envelope.xsd">
<SOAP:Header xmlns:eb="http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd"  xsi:schemaLocation="http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd  http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd">
<eb:MessageHeader version="2.0" SOAP:mustUnderstand="1"
xmlns=eb:"http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd"
xsi:schemaLocation="http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd
http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd">
<eb:From>
<eb:PartyId>urn:duns:123456789</eb:PartyId>
</eb:From>
<eb:To>
<eb:PartyId>urn:duns:912345678</eb:PartyId>
</eb:To>
<eb:CPAId>20001209-133003-28572</eb:CPAId>
<eb:ConversationId>20010215-111213-28572</eb:ConversationId>
<eb:Service>urn:oasis:names:tc:ebxml-msg:service</eb:Service>
<eb:Action>Ping</eb:Action>
<eb:MessageData>
<eb:MessageId>20010215-111212-28572@example.com</eb:MessageId>
<eb:Timestamp>2001-02-15T11:12:12</eb:Timestamp>
</eb:MessageData>
</eb:MessageHeader>
</SOAP:Header>
<SOAP:Body/>
</SOAP:Envelope>
--ebXMLBoundary

// we can continue with JAXM. I hope you will see where the overview
// of ebXML becomes useful when we look at JAXM messaging profiles

The Business Process Specification

We can't go any further without losing steam we need for JAXM, however
inspecting the schema and xml instance document for the ebXML Business
Process Specification gives a quick idea of the sort of exchanges that are
described in the specification.




 JAXM           Peter Komisar © Conestoga College  v.1.0  /  2005

references: JAXM 1.1.2 Reference Implementation documentation,
jaxm1.1.2/docs/index.html
,  The Java Web Services Tutorial,
http://java.sun.com/webservices/docs/1.2/tutorial/doc/IntroWS7.html#wp72421
'Overview or JAXM', (Part of an earlier Sun Web Services Tutorial)
http://java.sun.com/webservices/docs/1.1/tutorial/doc/JAXM3.html
The J2EE Tutorial, http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html,
'Developing Java Web Services' , R. Naggappan et. al. , Wiley Press.
'ebXML: An Interview with Sun Expert Ed Bratt, by John Kirkley,
http://developers.sun.com/sw/building/tech_articles/ebxml.interview.html, 'Applied
Java API for XML Messaging', java.sun.com/dev/evangcentral/totallytech/jaxm.html



JAXM provides "an application programming model for servlet-based b-to-b
applications." JAXM stated  goal  "is to provide a lightweight implementation
to help build business-to-business (b-to-b) applications using JAXM. Typical
b-to-b scenarios generally involve two or more business entities communicating
via the Internet using a common protocol, such as HTTP."

JAXM is intimately tied to SAAJ. It describes two sorts of communication
that can be accomplished, synchronous, request-response messaging which
is handled by SAAJ and asynchronous, one way communication which is
specifically part of the JAXM API. We might think of JAXM is an extension
of SAAJ. Sun's JAXM is implemented using servlets. (Other components
may also have been used to serve supply the requirements of the API, on,
i.e. message-driven Enterprise Java Beans.)

The JAXM Messaging Provider

A 'remote provider', a.k.a, 'a messaging provider', may be thought of as
a messaging server. From a SOAP perspecitve the messaging provider
is acting as a SOAP intermediary. The following quote from the release
documentation is key feature supplied by the JAXM messaging framework.

"The messaging provider takes a message sent by an application and holds
on to it until the message has been successfully delivered."

The messaging provider will contiuously attempt to deliver any messages
that the client application has sent and to receive any incoming messages
that have been addressed to the client. The event that triggers a message
provider to send stored messages, will typically be the establishment of
a connection to the remote provider. The JAXM release notes state that
"All messages sent through a remote provider are logged for perusal later."

// something like a Internet provider will pass on messages once a mail
// client has established a connection. If the connection is active the
// message will be forwarded as received


Review of a SAAJ Synchronous Message Exchange 

To summarize in diagrams, recall the our earlier discussions and examples
of SAAJ synchronous request / response model. In brief, a SOAP message
is created, or passed into the program, a URL object representing an endpoint
is created and a  message is sent via a SOAP connection supplied by a
SOAPConnection factory.

The recipient extracted data from the incoming SOAP message, processed
it in some way and created a new SOAP response message which was returned
as the response part of the original HTTP call. This was accomplished by
overriding the JAXM servlet's onMessage( ) method.

SAAJ Synchronous Messaging Model

Client       >-- sends SOAP request --->       Receiver
Client (waits)   < -- response returned ----<  Receiver


The JAXM Asynchronous Model

The JAXM asynchronous model adds an intermediary stage allowing
asynchrous, one-way messaging to occur. Enhancements like, message
acknowledgements, reliable message delivery and  'away from home' access
are also possible using the JAXM asynchronous messaging model.

JAXM  Asynchronous  Messaging Model

Sender                               Receiver  
  |                                     |
Provider                             Provider
  |_______ <SOAP / HTTP Connection> ____|




JAXM Profiles


JAXM incorporates the idea of profiles. Profiles enable the JAXM system
to be adapted to act as a carrier for different messaging models. A JAXM
provider is only requied to implement SOAP 1.1 and SOAP with Attachments.
It may however support other messaging protocols. Other messaging
protocols are referred to as 'profiles'. Profiles define additional levels of
service that are not found in the SOAP specifications. The Sun Web
Services Tutorial supplies the following quotation which serves to summarize
the relationship between a messaging provider and a profile, in this case,
the ebXML profile. .

"A messaging provider that is implemented to include ebXML capabilities on
top of SOAP capabilities is said to support an ebXML profile."
                                                                              -"Overview of JAXM"

// http://java.sun.com/webservices/docs/1.1/tutorial/doc/JAXM3.html

These models are defined as extensions of the SOAP messaging framework.
In practice, the JAXM provider will use a URL that references a schema for
that represents the alternate messaging system. For example, JAXM supplies
built in support for ebXML. It's schema can be found at the following URL.

http://www.ebxml.org/project_teams/transport/messageHeader.xsd

// the Sun white paper ''Applied Java API for XML Messaging' states
// that the JAXM Reference
implementation "supports only mandatory
// pieces of ebXML MS specification and is minimalistic in nature."

JAXM also support the SOAP-RP profile which is a Sun API for general
SOAP message querying. A message can be modeled on one of
these profiles enabling it to communicate successfully under the control
of the ebXML schema.

// recent Sun white paper mentions a profile for XMLP (XML Protocol)


The Messaging Provider Acts as a Server

A messaging provider is continuously active. The provider stays in the wait
state ready to receive any messages intended for it's client. It also will store
and forward any messages it client sends to it. In addition to resending
unsuccessful messages, the provider generates error messages as needed
and maintains a log to record messages and relevant error messages. A
JAXM application that uses a Provider can act in both roles, as client and
server, sender or receiver.

 Following is a possible set of activities that describe how a messaging
provider works.

<>// receiving

1) - the provider waits, to receive incoming messages for it's client.
2) - it stores incoming messages
3) - when client reconnects, the provider forwards messages to client.

// sending

1) - a client connects to it's provider, sends a message, and closes it's connection.
2) - the provider stores the message, then sends it.
3) - the message is resent, until successfully delivered or until resend limit is reached.



JAXM Administration Tool


Following is the quoted contents of the JAXM Provider Admin Tool.

"The JAXM provider administration tool allows users to make changes to the
provider configuration. It is expected that the main users will be Systems
Administrators, but anyone who needs to change the configuration for the
provider can use it.

Some typical ways to change the provider properties are:


Click on "Profiles" in the navigation bar to view the default properties common to
all profiles. Click on one of the profiles to view the supported protocols. Choose a
protocol to edit properties for that profile and protocol combination."


The JAXM API


Without SAAJ Bundled in the JAXM API becomes quite compact. It is
in fact compact enough, we can list the all the main classes and interfaces.
JavaDocs list interfaces in italics, which has been accentuated in a shade
of olive green below. The listener interfaces are implemented by the JAXM
servlet to provide a service that returns a message or doesn't. The other
interfaces we can practically think of as classes, as we will always be
working with class objects that implement these interfaces,
(i.e. ProviderConnection and ProviderMetaData).

All JAXM Classes & Interfaces

Service Target Classes

Listeners

API Specific Servlet Class for JAXM Server

JAXM Connection Classes

JAXM Provider MetaData Class

API Specific Exception


Following is a brief description of each of these JAXM types.

Endpoint

The Endpoint represents the location where a JAXM service can be found.
It is a
mapping of a logical name to a physical location, such as a URL.
The Endpoint class has the following constructor.

Endpoint Constructor
An endpoint may be supplied in a profile so that it isn't neccessary to specify
it explicitly.

URLEndpoint


URLEndpoint is a specialized form of the Endpoint. The URLEndpoint is used
in SAAJ style request-response communications.


Example   URLEndpoint destination = new
                               URLEndpoint("http://localhost:8080/X/LogService");


OneWayListener & ReqRespListener

These Listeners are simple interfaces that each define an onMessage( )
method. The one way version of onMessage( ) returns 'void' while the
request response version returns a SOAPMessage object. The latter
was the form we encountered in our SAAJ example. Following are the
two forms of the method that are overridden inside the JAXM servlet,
one with a return value and one that returns void.

// JAXM docs use fully-qualified name, javax.xml.soap.SOAPMessage

OneWayListener * ResRespListener onMessage( ) Method Variations
// form of the method specified by the OneWayListener interface
// form of the method specified by the ReqRespListener interface

JAXMServlet

The JAXMServlet extends HTTPServlet and as such is designed to
utilize the HTTP transport protocol. Any of it's parent methods might
be overridden. Often, for instance init( ) could be used to handle one
time instantiations. The  JAXM extension is focused on having the
servlet implement one of the two JAXM interfaces and to override
it's onMessage( ) method. It is in onMessage(  ) that message
processing takes place.

 
Descendancy of JAXMServlet  // from JAXM docs

   +--javax.servlet.GenericServlet
|
+--javax.servlet.http.HttpServlet
|
+--javax.xml.messaging.JAXMServlet
A typical servlet implementation would start with the following signature.


Example of a Typical JAXM Servlet Class Signature

public class LogService extends JAXMServlet implements ReqRespListener


ProviderConnectionFactory & ProviderConnection

The Provider factory and connection classes provides the common pattern
we may have seen in all the Java XML APIs we have looked at so far. In
this patten, an instance of the factory is obtained which returns a default
version of the class object that the factory produces, in this case, a
ProviderConnection object.

Example
 ProviderConnectionFactory pcf = ProviderConnectionFactory.newInstance( );
ProviderConnection con = pcf.createConnection( );


Retrieving a ProviderConnectionFactory using JNDI


In an implementation specific form, a ProviderConnectionFactory can be registered
with a naming service based on JNDI or Java Naming and Directory Interface. The
servlet or Enterprise JavaBean container in this case, manages the factory as a
container component. The factory object will have been associated with an identifier
which can then be used to get a handle to the factory. Then an application can
'lookup' the factory object via it's given name. In the following example, code
is shown which serves to reference the factory object.


Example Showing Locating a Factory object using a JNDI Lookup // example from JAXM docs

Context ctx = new InitialContext( );
ProviderConnectionFactory pcf = (ProviderConnectionFactory)ctx.lookup(
"ProviderXYZ");
ProviderConnection con = pcf.createConnection( );


The following quote from the JAXM API documentation gives an insight into how
the messaging provider acts as a SOAP intermediary. A list of Endpoints is created
at deployment when the messaging provider is configured.

"The messaging provider maintains a list of Endpoint objects, which is established
at deployment time as part of configuring the messaging provider. When a client
uses a messaging provider to send messages, it can send messages only to
those parties represented by Endpoint objects in its messaging provider's list.
This is true because the messaging provider maps the URI for each Endpoint
object to a URL".



ProviderMetaData

ProviderMetaData is a informational class that can be used to learn about a provider
once a connection to that provider has been made. The JAXM documentation supplies
the following example showing a ProviderMetaData object being returned and then
version information being obtained.


ProviderMetaData Example // from JAXM documentation
ProviderMetaData pmd = con.getMetaData( );
String name = pmd.getName( );
int majorVersion = pmd.getMajorVersion( );
int minorVersion = pmd.getMinorVersion( );
 

JAXMException


The following Tree Shows that the JAXMException is a descendent of
SOAPException, demonstrating that JAXM works over top of a SOAP
transport architecture. In the context of Java, it will behave the same
as any other Exception class.


Descendancy of JAXMException

   +--java.lang.Exception
|
+--javax.xml.soap.SOAPException
|
+--javax.xml.messaging.JAXMException



Download & Installation


The  JAXM Download

The JAXM download can be found at the following web site.


Installation

1) Unpack the download file and copy the 'dom4j.jar', the  'jaxm-api.jar'
and the 'jaxm-runtime.jar' into the common/lib of Jakarta /Tomcat.

2) Copy the 'jaxm-provider.war', (found under the jaxm distributions
 'jaxm' directory) into  the <Tomcat_Home>/webapps directory.

3) Copy the jaxm-provideradmin.war tools ( found under the distribution's
'tools' directory) tools into  the <Tomcat_Home>/webapps directory.

4) Copy all the sample wars (found under samples) into  the
<Tomcat_Home>/webapps directory.

5) Start ( or shutdown and startup ) Tomcat using the 'startup.sh' or 'startup'
depending if you are running Unix / Linix or a  'Windows system.

6) To clean up you should probably remove all the war files which
now have been expanded into JAXM web applications in Tomcat.

Example  rm *war   // Linux/Unix
              del *war    // Windows

7) To Test, open the browser and go to
http://localhost:8080/jaxm-provideradmin/

If you are prompted for a password everything is well. You can go
to the 'conf' directory and open 'tomcat-users.xml'.
Use the username
and password that has role "provider" from tomcat-users.xml. ( You
can also edit this file to supply your own authentication information
for various Tomcat applications.)

// my file didn't have the 'provider' role so I entered this role in the
// comma-separated list for 'admin', stopped and restarted 'Tomcat'



Example of Tomcat's User Password File   // tomcat-users.xml

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
  <user username="admin" password="secret" roles="manager,admin"/>
</tomcat-users>




Programming with JAXM



JAXM Packages

From a programming perspective, in addition to the SAAJ package
the JAXM API adding a messaging package. Following are the two
packages.


Auxillary to the key packages, are the util package for the Iterator
that is used to extract element information. As well on the server
side the servlet packages will also need to be imported. The following
summarizes the imports that will minimally be made by a JAXM
servlet.


Example Showing Typical Import of Auxillary Packages

import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.messaging.*;
import javax.xml.soap.*;
import java.util.Iterator;



JAXM Request Response Messaging


Though this describes one form of JAXM messaging, we know
from our discussion last week that this is basic SAAJ messaging
using a JAXM server in Request Response mode  to supply the
service. The key element here is there is no intermediary 'provider'
inserted between the client and the server.

In supplying this first example we also supply a solution for the
optional assignment in the last lesson. The following is a simple
version of SAAJ client and server that do synchronous messaging.
The client sends in some sort of unique identification to say they
are logged in and the Server notes the log in time and presumably
stores the information.

Recall we might have passed in a message as a document. In this
example  the message is created 'piece-by-piece'. An effort was
made to make the code as short as possible. If the message is
going to be build inside the client, the code will not be much more
brief than this.
 

A JAXM Synchronous Client 'Logging In'

import javax.xml.messaging.*;
import javax.xml.soap.*;
import java.util.Iterator;

public class LogClient{
    public static void main(String[] args){
     if (args.length!=3){
     System.out.println
     ("Please enter your first and last name and your 'ID number' at the command line");
     System.exit(0);
     }
 try{
    // Create a new, empty message.
    MessageFactory msgFactory = MessageFactory.newInstance( );
    SOAPMessage message = msgFactory.createMessage( );

    // get the SOAPPart
    SOAPPart req_SOAPPart = message.getSOAPPart();
    // get the Envelope and Body
    SOAPEnvelope req_Env = req_SOAPPart.getEnvelope();
    SOAPBody req_body = req_Env.getBody();

    // Create the <abc:SimpleText> body elements.
    Name logIn = req_Env.createName("LogIn", "log",
        "http://simple.ca/log");
    SOAPBodyElement req_BodyElement =
        req_body.addBodyElement(logIn);
    // mod -> adding text to BodyElement
    req_BodyElement.addTextNode( args[0] + " "+ args[1] + " : #" + args[2] + " : ");
    // Remove the SOAP header.
    req_Env.getHeader( ).detachNode( );

    // ****************Connection **********************

    // Get a SOAP connection from the connection factory.
    SOAPConnectionFactory connFactory =
        SOAPConnectionFactory.newInstance( );
    SOAPConnection conn = connFactory.createConnection( );

    // Define the message destination.
    URLEndpoint destination = new
        URLEndpoint("http://localhost:8080/X/LogService");

    // Send the message and wait for the response.
    SOAPMessage response = conn.call( message, destination );

    // Close the connection.
    conn.close( );

    // **************** Processing Response ***************


    SOAPPart res_SOAPPart = response.getSOAPPart();
    SOAPEnvelope res_Env = res_SOAPPart.getEnvelope();
    SOAPBody res_Body = res_Env.getBody( );
   
    // process if the response is a Fault message

    if( res_Body.hasFault( ) ) {
        SOAPFault fault = res_Body.getFault( );
    System.out.println("Fault Code: " + fault.getFaultCode( ) +
                "Fault Explanation: " +  fault.getFaultString( ));
    return;
    }

    Iterator responsesIT =
        res_Body.getChildElements();
        SOAPBodyElement ack =
        (SOAPBodyElement)responsesIT.next();
    System.out.println(ack.getValue());
       }
        catch (SOAPException se){
          System.out.println("SOAPException: " + se );
          }
        catch (Exception e)
        {
            System.out.println(e);
        e.printStackTrace();
        }
    }
}

Following is the Server that get the day and time and acknowledges
the log in.

A JAXM Synchronous Server Responds With a Date and Time Report


import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.messaging.*;
import javax.xml.soap.*;
import java.util.Iterator;

public class LogService extends JAXMServlet
    implements ReqRespListener{
    public SOAPMessage onMessage( SOAPMessage message ){
        try{

//~~~~~~~~~~~~~ Preparing the response message  ~~~~~~~~~~~~~~

    // Get a message factory and create the response message.
    MessageFactory msgFactory = MessageFactory.newInstance( );
    SOAPMessage response = msgFactory.createMessage( );

               // setting up response SOAP message

    SOAPPart res_SOAPPart = response.getSOAPPart();
    SOAPEnvelope res_Env = res_SOAPPart.getEnvelope();
    SOAPBody res_Body = res_Env.getBody();

    SOAPFactory factory= SOAPFactory.newInstance();
    Name responseName = factory.createName("LoggedIn","log","http://simple.ca/log");
    SOAPBodyElement bodyElement = res_Body.addBodyElement(responseName);

//~~~~~~~~~ Getting data from incoming SOAP message ~~~~~~~~

    SOAPPart req_SOAPPart = message.getSOAPPart();
    SOAPEnvelope req_Env = req_SOAPPart.getEnvelope();
    SOAPBody req_Body = req_Env.getBody();

// Can create a name and restrict iteration of children to named nodes
// we know there is one so we omit the while loop

 Iterator bodyChildIT = req_Body.getChildElements();
 SOAPBodyElement message_bodyElement = (SOAPBodyElement)bodyChildIT.next();
 String text = message_bodyElement.getValue();

// ~~~~~~~~~~~~~~~~~ handling faults  ~~~~~~~~~~~~~~~~~~~

         if (req_Body.hasFault()){
                SOAPFault fault = res_Body.addFault();
                fault.setFaultCode("SOAP Fault");
                fault.setFaultString("Request Body had a Fault");
            }
   
// ~~~~~~~~~~~~~~~~~loading response ~~~~~~~~~~~~~~~~~~~~

        else {  java.util.Calendar cal=java.util.Calendar.getInstance();
                bodyElement.addTextNode(
                 "\n\n___ - Agent: " + text + " Logged In: - ___\n\n"  +
                    " Year: "    + cal.get(cal.YEAR)         + "\n " +
                     "Month: "   + cal.get(cal.MONTH)        + "\n " +
             "Day: "     + cal.get(cal.DAY_OF_MONTH) + "\n " +
             "Hour: "    + cal.get(cal.HOUR)         + "\n " +
                 "Minutes: " + cal.get(cal.MINUTE)       + "\n " +
             "Second: "  + cal.get(cal.SECOND)       + "\n " +
             "AM/PM: " +  ((cal.get(cal.AM_PM)==0)?"AM":"PM")
            );

    // Remove the SOAP header.
    res_Env.getHeader( ).detachNode( );
        }
     // Return and send the response message.
        return response;
    }

    catch (SOAPException se){
    System.err.println("SOAPException: " + se.getMessage());
        return null;
        }
    }
}


JAXM Programming With Message Providers


Now that we have discussed message providers and profiles we can add the
functionality supplied by the provider to our program. The following diagram,
reiterates what we will now example programmatically.


JAXM Messaging Using a Message Provider

 Sender ----> Message Provider   ---  request --->
 Message Provider ---> Receiver
 Sender <---- Message Provider  <---response ---  Message Provider <--- Receiver


The following JAXM examples are from the text, 'Developing Java Web Services".
The first thing to notice that the applications representing the providers, which will
need to run continuously are rendered as servlets.

Provider Configuration

There are a few configuration steps that have to be taken. First the Provider
needs to have configuration information regarding it's client.



'Developing Java Web Services', R. Naggapan, Wiley Press Client.xml Example


<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE ClientConfig
    PUBLIC "-//Sun Microsystems, Inc.//DTD JAXM Client//EN"
    "http://java.sun.com/xml/dtds/jaxm_client_1_0.dtd">
<ClientConfig>
    <Endpoint>
      http://www.wiley.com/jaxmebxml/producer
    </Endpoint>
    <CallbackURL>
       http://localhost:8080/jaxm-jaxmebxml/ebxmlconsumer
    </CallbackURL>
    <Provider>
      <URI>http://java.sun.com/xml/jaxm/provider</URI>
      <URL>http://localhost:8081/jaxm-provider/sender</URL>
    </Provider>
</ClientConfig>


The Provider can be configured using the JAXM provider administration tool or by
providing a provider.xml file. // see 'Developing Java Web Services' page 429, Listing 9.4


Producer & Consumer Code with Message Providers

Following is a Producer Consumer Sample supplied in Developing Java Web
Services. The authors do a good job commenting the code so we can tour the
code following their comments (Wiley author comments are in green, additional
comments are in red).

You'll notice that the authors utilize the HTTP servlet methods such as init( )
to do initialization. They also override doGet( ) and do more build work there.
This servlet is hard-coded to supply a message via the provider. Really it is
just a deluxe client that has extra provider features.


'Developing Java Web Services', R. Naggapan, Wiley Press Producer Code Sample


package jws.ch9.jaxmebxml.producer;

import java.net.*;
import java.io.*;
import java.util.*;

import javax.servlet.http.*;
import javax.servlet.*;

import javax.xml.messaging.*;
import javax.xml.soap.*;

import javax.activation.*;

// Import ebXML profile implementation
import com.sun.xml.messaging.jaxm.ebxml.*;

/**
 * ebXMLProducerServlet.java
 * Uses a provider based connection to send messages
 * Runs as a servlet in a container based environment
 */


public class ebXMLProducerServlet extends HttpServlet {
  
   
    private String MessageFrom ="http://www.wiley.com/jaxmebxml/producer";
    private String MessageTo = "http://www.wiley.com/jaxmebxml/consumer";
  
    private String attachmentURL = "http://www.wiley.com/cda/product/0,,0471236403,00.html";

    private ProviderConnectionFactory pcf;
    private ProviderConnection pc;
    private MessageFactory mf = null;
       
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init( servletConfig );

        try {
   
         // Creates an instance of ProviderConnectionFactory and
         // establishes Provider connection

         pcf = ProviderConnectionFactory.newInstance();
        pc = pcf.createConnection();
        } catch(Exception e) {
            e.printStackTrace();
        }   
      }
   
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException     {
   
        PrintWriter out = resp.getWriter();
     resp.setContentType("text/html");

       try {
        
        if (mf == null) {
      
          // Get Provider supported messaging profiles
             ProviderMetaData metaData = pc.getMetaData();
            String[] supportedProfiles = metaData.getSupportedProfiles( );
            String profile = null;

            for(int i=0; i < supportedProfiles.length; i++) {
     
          // Find out the ebXML profile by matching ebXML
                if(supportedProfiles[i].equals("ebxml")) {   
                  profile = supportedProfiles[i];
            break;
            }
            }
        
         // Create a Message factory instance using the profile
             mf = pc.createMessageFactory(profile);
        }

            // Create an ebXML message from the message factory.
            EbXMLMessageImpl ebxmlMsg = (EbXMLMessageImpl)mf.createMessage();

         // Set the Message sender and receiver
            ebxmlMsg.setSender(new Party(MessageFrom));
            ebxmlMsg.setReceiver(new Party(MessageTo));
           // two characteristic elements of an ebXML message From & To
      

             // Get the SOAP Part from the message.
              SOAPPart soapPart = ebxmlMsg.getSOAPPart( );

              // Get the SOAP Envelope
              SOAPEnvelope soapEnvelope = soapPart.getEnvelope( );

              // Create the SOAPBody
               SOAPBody soapBody = soapEnvelope.getBody( );


              // Create a Name object and add to SOAPBodyElement
                 Name bodyName =soapEnvelope.createName
                 ("SubmitPurchaseOrder","wiley","http://jws.wiley.com/jws");                                    
                 SOAPBodyElement sbe =  soapBody.addBodyElement(bodyName);

               // Create a Name object and add body child elements
                  Name elemName = soapEnvelope.createName("BookName");                                    
                 SOAPElement se =  soapBody.addChildElement(elemName);   
                 se.addTextNode("Developing Java Web services");
          
            // Set Attachment URL
            URL url = new URL(attachmentURL);

            // Add Attachment URL as an attachment
            AttachmentPart ap =
                ebxmlMsg.createAttachmentPart(new DataHandler(url));
           
            ap.setContentType("text/html");
           
            // Add the attachment part to the message.
            ebxmlMsg.addAttachmentPart(ap);
           
            // Print the message delivery status of Message
            out.println("<html><head><title>");
            out.println("ebXML Producer Servlet - Status </title></head>");
            out.println("<H1> ebXML Producer Servlet - Status </H1></HR>");      
            out.println("<H3>Message sent to : " + ebxmlMsg.getTo() + "</H3><HR>");
   
           // Write sent message to a file
            out.println("<H3>Sent Message saved to file in \"e:\\jaxm\\messages\\ebXMLsent.msg\"</H3>");
            FileOutputStream sentFile = new FileOutputStream("e:\\jaxm\\messages\\ebXMLsent.msg");
            ebxmlMsg.writeTo(sentFile);
            sentFile.close();
            // characteristic store and send
          
            // Send the message
          pc.send(ebxmlMsg);

            out.println("<H3>Message delivered to the provider</H3><HR>"); 

            out.println("<H3>To ensure message delivery at the final destination</H3>"); 
            out.println("<H3>Refer to file \"ebXMLReceived.msg\"</H3>");
            out.println("</html>");
            out.close();

           // Close the provider connection
           pc.close();

        } catch(Throwable e) {
        e.printStackTrace();
        }
    }
}



The consumer implements OnewayListener and is a real JAXM servlet.
The servlet implements the listener's onMessage( ) method.


'Developing Java Web Services', R. Naggapan, Wiley Press Consumer Code Sample


package jws.ch9.jaxmebxml.consumer;

import javax.xml.messaging.*;
import javax.xml.soap.*;
import javax.servlet.*;
import javax.servlet.http.*;

import javax.xml.transform.*;
import java.io.*;
import java.util.*;

// import ebXML profile implementation (JAXM 1.1)
import com.sun.xml.messaging.jaxm.ebxml.*;

/**
 * ebXMLConsumerServlet.java
 * Uses provider based connection to receive messages
 * Runs as a servlet in a container based environment
 */

public class ebXMLConsumerServlet extends JAXMServlet implements OnewayListener {
   
    private ProviderConnectionFactory pcf;
    private ProviderConnection pc;
 
    public void init(ServletConfig sc) throws ServletException {
        super.init(sc);
   
    try {
     
         // Creates an intance of ProviderConnectionFactory and
         // ProviderConnection
 
          pcf = ProviderConnectionFactory.newInstance();
         pc = pcf.createConnection();
   
          // Sets the Message factory to ebXML profile implementation
          setMessageFactory(new EbXMLMessageFactoryImpl());
   
     } catch (Exception ex) {
        ex.printStackTrace();
        throw new ServletException(
            "Initialization failed : " + ex.getMessage());
    }
    }
   // Upon receiving messages, calls the onMessage method
   // processes the Incoming message

 public void onMessage(SOAPMessage msg) {
   
        try {
            System.out.println("Receiving the incoming ebXML message: ");
      
            // Saves the incoming message
           msg.saveChanges();

            // Writes to a file in a desired location
            FileOutputStream receivedFile = new FileOutputStream("e:\\jaxm\\messages\\ebXMLreceived.msg");
            msg.writeTo(receivedFile);
            receivedFile.close();
           // also does the provider's characteristic persist to storage

        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}


Exercise


Visit the ebXML.org site, download the pdf files for ebXML Technical
Architecture, Messaging Service and Business Process and create
a 1000 word synopsis of their contents . . .

// just kidding! No exercise! Good Luck on the Final!