EJB 3.0 and WebServices

SHARE & COMMENT :

This article discusses how an enterprise bean can act as a Web-Service component. Since Web-Services itself is a vast technology, the first part of the article discusses more about Web-Services. Specifically, the first part of the article discusses what Web-Services are, its unique features among other related technologies, its architecture, and the various base components upon which Web- Services are built. The second part of the article describes the JSR-181 which is the “Web-Services Meta-data for the Java Platform” and how enterprise beans can make use of the API’s available under this JSR to expose themselves as Web-Services components.

also read:

Web Services-Introduction

Normally a Service represents any kind of feature or some piece of functionality that a specific kind of client can be benefited from. Say for a printer service, the clients are either the applications or the programs using the printers or users. Consumers of an ATM service are Bank Customers, like-wise the list of real-world services goes on.

Like these kinds of service, a Web-Service is a kind of remote service that is available in the web and it can be accessed through some standard protocols. A Web-Service can be imagined as a program that is running in a remote machine, usually guarded by a server, so that it can be made accessible by remote clients. How Web-Services are very different from the existing technologies is that, Web-Services have some unique features that are very uncommon to other existing technologies. The clients for these Web-Services can be any one, it can be a user or HTML browser, or even another Web-Service.

Features of Web Services

Following are the unique features of a Web-Service based application.

  • Language Independent
  • Operating System Independent

Language Independent

Let us assume that a Web-Service is running in a remote machine. Suppose an application (can be a Web-Service also) want to gain the functionality of the Web-Service by accessing it. It is not that both the Web-Service and the client application must be built in the same language or technology. They can be different. From this, we can infer that a Web-Service can be built in Java, running in some remote machine and the client of the Web-Service can be a legacy C++ application or a DotNET application.

Communication between Web-Service and heterogeneous clients

From the above diagram, we can see that 3 different applications (built on 3 different technologies) are accessing the same Web-Service.

Operating System Independent

Web-Services are independent of operating systems. This implies that the Web-Service and its consumer can be running in different operating systems. It means that an application running in Unix operating system can access a Web-Service that is running in Windows OS. This is possible, because of the fact that, Web-Services have their specifications defined by W3C and vendors who are providing implementations for the various Web-Services standards are bound to follow the specifications.

[W3C, which stands for World Wide Web Consortium, is a group of companies for proposing and defining some standards for World Wide Web (W3). A whole bunch of Internet standards have been given by W3C till now. Major standards include HTML, XHTML, XML, SOAP, and WSDL…]

Comparison with Other Technologies

If we have a broader look over Web-Services, it is nothing but a distributed computing enabling integration between applications. So many distributing computing standards are there till date and each of them have their own set of limitations. Some of the popular distributing computing technologies include COM-DCOM from Microsoft, Java’s RMI and EJB and Object Managements’ Group CORBA. Each of the above-mentioned technologies seriously suffered from issues like portability, platform-dependency, etc.,

Considering the effort taken by Microsoft to give a common solution to Distributed computing is that both COM (Component Object Model) and DCOM (Distributed Component Object Model) technologies allowed Component based software model development and the components can only be written in a language like VB, VC++ or any Microsoft’s compliant language. Therefore, components written in VB and VC++ can communicate with each other and this doesn’t seem to promote language independency. Another issue is that these COM and DCOM technologies are available only in Operating systems like Windows 98, XP and 2000.

Sun’s Remote Method Invocation, through the support of Java Remote Method Protocol (JRMP) , though is operating system independent (as Java code can be written only once and can be run anywhere as long as a JVM is installed in the target operating system), lacked the same issue of language independency. Both RMI enabled servers and clients should only be written in Java. Outside languages are prohibited to take the advantage of this distributed computing. Though, EJB has support to integrate well with other technologies like DotNet, it hasn’t become very popular, as providing integration of a J2EE Component with other technologies, for sure, will lose the efficiency of portability of the applications in other platforms.

In comparison with the other two technologies, CORBA almost eliminated all the serious issues by providing a language independent and a platform independent framework. It means that in a distributed application, a C++ Server can talk to a Java Client and vice versa. Though this looks good from the outside view, there are other issues like maintaining a heavy middle-ware between the client and the server called Object Adapter and Object Broker, which does the job of locating and loading servers, creating server objects on behalf of clients etc., which made it to prevent from being a successful technology.

Web Services Architecture

A Web Service is not a single technology but it is a combination of several other technologies like

  • SOAP
  • WSDL
  • UDDI

Following sections cover these technologies in greater depth.

SOAP

For establishing communication between heterogeneous systems for exchange of data, we have to adhere to some set of standards in the form of protocols. Distributed computing technologies likeDCOM, CORBA, and RMIetc. have their own proprietary protocols. For example, CORBA usesIIOP (Internet Inter-ORB Protocol) as the standard protocol for communication, DCOMuses ORPC(Object Remote Procedure Call) and Java’s RMIused JRMP(Java Remote Method Protocol). Similarly,Web-Services uses SOAP(Simple Object Access Protocol) as the standard protocol for transferring data between applications. SOAP is an XML based protocolfor packing messages in XML format. Since SOAP is using XML to transfer data/messages between applications, it provides a lighter mechanism and that’s the reason why most of the Web-Services applications use SOAP over HTTPas the standard transport protocol for exchanging messages over the Internet, although Web-Services can easily mingle with any type of compliant protocols.

SOAP Specification

SOAP which is the standard protocol for Web-Services, is actually a standard given by W3C (World Wide-Web Consortium) Group.  The following section discusses the structure of  SOAP messages in greater detail.

The SOAP message

Communication between two heterogeneous systems using Web-Services can be achieved with the help of SOAP protocol by sending and receiving SOAP messages. A client construct a SOAP message, which is an XML based message with appropriate XML schema (http://schemas.xmlsoap.org/soap/envelope/) and sending the message as a request message to the processing application. The processing application (which is usually a Web-Service) unpacks the message, performs the requested operation and returns the result back to the calling application in the form of SOAP response message.

Structure of a SOAP message

The SOAP message consists of the following parts namely, the Envelope, Headerand the Body. Following diagram shows how a SOAP message looks like,

Envelope

From the above picture, one can infer that the Envelopeforms the outer-most structure in a SOAP message and it acts as a container for both the Headerand the BodyEntries. The Envelope therefore forms a mandatory part in the SOAP message. Envelope doesn’t contain any of the data to be transmitted to the receiving application, but still it may contain the necessary meta-data of the sending and the receiving applications.

Following is how the envelope looks like in XML format,


<Soap:Envelope

xmlns:Soap="<a href="http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/">http://schemas.xmlsoap.org/soap/envelope/</a>">

….

</ Soap:Envelope>

As we can see, the above Soap envelope declaration references the name-spacefrom ‘http://schemas.xmlsoap.org/soap/envelope’. See more about name-spacesbelow. The name of the envelope element is ‘Envelope’ and the fully-qualified name (element name along with namespace prefix) isSoap:Envelope, where Soap is the namespace prefix.

[XML Namespaces – XML Namespaces are a way to avoid name collisions that may occur in the elements and attributes that are found in a XML document. Consider a situation where we want to represent a television monitor and a computer monitor in a XML file. Following may be one kind of representation for this,


<items>

...

<television>

<monitor inch=’14’/>

</television>

<computer>

<monitor inch = ‘11’/>

</computer>

...

</items>

In the above simple example, we have two monitor elements within television and computer elements both sharing the common name(‘monitor’). It may happen for the processing applications to spend a good deal of time, to find whether the parsed ‘monitor’ element belong to television or computer element by analyzing its root element. Situations may go even worse if both the monitor elements are at the same level.

So, to avoid these kinds of naming collisions within an XML document, XML namespaces were introduced. A namespace represents a collection of names and no two names within the namespace can be the same. Following represents the syntax to define a namespace in a XML document, xmlns:prefixId=’NamespaceIdentifer’.

The above syntax has 3 entities, namely the keyword name ‘xmlns’ (which stands for XML Namespace), the prefix which serves as a short-hand representation for the NamespaceIdentifier. Any kind of string can be given for NameSpaceIdentifer, but the preferred way is to give URL’s as no two URL’s in the world can be unique.

Now these namespace definitions have to be applied to the elements in such a way that the element’s name have to be prefixed with the prefix that we have already declared in the namespace definition.


<tele:television xmlns:tele=’http://www.mytelevisions.com’>

<tele:monitor inch=’14’/>

</tele:television>

The above modified element declared can be interpreted like this, a namespace called “http://www.mytelevisions.com” is created and it is given a prefix ‘tele’, After this all the elements within the television element are made namespace-aware by prefixing them with ‘tele’.

Now, the revised XML document will look similar to this,


<items>

...

<tele:television xmlns:tele=’http://www.mytelevisions.com’>

<tele:monitor inch=’14’/>

</tele:television>

<comp:computer xmlns:tele=’http://www.mycomputers.com’>

<comp:monitor inch = ‘11’/>

</comp:compuer>

...

</items>]

Header

The next optional element in the SOAP Envelope is the headerelement. If present, the element comes immediately after the Envelopeelement. The XML representation for the Headerelement looks like the following,


<Soap:Envelope

xmlns:Soap="<a href="http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/">http://schemas.xmlsoap.org/soap/envelope/</a>">

<Soap:Header>

…

</Soap:Header>

<Soap:Header>

…

</Soap:Header>

</Soap:Envelope>

Any number of header elements can appear after the Envelopeelement. The Headerelement is used to provide some meaningful information to the receiving application. For example, a sender application can include the language and the currency information as part of the header information like this,


<Soap:Envelope

xmlns:Soap="<a href="http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/">http://schemas.xmlsoap.org/soap/envelope/</a>">

...

<Soap:Header>

<language>English</language>

</Soap:Header>

<Soap:Header>

<currency>INR</currency>

</Soap:Header>

...

</Soap:Envelope>

Body

Unlike the optional header element, Bodyelement is mandatory as it includes that actual data to be sent to the receiving application. The bodyelement immediately follows the Envelope element -if there is no Header element, or it comes after the Header element.


< Soap:Envelope

xmlns:Soap="<a href="http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/">http://schemas.xmlsoap.org/soap/envelope/</a>">

<Soap:Header>

<language>English</language>

</Soap:Header>

<Soap:Body xmlns:MyData=”http://mydata.com”>

<MyData:MyPersonalData>

<MyData:Name>MyName</MyData:Name>

<MyData:Age>MyAge</MyData:Age>

</MyData:MyPersonalData>

</Soap:Body>

</Soap:Envelope>

Note that in the above XML, a namespace called “http://mydata.com” is referenced and all the elements within the body like ‘MyPersonalData’, ‘Name’ and ‘Age’ are fully qualified as ‘MyData:MyPersonalData’, ‘MyData:Name’and ‘MyData:Age’ respectively.

SOAP messages with Attachments

In many of the situations SOAP messages alone cannot be sufficient for data transmission between applications as a SOAP message can hold only textual representation of data. Say, an XML message can only hold a Customer Name, an Employee Id, or a Cricket Score. It cannot hold binary information like images, audio files or video files. In such a case, SOAP XML messages cannot always best represent the whole set of real-world data. To get rid-off the lacking functionality with SOAP, came the specification from W3C called “Soap Messages with Attachments”.

One can identify from the name that SOAP messages with Attachments are extensions to SOAP messages in that it can hold not only textual data (in the form of XML) but also other types of messages (like audio files, image files etc.,). Logically, SOAP messages with attachments can two different parts (or sections) namelySOAP Partand the Attachment Part, which is illustrated in the following diagram.

SOAP Implementation

Different vendors have given implementation for the specification of SOAP given by W3C. Popular SOAP implementation (or products) includes, SAAJ(SOAP withAttachments API for Java) from Java, IBM’s SOAP4J(SOAP for Java) and Microsoft’s SOAP Toolkit. The following section presents a sample application for constructing a SOAP message using the SAAJ API.

Sample Application

With the above basics like SOAP messages and attachments in mind, let us write a sample SOAP application in Java usingSAAJ API. SAAJ, which stands for SOAP with Attachments API for Java, can be used to send XML messages along with Attachments between two applications. The entire API needed for sending and receiving SOAP messages are available injavax.xml.soap.

Let us use the API to construct a sample SOAP message. Though the API provides rich features like constructing, sending and receiving SOAP messages, this sample is limited in showing the construction of SOAP messages only. Listing shows the code to construct the SOAP message using the SAAJ API.


SoapMessageConstruction.java:

package test;

import javax.xml.namespace.QName;

import javax.xml.soap.*;

public class SoapMessageConstruction {

public SoapMessageConstruction() {

}

public void construct(){

try{

MessageFactory messageFactory = MessageFactory.newInstance();

SOAPMessage message = messageFactory.createMessage();

// Add header entries here.

SOAPHeader soapHeader = message.getSOAPHeader();

// Application name header.

QName qNameForAppName = new QName("http://myApp.com", "Bank-Name", "app");

SOAPHeaderElement headerForAppName = soapHeader.addHeaderElement(qNameForAppName);

headerForAppName.addTextNode("ICICI Bank");

// Currency header.

QName qNameForCurrency = new QName("http://myApp.com", "Currency", "app");

SOAPHeaderElement headerForCurrency = soapHeader.addHeaderElement(qNameForCurrency);

headerForCurrency.addTextNode("INR");

// The SOAP part of the message.

SOAPPart soapPart = message.getSOAPPart();

SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

SOAPBody soapBody = soapEnvelope.getBody();

QName qNameForAccNo = new QName("http://myBank.com", "Account-No", "bank");

SOAPBodyElement elementForAccNo =

soapBody.addBodyElement(qNameForAccNo);

elementForAccNo.addTextNode("123456789");

QName qNameForTotalAmount = new QName("http://myBank.com", "Total-Amount", "bank");

SOAPBodyElement elementForTotalAmount =

soapBody.addBodyElement(qNameForTotalAmount);

elementForTotalAmount.addTextNode("75000.00");

message.writeTo(System.out);

}catch(Exception exception){

exception.printStackTrace();

}

}

public static void main(String args[]){

SoapMessageConstruction constructor = new SoapMessageConstruction();

constructor.construct();
}

The output for the above sample program is given below,

</pre>
<SOAP-ENV:Envelope

xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

<SOAP-ENV:Header>
<app:Bank-Name xmlns:app="http://myApp.com">

ICICI Bank

</app:Bank-Name>

<app:Currency xmlns:app="http://myApp.com">

INR

</app:Currency>


</SOAP-ENV:Header>


<SOAP-ENV:Body>

<bank:Account-No         xmlns:bank="http://myBank.com">123456789</bank:Account-No>

<bank:Total-Amount xmlns:bank="http://myBank.com">75000.00</bank:Total-Amount>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>
<pre>

Let us see the various pieces of code in detail.

MessageFactory messageFactory = MessageFactory.newInstance();

SOAPMessage message = messageFactory.createMessage();

The initial point of entry to construct a SOAP message is to depend on the MessageFactory class which is a factory class to create SOAP messages. The createMessage() method creates and returns a new instance of the SOAP message. The very good thing is that as soon as a SOAP message is created, the inner elements like envelope, header and body are created by default. Printing the SOAP message object to the console  (by calling message.writeTo(System.out)) will result in an output like this,


<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

</SOAP-ENV:Envelope>

// Add header entries here.

SOAPHeader soapHeader = message.getSOAPHeader();

// Application name header.

QName qNameForAppName =

new QName("http://myApp.com", "Bank-Name", "app");

SOAPHeaderElement headerForAppName =

soapHeader.addHeaderElement(qNameForAppName);

headerForAppName.addTextNode("ICICI Bank");



// Currency header.

QName qNameForCurrency =

new QName("http://myApp.com", "Currency", "app");

SOAPHeaderElement headerForCurrency =

soapHeader.addHeaderElement(qNameForCurrency);

headerForCurrency.addTextNode("INR");

The next section of the code gets the header element of the SOAP message by callingmessage.getSOAPHeader()and adds some header entries to it. It does so by calling theSOAPHeader.addHeaderElement(QName)method (See more about QName below.) which adds an empty element called “Bank-Name”. The Bank-Name element is populated with some text content by calling theSOAPHeaderElement.addTextNode(String)method. The above code will result in populating the message structure like this,


QName – QName which stands for qualified name represents the fully qualified name for an xml element, Consider the following xml,

 

<cricket:player xmlns:cricket = “<a href="http://web.archive.org/web/20080116132744/http://www.cricket.com/">http://www.cricket.com</a>”>

            <name>….</name>

</cricket:player>

 

<football:player xmlns:football = “<a href="http://web.archive.org/web/20080116132744/http://www.football.com/">http://www.football.com</a>”>

            <name>….</name>

</football>

We have two player elements here, However, with the help of XML name-spaces, they are fully qualified as cricket:player and football:player. For the cricket:player, the element name is “player”, the prefix is “cricket” and the reference name-space is “http://www.cricket.com”.

This fully qualified name representation forms the QName for an element, For example, the above xml code is logical equivalent to the following java code,


QName qNameForCricketPlayer = new QName(“<a href="http://web.archive.org/web/20080116132744/http://www.cricket.com/">http://www.cricket.com</a>”, “player”, “cricket”);

QName qNameForFootballPlayer = new QName(“<a href="http://web.archive.org/web/20080116132744/http://www.cricket.com/">http://www. football.com</a>”, “player”, “football”);

The first three arguments in the constructor refers to the name-space URI, the element name and the prefix respectively]


<SOAP-ENV:Envelope

xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

<SOAP-ENV:Header>

<app:Bank-Name xmlns:app="http://myApp.com">

ICICI Bank

</app:Bank-Name>

<app:Currencyxmlns:app="http://myApp.com">

INR

</app:Currency>      



</SOAP-ENV:Header>



</SOAP-ENV:Envelope>


// The SOAP part of the message.

SOAPPart soapPart = message.getSOAPPart();

SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

SOAPBody soapBody = soapEnvelope.getBody();

          

QName qNameForAccNo = new QName("http://myBank.com", "Account-No", "bank");

SOAPBodyElement elementForAccNo =

soapBody.addBodyElement(qNameForAccNo);

elementForAccNo.addTextNode("123456789");           



QName qNameForTotalAmount = new QName("http://myBank.com", "Total-Amount", "bank");

SOAPBodyElement elementForTotalAmount =

soapBody.addBodyElement(qNameForTotalAmount);

elementForTotalAmount.addTextNode("75000.00");           

Similarly, the elements within the body content are added using the above code. Now the resultant SOAP message will look similar to this,


<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

<SOAP-ENV:Header>

<app:Bank-Name xmlns:app="http://myApp.com">

ICICI Bank

</app:Bank-Name>
<app:Currency xmlns:app="http://myApp.com">INR</app:Currency>

</SOAP-ENV:Header>


<SOAP-ENV:Body>

<bank:Account-No xmlns:bank="http://myBank.com">123456789</bank:Account-No>
<bank:Total-Amount xmlns:bank="http://myBank.com">75000.00</bank:Total-Amount>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Trackbacks

  1. […] EJB 3.0 and Web Services […]

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better