Wednesday, December 14, 2011

The Beginners Guide to JAXB

  JAX-pack, now being referred to as JWSDP,is a very important development in J2EE.In the previous editions,(July,August,October-2004)  we had covered the basics of JAXP( Java -API for XML Processing), dealing with  DOM,SAX,JDOM,TrAX etc. Part-1 of this tutorial deals with general theory of JAXB and its importance in binding XML to Java classes.
   JAXB  is a component  part of JAX set of API's.  SUN MICRO SYSTEMS is giving a lot of importance to XML WebServices and within a short span, has released a number of revisions of JWSDP ( Java WebService Development pack). It began with JWSDP1.0 and now is running JWSDP1.5. (Version numbers have become very important in modern software field, because, there is so much development taking place almost every month.
This is true in J2EE/OpenSource & DotNet  too. )
It appears that JAXB is available for downloading,  as a part of JWSDP only, and cannot be downloaded as such. So, we should download JWSDP , to gain access to JAXB for experimentation.We are using JWSDP1.4.
   JWSDP is essentially for XML-WebService work. The constituent parts of this package are  JAX-RPC, JAXM(Messaging)& JAXR(Registry).There is also SAAJ ( SOAP with Attachment)not to be confused with JAAS ( Java security). (Hopefully, we will cover these topics , in coming editions).JAXP takes care of DOM,SAX  & XSLT .
  JAXB allows Java developers to access and process XML data without having to know XML or XML processing. For example, there's no need to create or use a SAX parser or write callback methods. It makes use of a  given schema of an XML document and automatically generates the required Java classes, corresponding to that schema.( DeveloperIQ is now providing a detailed workshop on DTD, a form of Schema).Modern trend focuses on XML representation of Data, for ease of exchange in web-service and otherwise. If we have an xml representation of a database, we can use JAXB to create a tree of Java objects  and work with them in Java idiom..This is known as XML-Databinding. .
  Validation is an important part of any XML document. Unlike  HTML, XML tags are user-defined. This is what gives XML its power and utility. But, at the same time, to make it really useful, each such XML document should have a 'schema'....Something like Data Definition in SQL. It should be carefully noted that 'schema' is a general term. In the earlier days of XML, the only schema that was known and used was DTD (Document-type-definition). Even today, DTD is said to be the most prevalent 'schema' in use and best known, among developers.
  However, DTD was found to have a number of limitations.Microsoft is credited with the proposal for an alternative to DTD in the very early days of XML.It was known as 'XML Schema'.The proposal was submitted to the W3C (World-wide Web Consortium), which is the standards body for XML , HTML and related topics and was later adopted by W3C with some modifications.
  'XML-Schema' is considered to be better than DTD, for a number of reasons. First, unlike a DTD, an XML-Schema is itself an XML document. Secondly, it has provision for greater variety of data-types than are available in DTD.It supports Name-space.
********************************************
 JAXB Mapping of XML Schema Built-in Data Types 
XML Schema Type
Java Data Type
xsd:string
java.lang.String
xsd:integer
java.math.BigInteger
xsd:int
int
xsd.long
long
xsd:short
short
xsd:decimal
java.math.BigDecimal
xsd:float
float
xsd:double
double
xsd:boolean
boolean
xsd:byte
byte
xsd:QName
javax.xml.namespace.QName
xsd:dateTime
java.util.Calendar
xsd:base64Binary
byte[]
xsd:hexBinary
byte[]
xsd:unsignedInt
long
xsd:unsignedShort
int
xsd:unsignedByte
short
xsd:time
java.util.Calendar
xsd:date
java.util.Calendar
xsd:anySimpleType
java.lang.String
********************************************  
However, an XML-Schema is of rather large size compared to the corresponding DTD representation .
   Because of this 'limitation' of XML-Schema, another validation scheme , known as Relax-NG , developed by another standards organization, known as OASIS  ,is also prevalent.This schema is comparatively compact. Be it DTD or XML-Schema or Relax-NG, all these topics are heavy reading and belong properly to the study of XML by itself rather than as applied XML in Java.Though , XML webservice is built entirely on XML and SOAP, it is possible for a developer to build an effective webservice application in ASP.net & AXIS, without going into the details of XML.It may be said to be the main merit of ASP.net,that it hides the details of implementation and allows the Application developer to concentrate on the business-logic on hand.So does, Apache's AXIS.But, at some stage, a good understanding  of the inner working details becomes useful, for trouble-shooting and advanced work.But, the danger of 'missing the forest for the trees' , also is there , if we get into implementation details, too deeply.
    The problem in JAXB, is that it originally dealt with DTD and later switched over to XML-Schema (And many books were written about this earliest version of JAXB and are not suitable now).. SUN  promotes  an alternative to the SOAP standard , known  as Eb-XML , being developed under the auspices of UNESCO & OASIS.This is said to be more attuned to the needs of Vericals ( specific industries ). JAXB attempts to incorporate support for Relax-NG also, as it is from OASIS..
When JAXB work started, it  dealt with  DTD only, because at that time the XML-Schema had not been standardized.Later versions ,are primarily meant to work with XML-schema and DTD support  is  only experimental. Same for Relax-NG,but for an entirely different reason, because work on that is still progressing.  These areas are developing so fast that books and articles become out-dated, very quickly, but they are not withdrawn from the web/market, thus  confusing the readers. Information is getting 'dated', rapidly.With so many acronyms around, it is better  that we try to understand what they mean and their context , before diving in.Hence, the present tutorial attempts to give such an overview.
  (The JWSDP1.4 package has the sub-folders for
JAXP,JAXB,JAXR,JAX-RPC,JSTL,SAAJ,XWS-SECURITY,XMLDSIG-xml digital signature).
------
   The latest release of JWSDP is JWSDP1.5.
( Jan-2005).The following three items can be said to be new or  special improvements  the JWSDP pack.
   a)  Java Streaming XML Parser
   b)  XML Digital Signature
   c)  JAXB(1.04)
--------------------------------------
a)  (SJSXP)(Sun Java Streaming XML Parser ).
------------------------------
The Streaming API for XML (StAX)provides a stream-based API for reading and writing XML documents. The StAX approach is also known as "pull" parsing. This sounds like Microsoft's method of XML processing, in DotNet platform.The DotNet platform has a class known as XmlTextReader which provides a stream API which also is based on 'pull' model.The usual SAX method is known as 'Push' model.The 'pull' model is said to be more efficient in some cases.(Interested readers can refer to page 307-322 of a very valuable book..
'ASP.Net..Tips,Tutorials and Code' by a team of authors led by Scott Mitchell(Techmedia).)
b)The Java-XML- Digital Signature package in the WSDP provides  a standard way for Java developers to access digital signature services. To quote: ***Using the XML Digital Signature APIs found in the WSDP, developers can sign and validate digital content and represent the signatures in an XML format. The signatures provide a standard way to verify that content originated from a known source and was not altered during transmission***.
c) Coming now to JAXB,in the words of Sun Documentation,
***The Java Architecture for XML Binding (JAXB) project  provides a standard API for automating the mapping between XML documents and Java objects. Using JAXB, a developer can compile a schema into Java classes that provide support for marshaling, unmarshaling, accessing, updating, and validating. The main goal of JAXB is to relieve the developer of these tasks so that they can be more productive and be exposed to fewer XML-oriented issues. JAXB 1.0.4 provides support for a subset of XML Schema and experimental support for RelaxNG. RelaxNG is a simplified XML schema system sponsored by the Oasis group. JAXB is currently integrated with JAX-RPC for easily transporting objects across the wire.***.
   There is common agreement in Industry that XML-Schema  is better than DTD.
In a DTD, element content is mostly limited to strings whereas an XML-Schema can set the data type of elements to very specific types such as integers and date. However, with thousands  of DTD based XML documents , being in use today, it is vital that compatibility is maintained. Tools are said  to be available for automating the conversion of DTD into an equivalent Schema.
( readers can see p114 of XML-Unleashed by
Michael Morrison..Techmedia, for details).
   If to create a valid XML document, we begin by creating a DTD.(Document-type-Definition),such DTD creation  is more difficult than creating a well-formed XML document, straight away! If the beginner can first create an XML document and from that generate a DTD automatically, it will be easier job.AlphaWorks of IBM created a Java library, DDbE(Data Descriptors by Example),to make it easier for beginners to create the DTD. The above library fulfils that role.For working properly, DDbE requires XML4j  parser from IBM. ( see p.636 of the above book).Student readers can check up the current status of such automated tools. Though unconventional, this approach, is easier and saves a lot of labour. We get a readymade framework which can then be suitably modified. The recommended method in JAXB is not to begin with DTD but to use an
XML-Schema.
--------------------------------------------
   Let us now try to get familiar with the technical terms in JAXB environment.
   We begin from an XML-Schema , first. An XML schema uses XML syntax to describe the relationships among elements, attributes and entities in an XML document. The purpose of an XML schema is to define a class of XML documents that must adhere to a particular set of structural rules and data constraints. 
There is a  command  in JAXB/bin known as xjc .(Actually, it is a batch file which uses jaxb binding compiler.). We can invoke this batch file from the command line (after setting the required path & classpath, to be defined soon).The command is like :
 >xjc  books.xsd , where books.xsd is the XML-Schema file being used.The command has a few optional arguments, to specify the name of target directory, package name etc. Sometimes, we may prefer to use an existing DTD as reference and in such cases, we can give -dtd  as option and then specify the DTD file).
 When we run this command,it generates a number of Java source files in layered packages.There is a default binding rule and it is generally sufficient. In case, we need more fine-tuned behaviour, we can supply such a binding schema also as an argument.
    These source files are then compiled.
Using these classes, we can convert an XML document which is based on the specified schema into corresponding java objects in a tree, different from the usual DOM tree and more efficient. This process of converting an XML document into Java objects is called Unmarshalling.
In the context of JAXB, a Java application is a client application that uses the JAXB binding framework to unmarshal XML data, validate and modify Java content objects, and marshal Java content back to XML data.
---
To paraphrase from Sun's Documentation,
*** 
The general steps in the JAXB data binding process are:
1.  Generate classes. An XML schema is used as input to the JAXB binding compiler to generate JAXB classes based on that schema.
2.   Compile classes. All of the generated classes, source files, and application code must be compiled.
3.  Unmarshal. XML documents written according to the constraints in the source schema are unmarshalled by the JAXB binding framework.
4.  Generate content tree. The unmarshalling process generates a content tree of data objects instantiated from the generated JAXB classes; this content tree represents the structure and content of the source XML documents.
5.   Validate (optional). The unmarshalling process optionally involves validation of the source XML documents before generating the content tree.
6.   Process  the content. The client application can modify the XML data represented by the Java content tree by means of interfaces generated by the binding compiler.
7.  Marshal. The processed content tree is marshalled out to one or more XML output documents. The content may be validated before marshalling.
---------------------------------------------------------------------------------------------------------------------
The following code-snippet  illustrates the process of unmarshalling.
( we are assuming an xml document named 'library'.)."<package-name>" refers to the package in which the auto-genrated class files due to xjc command are available.
 ------------------------------------------- 
JAXBContext  context =
JAXBContext.newInstance("<package-name>") ;
Unmarshaller   unmarshaller =
   context.createUnmarshaller() ;
Library   library =
  (Library)unmarshaller.unmarshal
  (new   FileInputStream("library.xml")) ;
-------------------------------------------------------
library.xml is an example XML document that conforms to the schema file from which the JAXB-generated Java classes and interfaces are created, and Library is the root object in the XML document. Hereafter, we can use java  idiom to manipulate the objects in the library.
-------------------------------------------
An application can directly create java objects by using the ObjectFactory created by the xjc process.First, we get an instance of ObjectFactory.This factory instance is then used to create a library object. 
We create objects in that library tree, set attributes for such objects& add the objects to the root.Finally, an instance of Marshaller class, is created and used to send the object to xml file.
---------------------------------------
ObjectFactory   factory=
  new ObjectFactory();
Library  library = factory.createLibrary();
Book  book1 = factory.createBook();
book1.setTitle("java today");
book1.setPrice("200Rs");
library.add(book1);
Marshaller   marshaller =   context.createMarshaller();
marshaller.marshal(library, new FileOutputStream("library.xml")) ;
============================================
   Thus, the process of converting a java-object tree to xml is known as Marshalling.
To, recapitulate,
Unmarshalling means creating a java object tree  for an XML document.
Marshalling means  converting a javaobject tree into equivalent XML.
==========================================
With these introductory ideas, we take up a simple example in the next part of this tutorial.
*******************************************

Tuesday, December 13, 2011

The Life Cycle of the Reliable Message Sequence and Failure Recovery Scenarios.

The Life Cycle of the Reliable Message Sequence

The following figure shows a one-way reliable message exchange.
Figure 5-1 Web Service Reliable Message Exchange
Description of Figure 5-1 follows
Description of "Figure 5-1 Web Service Reliable Message Exchange"
A reliable message sequence is used to track the progress of a set of messages that are exchanged reliably between an RM source and RM destination. A sequence can be used to send zero or more messages, and is identified by a string identifier. This identifier is used to reference the sequence when using reliable messaging.
The Web service client application sends a message for reliable delivery which is transmitted by the RM source to the RM destination. The RM destination acknowledges that the reliable message has been received and delivers it to the Web service application. The message may be retransmitted by the RM source until the acknowledgement is received. The RM destination, if configured to buffer requests, may redeliver the request to the Web service if the Web service fails to process the request.
A Web service client sends messages to a target Web service by invoking methods on the client instance (port or Dispatch instance). A port is associated with the port type of the reliable Web service and represents a programmatic interface to that service. The port is created by the <clientgen> child element of the jwsc Ant task. A Dispatch instance is a loosely-typed, general-purpose interface for delivering whole messages from the client to the Web service. For more information about Dispatch clients, see Developing a Web Service Dispatch Client..
WebLogic stores the identifier for the reliable message sequence within this client instance. This causes the reliable message sequence to be connected to a single client instance. All messages that are sent using a given client instance will use the same reliable messaging sequence, regardless of the number of messages that are sent. (Unless you using batching, as described in Grouping Messages into Business Units of Work (Batching).)
Because WebLogic Server retains resources associated with the reliable sequence, it is recommended that you take steps to release these resources in a timely fashion. this can be done by managing the lifecycle of the client instance itself, or by using the weblogic.wsee.reliability2.api.WsrmClient API. Use the WsrmClient API to perform common tasks such as set configuration options, get the sequence id, and terminate a reliable sequence. For more information, see Managing the Life Cycle of a Reliable Message Sequence.

Reliable Messaging Failure Recovery Scenarios

The following sections outline reliable messaging failure recovery for various scenarios.
The first three scenarios assume that buffering is enabled on both the Web service and client. The last scenario describes reliable messaging failure recovery for non-buffered Web services. Buffering is enabled on Web service client by default. To configure buffering on the Web service, see Chapter 7, "Configuring Message Buffering for Web Services."

RM Destination Down Before Request Arrives

Table 5-3 describes the reliable messaging failure recovery scenario when an RM destination is unavailable before a request from the RM source arrives.
It is assumed that Web service buffering is enabled on both the Web service and client. Buffering is enabled on Web service client by default. To configure buffering on the Web service, see Chapter 7, "Configuring Message Buffering for Web Services."
Table 5-3 Reliable Messaging Failure Recovery Scenario—RM Destination Down Before Request Arrives
Transport Type Scenario Description
Asynchronous Transport
  1. Client invokes an asynchronous method.
  2. Reliable messaging runtime accepts the request; client returns to do other work.
  3. Reliable messaging runtime attempts to deliver the request and fails because the RM destination is down.
  4. Reliable messaging runtime waits for the retry interval and tries to send the request again. The request delivery fails again.
  5. RM destination comes up.
  6. Reliable messaging runtime waits for the retry interval and tries to send the request again. The request delivery succeeds.
  7. Acknowledgement is sent to the client which includes the message number of the request. The reliable messaging runtime removes the message from the retry list.
  8. Response arrives and the client processes it.
Note: At any time, the client can check acknowledgement status, access information about a message, and so on, as described in Managing the Life Cycle of a Reliable Message Sequence.
Synchronous Transport
  1. Client invokes a synchronous method.
  2. Reliable messaging runtime accepts the request and blocks the client thread.
  3. Reliable messaging runtime attempts to deliver the request and fails because the RM destination is down.
  4. Reliable messaging runtime waits for the retry interval and tries to send the request again. The request delivery fails again.
  5. RM destination comes up.
  6. Reliable messaging runtime waits for the retry interval and tries to send the request again. The request delivery succeeds.
  7. Response and acknowledgement are sent to the client via the transport back-channel. The acknowledgement includes the message number of the request. The reliable messaging runtime removes the message from the retry list.
  8. Reliable messaging runtime unblocks the client thread and returns the response.
  9. Client receives the response as the return value of the method invocation, and processes the response.
Note: At any time, the client can check acknowledgement status, access information about a message, and so on, as described in Managing the Life Cycle of a Reliable Message Sequence.
Note: To achieve true reliability with synchronous transport, it is recommended that you use MakeConnection. For more information, see Using Asynchronous Web Service Clients From Behind a Firewall (MakeConnection).

RM Source Down After Request is Made

Table 5-4 describes the reliable messaging failure recovery scenario when an RM source goes down after a request is made.
It is assumed that Web service buffering is enabled on both the Web service and client. Buffering is enabled on Web service clients by default. To configure buffering on the Web service, see Chapter 7, "Configuring Message Buffering for Web Services."
Table 5-4 Reliable Messaging Failure Recovery Scenario—RM Source Down After Request is Made
Transport Type Scenario Description
Asynchronous Transport
  1. Client invokes an asynchronous method.
  2. Reliable messaging runtime accepts the request; client returns to do other work.
  3. Client (RM source) goes down.
  4. Client comes up. Client must re-initialize the client instance using the same client ID. The runtime will use this client ID to retrieve the reliable sequence ID that was active for the client. For more information, see Managing the Client ID.
  5. Reliable messaging runtime detects the reliable sequence ID that was in use prior to the client going down and recovers the accepted requests.
    Note: This step is accomplished only after the client re-initializes the client instance that was used to send the request because delivery of the request depends on resources provided by the client instance. It is recommended that clients initialize the client instance in a static block, or use a @PostConstruct annotation or other mechanism to ensure early initialization of the client instance. For more information, see the best practices examples presented in Roadmaps for Developing Web Service Clients.
  6. Reliable messaging runtime sends the request and succeeds.
  7. Acknowledgement is sent to the client which includes the message number of the request. The reliable messaging runtime removes the message from the retry list.
  8. Response arrives and the client processes it.
Note: At any time, the client can check acknowledgement status, access information about a message, and so on, as described in Managing the Life Cycle of a Reliable Message Sequence.
Synchronous Transport
  1. Client invokes a synchronous method.
  2. Reliable messaging runtime accepts the request and blocks the client thread.
  3. Reliable messaging runtime attempts to deliver the request. The request delivery succeeds.
  4. Before response can be sent, the client (RM source) goes down. Client thread is lost as the VM exits, along with the invocation state and calling stack of the client itself.
  5. Client (RM source) comes up. Client must re-initialize the client instance (port or Dispatch) using the same client ID. For more information, see Managing the Client ID
  6. Reliable messaging runtime detects the previous sequence ID for the client, and sees that the last request was made synchronously.
  7. Reliable messaging runtime delivers a permanent failure notification for this request, and fails the entire RM sequence associated with the client instance. Any ReliabilityErrorListener associated with the client instance will be called at this point.
  8. Client is responsible for retrieving the original request (via some client-specific mechanism) and resending it by re-invoking the client instance with the request.
Note: At any time, the client can check acknowledgement status, access information about a message, and so on, as described in Managing the Life Cycle of a Reliable Message Sequence.
Note: To achieve true reliability with synchronous transport, it is recommended that you use MakeConnection. For more information, see Using Asynchronous Web Service Clients From Behind a Firewall (MakeConnection).

RM Destination Down After Request Arrives

Table 5-5 describes the reliable messaging failure recovery scenario when an RM destination is unavailable after a request has been accepted from the RM source.
It is assumed that Web service buffering is enabled on both the Web service and client. Buffering is enabled on Web service client by default. To configure buffering on the Web service, see Chapter 7, "Configuring Message Buffering for Web Services."
Table 5-5 Reliable Messaging Failure Recovery Scenario—RM Destination Down After Request Arrives
Transport Type Scenario Description
Asynchronous Transport
  1. Client invokes an asynchronous method.
  2. Reliable messaging runtime accepts the request; client returns to do other work.
  3. Reliable messaging runtime attempts to deliver the request and succeeds.
  4. The RM destination accepts the request and send an acknowledgement on the back channel.
  5. Reliable messaging runtime sees the acknowledgement and removes the message from the retry list.
  6. RM destination goes down.
  7. Reliable messaging runtime on RM source retries any pending requests during this time.
  8. RM destination comes up.
  9. RM destination recovers the stored request, processes it, and sends the response.
  10. Response arrives and the client processes it.
Note: At any time, the client can check acknowledgement status, access information about a message, and so on, as described in Managing the Life Cycle of a Reliable Message Sequence.
Synchronous Transport
Note: If you attempt to invoke a buffered Web service using synchronous transport, one of following will result:
  • If this is the first request of the sequence, the destination sequence will be set to be non-buffered (as though the Web service configuration was set as non-buffered).
  • If this is not the first request of the sequence (that is, the client sent a request using asynchronous transport previously), then the request is rejected and a fault returned.
The following describes the sequence of this scenario:
  1. Client invokes a synchronous method.
  2. Reliable messaging runtime accepts the request and blocks the client thread.
  3. Reliable messaging runtime attempts to deliver the request. The request delivery succeeds.
  4. RM destination accepts the request and sends an acknowledgement via the transport back channel.
  5. Client (RM source) detects the acknowledgement and removes the request from the retry list.
  6. RM destination goes down.
  7. Client thread remains blocked.
  8. RM Destination comes up, recovers, and processes the request, and sends the response to the client.
  9. Reliable messaging runtime unblocks the client thread and returns the response.
  10. Client receives the response as the return value of the method invocation, and processes the response.
Note: At any time, the client can check acknowledgement status, access information about a message, and so on, as described in Managing the Life Cycle of a Reliable Message Sequence.

Failure Scenarios with Non-buffered Reliable Web Services

A non-buffered Web service operates differently than a buffered Web service in that it does not buffer a request to hardened storage before acknowledging it and attempting to process it. A non-buffered Web service will not attempt to reprocess a request if the service logic fails, whereas a buffered Web service will attempt to reprocess the request. In both cases, buffered or non-buffered, any response generated by the Web service will be buffered before it is sent back to the client.
A non-buffered Web service may be useful in the following cases:
  • Web service operates against non-transactional resources and should not process any request more than once (because rolling back the transaction that dequeued the buffered request cannot roll back the side effects of the non-transactional service).
  • Web service is relatively light weight, and does not take very long to process requests.
  • Web service performance is of paramount importance and risk of losing request or response is acceptable. Non-buffered Web services will not incur the overhead of buffering the request to a store, and thus can deliver better throughput than a buffered Web service. The performance gain is dependent on how much time and resources are required to buffer the requests (for example, very large request messages may take significant time and resources to buffer).
A non-buffered Web service is operationally similar to a buffered Web service in most failure scenarios. The exceptions are cases where the service (RM destination) itself fails. For example, in all the RM source failure scenarios described, the behavior is the same for a buffered or a non-buffered Web service (RM destination). For non-buffered Web services the failure window is open between the following two points:
  • The request is accepted for processing.
  • The response from the Web service is registered for delivery to the client (RM source).
If the Web service (RM destination) fails between these two points, the RM source will assume the request has been successfully processed (since it has been acknowledged) but will never receive a response, and the request may never have been processed.
Carefully consider this failure window before configuring a Web service to run as non-buffered.

Monday, December 12, 2011

JAX-WS Reference Implementation

JAX-WS RI 2.2 is a Web Services framework that provides tools and infrastructure to develop Web Services solutions for the end users and middleware developers.
  • Standards
    • Web Services Addressing 1.0 - Core
    • Web Services Addressing 1.0 - SOAP Binding
    • Web Services Addressing 1.0 - Metadata
    • Web Services Addressing 1.0 - WSDL Binding (RI specific support)
    • WS-Addressing  - Member Submission
    • SOAP 1.1 and 1.2
    • REST and XML/HTTP
    • WS-I Basic Profile 1.1
    • WS-I Simple SOAP Binding Profile 1.0
    • WS-I Attachment Profile 1.0
    • MTOM
  • Extensions (May not be final unless says so)
  • Data binding - JAXB 2.2 RI
  • Server Side Asynchrony - AsyncProvider
  • Stateful Web Services
  • Support for custom WebServiceFeature
  • Hosting API
    • These APIs can be used b y a J2EE application server to integrate JAX-WS RI 2.2 for hosting JAX-WS services
  • Endpoint Deployment
    • Glassfish v2
      • Tightly integrated with Glassfish
      • Supports EJB and Web endpoints
      • 109 based deployment support for better portability
      • JAX-WS RI specific deployment descriptor support
    • Sun One Application Server 9.0 ur1
    • Light weight HTTP server
      • On JDK 1.5 through http.jar distributed with the JAX-WS 2.2 FCS RI bundle
      • Bundled with JDK 6
    • Any other container that supports Servlet 2.4, such as Tomcat, Jetty, Geronimo, JBoss, Resin, ... You name it!

Axis2 - Sandesha Reliable messaging Implementation

As the adoption curve for Web services continues to evolve, merely alleviating the distributed communication headaches of heterogeneous platforms will not be enough for many projects. Even though interoperability figures at the top of list for most people considering Web services, distributed systems pose many thorny issues that can leave interoperability as an unrealized goal. In the following paragraphs, we will take a look at how Web services tackles one of these distributed technology concerns: Reliability.
Reliability is a critical concern especially among applications involving financially sensitive data, having a Web service broker information on behalf of a weather forecast is not the same as one providing stock market orders. The former can tolerate a network failure and newly issued requests without major impact, but if the latter does not have the necessary provisions to deal with these effects it can have severe consequences. To this end, there is one particular Web service specification under the auspices of OASIS that tackles reliability issues: WS-ReliableMessaging .
WS-ReliableMessaging, like any other Web service specification, poses the characteristic known as composability, which allows you to mix and match SOAP specific behaviors on an as needed basis. In this manner, any SOAP-based application you may already have can reap the benefits of this reliability layer simply by incorporating additional SOAP header information, thus enforcing any of the rules available in WS-ReliableMessaging, such as:
  • Guaranteed delivery at least once - the sent message must be delivered at the receiver or else a notification of potential delivery failure is given to the sender
  • Duplicate elimination - delivery at most once, duplicates are detected and eliminated by the receiver
  • Guaranteed message ordering - messages are delivered in the order sent
While WS-ReliableMessaging provides the protocol -- based on SOAP -- to transfer reliability data over the wire, such a payload, in one manner or another, has to be interpreted or processed by a higher level stack to determine if a reliable communication has been executed. In WS-ReliableMessaging's case, this higher level stack refers to a specific environment which will be capable of such evaluation, this could either be an ESB or a Web Services framework like PHP/PEAR or Java/Axis.
Where this takes us is that, even though services built with any WS-ReliableMessaging implementation should be capable of interacting seamlessly with one other, in order to use such information, there will surely be a learning curve unique to a particular Web services stack. One such case is the WS-ReliableMessaging implementation produced by the Apache Software Foundation named Sandesha which is closely pegged to the Axis framework, a Java Web services stack produced by the same foundation.
We will now take a look at Sandesha and see how it leverages the Axis framework to create reliable Web services. Bear in mind we won't delve into specific details, so you are advised to consult Sandesha's documentation to see how it plugs-in with the Axis architecture or, of course, Axis documentation if you are unfamiliar with the framework.
Our scenario consists of a Web service client which requires a reliable request to a stock quoting system. Listing 1.1 illustrates how our client uses Sandesha/Axis for such a task.
Listing 1.1 : Web Service Client using Sandesha/Axis for WS-ReliableMessaging
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;

import org.apache.sandesha.Constants;
import org.apache.sandesha.SandeshaContext;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;

public class StockQuoteClient {

   private static String targetURL = 
        "http://acmestockquote.com/axis/services/StockQuote";

   public static Double stockQuote(String symbol) {
        Double priceObject = new Double(0.0); 
 try {

         Service service = new Service();
  Call call = (Call) service.createCall();
  SandeshaContext ctx = new SandeshaContext();
     ctx.initCall(call,targetURL,
 "urn:wsrm:stockQuotePrice",Constants.ClientProperties.IN_OUT);
 call.setOperationName(
       new QName("acmestockquote.com", "stockQuotePrice"));
 call.addParameter(
       "Text", XMLType.XSD_STRING, ParameterMode.IN);
 call.addParameter(
       "Seq", XMLType.XSD_STRING, ParameterMode.IN);
 call.setReturnType(
       org.apache.axis.encoding.XMLType.XSD_DOUBLE);
  ctx.setLastMessage(call);
 priceObject = (Double) 
  call.invoke(new Object[]{"StockQuote",symbol});
        ctx.endSequence();
 } catch (Exception e) { 
            e.printStackTrace();
 }
        return priceObject; 
   }
   
    public static void main(String[] args) {

        StockQuoteClient.stockQuote("SLB"); 
 StockQuoteClient.stockQuote("BCA"); 
 StockQuoteClient.stockQuote("SNY"); 
    }
}
The stockQuote method contains the bulk of our business logic. First off, you will notice the use of the Service and Call classes, each of these object instances would normally be used by any Web service client based on Java Axis, but in this particular case, both are interleaved with the SandeshaContext class which is it what grants us our reliability layer.
The SandeshaContext is used to maintain state on the interactions taking place between client and server. That is the reason why the Call method invocations are nested between ctx.initCall and ctx.endSequence, which represent Sandesha's delimiters for initiating and terminating a reliable process, in case the actual Call methods generate an error that is undetectable by standard Web services operation -- such as guaranteed delivery or duplicate requests - Sandesha can determine by its context such an outcome.
In this listing, you can also observe the use of the namespace urn:wsrm:stockQuotePrice within the ctx.initCall method. This represents the additional SOAP header information added to the client request that has to be acknowledged by the Web service provider in order to fulfill the reliability loop. In Axis/Sandesha's case, while the combination does provide extensive support for building service providers capable of interpreting WS-ReliableMessaging clients, it would go beyond the scope of this article to explore such details. However, you should note that the Axis/Sandesha framework has been successfully tested to interoperate with WS-ReliableMessaging enabled clients and servers produced on different Web services stacks, such as those produced by IBM, Microsoft and Systinet.
With this we conclude our overview of Sandesha and WS-ReliableMessaging. Having exposed how to leverage Web services with reliability features, you are now in a position to consider complementing other enterprise messaging technologies such as JMS (Java Messaging Service) -- which until recently provided the only viable alternative to reliable distributed communication -- and use WS-ReliableMessaging to offer this same reliability level, but with the inherent benefits of platform independent Web services.

Axis2 and Reliable messaging

A big milestone was reached when Apache Axis2 1.0 was released in May 2006. Axis2 1.1 will be released in November 2006, with lots of new features, mostly initiated by its user community, and numerous bug fixes making it more and more stable. Axis2 has come a long way since its Apache Axis and Apache SOAP origins. Not only is it more efficient, modular, and XML-oriented, it is also flexible and extensible and it implements enterprise features such as security and reliability. The ease of use and functionality of Apache Axis2 really makes it the next generation web services platform. And in this article, you will see how much has been achieved. You'll see a mature product that supports the new generation of interoperable standards such as WS-Security, WS-Reliable Messaging, and WS-Addressing.
Axis2 architecture: The component view

Figure 1. The component view
Figure 1. The component view
AXIs Object Model (AXIOM) is the XML object model for Apache Axis2. The kernel layer on top of Axiom consists of the engine, the module, and the deployment frameworks. There are no Java™-specific concepts inside the core parts of Axis2. All other components are layered on top of the kernel. The various transports (for example, HTTP and SMTP) and data binding (converting XML to and from Java code) are not in the core and because they are pluggable, they provide a lot of flexibility. All other relevant technologies, such as Java API for XML Web Services (JAX-WS), are layered on top of Axis2.
We'll now examine the following components of Axis2:
  • AXIOM (the new XML Infoset representation)
  • Extensible messaging engine
  • Pluggable module architecture
  • Improved deployment model
  • New client API
  • Pluggable data binding
  • Representational State Transfer (REST) support
AXIOM
AXIs Object Model (AXIOM) is an XML object model designed to improve both memory use and performance during XML processing and is based on pull parsing. By using the Streaming API for XML (StAX) pull parser, AXIOM (also referred to as OM) can control the parsing process to provide deferred building support. Deferred building is the ability of AXIOM to partially build the object model while the rest of the model is built based the user's needs. The following example illustrates the concept:
Suppose a user needs to get the value of <Location> element of the first person from an XML input stream, AXIOM builds the object model up to the end of <Location> element and leaves the rest in the stream:

Listing 1. AXIOM partial build of object model
<Persons>
  <Person>
     <Name>Dihini Himahansi</Name>
     <Sex>Female</Sex>
     <Location>Colombo, Sri Lanka</Location>  
     <--- Object model is being built only up to this point
  </Person>
  <Person>
     <Name>Thushari Damayanthi</Name>
     <Sex>Female</Sex>
     <Location>Elpitiya, Sri Lanka</Location>
  </Person>
</Persons>

The advantage here is that the memory is used only to satisfy user needs as much as possible. If a user wants to access first couple of bytes or kilo bytes in a larger document, then the deferred building capability will enhance the memory requirement of that application.
You can get StAX events from any element, regardless of whether the object model is fully built or not. There are some cases in which this feature becomes handy inside Axis2. For example, when Axis2 is mediating messages, and if it needs to read only the headers of the SOAP messages, AXIOM prevents it from reading the whole SOAP message, making it highly memory efficient. Another example would be when a web service implementation can consume StAX events directly, because of AXIOM, the memory requirements are very low for that web service.
In addition, AXIOM has built-in support for Message Transfer Optimization Mechanism (MTOM). With the AXIOM architecture, you can execute your own object model by implementing AXIOM interfaces and plugging them into Axis2.
Because AXIOM initially started as the object model for Axis2, AXIOM comes with SOAP interfaces built on top of base AXIOM APIs. This allows you to look at SOAP using convenience methods like envelope.getHeaders and envelope.getBody.
AXIOM has proven to be fast and efficient compared to other widely used object models. See Resources for some performance tests done with AXIOM.
Extensible messaging engine
As we mentioned earlier, the Axis2 engine is a pure SOAP processor and doesn't depend on any Java-specific specification. For example, JAX-WS will be implemented as a layer on top of Axis2 and won't leak into the core.

Figure 2. Extensible messaging engine
Figure 2. Extensible messaging engine
Once a message is received by the engine through a transport, the engine calls the preregistered set of interceptors called handlers. Handlers normally process the information inside the SOAP headers, although they have no limitations on processing other parts of the message as well. The message is then handed to a message receiver -- the ultimate recipient of the message. The message receiver also is responsible for dealing with the message accordingly, and most of the time will hand this message to a service implementation class for processing.
Piping model of Axis2
Axis2's core message processing parts can be modeled using a set of pipes. An incoming message to the Axis2 engine goes through the "in" pipe. All outgoing messages go through the "out" pipe.

Figure 3. Piping model of Axis2
lFigure 3. Piping model of Axis2
Message Exchange Pattern (MEP)
Let's look at a message exchange between a client and a server. If a client needs to get a stock quote from the server, it sends a request message to the server, and the server sends out a response message to the client. From the server's point of view, it receives an "in" message and sends an "out" message. This is a pattern for the request-response scenario, and is named in-out MEP. Likewise, a client can send an in-only message to the server, for example, to subscribe to a mailing list.
For more information about Message Exchange Patterns please refer to the W3C web site.
The combination of the variable number of in and out pipes enables Axis2 to handle any MEP. For example, one in pipe and one out pipe can be used to enable an in-out interaction. One in pipe can be used to enable in-only interaction. The connecting of these pipes is done by the message receiver.
Axis2 can handle most MEPs defined in the Web Services Description Language (WSDL) 2.0 specification and can be extended to support any custom MEP.
Phases
The inside of every Axis2 pipe is divided logically into areas called phases. (Phases are a logical set of handlers in a pipe.) These phases are named to represent what happens to a message during that phase. For example, the first phase of the in pipe is the TransportIn phase and all of the handlers which does transport information processing can be there. Handlers in the Dispatch phase will identify to which service and operation this message is destined.
These phases come in handy, especially when trying to deploy new handlers, since we can specify in which phase the handler needs to be executed.
Context hierarchy
The Axis2 environment needs to keep information in different levels. For example, information that is common to the whole engine should be maintained at the system level, while the message-level information should be kept at the message level. Some information is dynamic and some is static. To address those various requirements, Axis2 has a context hierarchy to maintain information at different levels.

Figure 4. Context hierarchy
Figure 4. Context hierarchy
The left-hand side of the hierarchy contains all the dynamic information, while the right-hand side of the hierarchy contains static information that is mostly read from files.
MessageContext contains information relevant to the message that is being processed, and OperationContext has the information relevant to the particular MEP this message belongs to. ConfigurationContext contains system-wide dynamic information, while AxisConfiguration contains system-wide static information mostly read from axis2.xml.
Dispatching
Every message that comes into the Axis2 engine is destined for a particular service and operation. Identifying this service/operation combination is called dispatching, and the Axis2 engine provides four basic ways to do that:
  1. Dispatching based on request URI: Sometimes you can identify the service the message is destined for by looking at the request URI. For example, the request URI "http://myip/axis2/service/StockQuoteService/getQuote" can be used to identify that the message is destined for the getQuote operation of StockQuoteService.
  2. Transport information: The SOAPAction HTTP header can be used to determine the service and operation.
  3. WS-Addressing headers: If the incoming message contains WS-Addressing headers, they also can be used for dispatching.
  4. The QName of the first child of the SOAP body also can be used if the name was defined using RPC rules.
Those are some of the basic features of the Axis2 engine. We'll look now at how modules provide an extension mechanism for Axis2.
Pluggable module architecture
Modules provide an extension mechanism to the server. Each module in Axis2 contains a set of related handlers. For example, a WS-Addressing module will contain a set of handlers for WS-Addressing support for the Axis2 engine. An Axis2 administrator can add WS-Addressing support to an Axis2 engine by downloading a WS-Addressing module and deploying it in the Axis2 engine. The module.xml file contains rules to designate which pipe and phase the handlers should go in.

Figure 5. Pluggable module architecture
Figure 5. Pluggable module architecture
The module is useful because if you need support for a WS-*, the proper module can be downloaded and deployed without worrying about where the handlers should go. Modules have the .mar extension to denote module archive. Following are several modules supporting WS-* specifications that have already been built:
  • Sandesha2 module: Provides WS-Reliable Messaging support
  • WS-Addressing module: Provides WS-Addressing support for Axis2
  • Rampart and Rahas modules: Provide WS-SX (security-related specifications) support
  • Kandula module: Provides WS-AT support
  • Savan module: Provides WS-Eventing support
Module availability and engagement
Once a module is deployed in the Axis2 engine, it is "available" and can be engaged. Engagement of a module can be done at the following levels, depending on the requirement:
  • System level: The module will affect the entire system and the handlers in this module will work on all messages that come into the system.
  • Service level: Handlers in this module will work on messages that are destined for a particular service. These handlers should always be deployed after the dispatch phase.
  • Operation level: Handlers in this module will work on messages that are destined for a particular operation. These handlers should always be deployed after the dispatch phase.
When the service is deployed, modules can be engaged to the service by putting a small entry in the descriptor.
Improved deployment model
Axis2 now supports hot deployment of services into the Axis2 engine. This enables users to deploy services without restarting the server. Services should be archived ZIP files with a .aar (Axis2 archive) extension in the file name. Service archives contain the following:
  • Service implementation class
  • Services.xml file, which describes the message receiver it uses, any module that is required, and operations that are available
  • Optional dependency libraries packed inside the lib folder
These service archive files can either be copied to the Axis2 repository, which contains all the services and modules, or uploaded through the administration console that is part of Axis2.
New client API
Axis2 can invoke a web service in two ways. The ServiceClient API is the easiest to use but gives the user less control. The OperationClient API provides a great deal of control during an invocation. Both APIs have built-in support for basic in-out and in-only MEPs.
Axis2 now supports both blocking and nonblocking invocation models. Nonblocking invocations are useful in designing user interfaces and when service invocations take a lot of time.
Users can now select different transports for different paths of the invocation. For example, with an in-out invocation, the user can do the following:
  • Send a message using HTTP and receive the response using the same HTTP channel (use of one dual-channel transport)
  • Send a message using HTTP and receive the response using a different HTTP channel (two dual-channel transports)
  • Send a message using SMTP and receive the response using SMTP (two different transports)
This ability provides maximum control to the user in selecting the proper transport for interactions.

Apache Sandesha2

Apache Sandesha2™ is an Axis2 module that implements the WS-ReliableMessaging specification published by IBM, Microsoft, BEA and TIBCO. By using Sandesha2 you can add reliable messaging capability to the web services hosted using Axis2. Sandesha2 can also be used with Axis2 client to interact with already hosted web services in a reliable manner. Please see sandesha2 user guide for more information on using Sandesha2. Read Sandesha2 Architecture guide to see how Sandesha2 work internally.
Apache Sandesha2, Sandesha2, Apache, the Apache feather logo, and the Apache Sandesha2 project logo are trademarks of The Apache Software Foundation.

Java - ArrayList

ArrayList class provides methods for basic array operations:
  • add( Object o ) - puts reference to object into ArrayList
  • get( int index ) - retrieves object reference from ArrayList index position
  • size() - returns ArrayList size
  • remove( int index ) - removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list.
  • indexOf( Object o) - finds the index in this list of the first occurrence of the specified element
  • clear() - removes all of the elements
Following example ask user for his/her name, and suggests him/her a vacation place.
ArrayList "myarr" is filled with resort names(add method). After user enters his name, we calculate residue of division of user's name length by myarr size -- operation result is a number from 0 to myarr.size()-1 -- which is suitable as array index.
source code: Java
 
 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
 
public class Ex01 { 
 
    public static void main(String[] args) throws IOException { 
 
        BufferedReader userInput = new BufferedReader 
            (new InputStreamReader(System.in));
 
        ArrayList<String> myArr = new ArrayList<String>();
        myArr.add("Italian Riviera");
        myArr.add("Jersey Shore");
        myArr.add("Puerto Rico");
        myArr.add("Los Cabos Corridor");
        myArr.add("Lubmin");
        myArr.add("Coney Island");
        myArr.add("Karlovy Vary");
        myArr.add("Bourbon-l'Archambault");
        myArr.add("Walt Disney World Resort");
        myArr.add("Barbados");
 
        System.out.println("Stupid Vacation Resort Adviser");
        System.out.println("Enter your name:");
        String name = userInput.readLine();
        Integer nameLength = name.length();
        if (nameLength == 0) 
        { 
            System.out.println("empty name entered");
            return;
        } 
 
        Integer vacationIndex = nameLength % myArr.size();
 
        System.out.println("\nYour name is "+name+", its length is " + 
                        nameLength + " characters,\n" +
                        "that's why we suggest you to go to " 
                        + myArr.get(vacationIndex));
    } 
} 
 
warning 

  • ArrayList stores only object references. That's why, it's impossible to use primitive data types like double or int. Use wrapper class (like Integer or Double) instead.

  • For multi-theaded(synchronized) array class use Vector (java.lang.Vector)