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

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


Using JAXB in J2EE-Based Enterprise Applications
Narrowing the bridge between XML and Java Part 2

In Part 2 of this two-part series (Part 1 appeared in Vol. 9, issue 4) I shall try to construct an XML Schema, take you through the steps required to convert an XML document into its corresponding Java classes and interfaces, and also show how to generate an XML document (by using the generated Java classes and interfaces) from a Java object tree, in a programmatic fashion.

A Brief Recap
Part 1 introduced the fundamental concepts of Java Architecture for XML Binding (JAXB) and gave some insights into how it can be used in a typical J2EE-based enterprise application.

The power of JAXB comes from the fact that it removes the developer from the shackles of arduous XML-to-Java (and vice versa) conversion. Its feature-rich specification allows a Java developer to incorporate Java-specific programming constructs as part of the XML Schema. Among the rich set of features, the specification class allows the addition of Java packages, Javadoc comments, Collection classes, etc., to the XML Schema. Once configured, this becomes part of the Java classes and interfaces that are generated by the JAXB compiler.

Example Scenario
We are going to work with an example of a simple library. An oversimplified library may be modeled as a collection of books. Each book has a list of attributes (title, author, ISBN code, etc.). Books may be added or removed from a library.

Referring to Listing 1, the complexType Book has three attributes while the complexType Library is composed of a collection of elements of type Book. BookItem is declared as an element of type Book while CityLibrary is declared as an element of type Library. Any XML document that conforms to this XML Schema can either have a CityLibrary or a BookItem as the root element. A CityLibrary element may contain one or more BookItem elements and any BookItem element contains three attributes. Any reference to elements within the XML Schema is qualified by a namespace - domainObjects in this scenario.

Once the XML Schema is defined, the first step is to use your favorite editor to compile the schema using the JAXB compiler. This produces the Java classes and interfaces in the desired package(s). Listing 2 provides the output of running the JAXB compiler on our schema file.

The compiler can be run with the following command:

xjc.bat -p <package name> -d <working directory>

where <package name> is the package where the Java artifacts are to be generated and <working directory> is the directory in the file system where the packages are going to be generated. (Note: For a Unix-based system, the compiler script is called xjc.sh.)

Figure 1 illustrates the list of Java artifacts that are generated after running the schema through the JAXB compiler.

Once this is created, the developer is ready to harness the real potential of JAXB. The developer can now interpret any XML file that conforms to the XML Schema (from which the above Java artifacts were generated). The process of interpretation is known as unmarshalling (the creation of a Java object tree from an XML document). You can also use the generated classes to programmatically create an XML document. This process is known as marshalling (the creation of an XML document from the Java objects).

The first step for the developer is to obtain a reference to the JAXBContext object. This object has methods to retrieve references to the Marshaller and the Unmarshaller objects.

The Marshaller object instance is used in any subsequent marshalling process while the Unmarshaller object instance is used in any subsequent unmarshalling process.

Listing 3 is a sample Java class that illustrates how the JAXB framework can be used. The method createContext() creates instances of the Marshaller and Unmarshaller classes.

Unmarshalling
In unmarshalling, an XML document (as in Listing 4) is accepted as the input. This XML document is interpreted by the program and corresponding Java classes are instantiated.

The root element of the XML document is CityLibrary, which contains two Books. Referring to Listing 5, the method unmarshallIt creates the root element CityLibraryImpl from the XML document. This generated class has methods to iterate through the list of contained BookImpl objects.

It's up to the application requirements from this point - how to use the data that is now represented as simple Java objects. There is no Java XML parsing that is required to interpret the XML document artifacts. The simple example that is shown here iterates through the list of books and prints out the title and author attributes in each iteration.

Marshalling
In marshalling, the Java objects (generated by the JAXB compiler) are used to create an XML document whose contents conform to the XML Schema (see Listing 5).

A creational class called ObjectFactory (generated by the JAXB compiler) is used to instantiate any class in the Java object tree. A careful look into the classes (in the Java object tree) illustrates that the element containment structure in the XML Schema is represented as contained object references (using the Java Collections Framework). Attributes, however, have getter and setter methods in the Java object's representation of the contained element.

Referring to Listing 3, the method marhsallIt first creates an instance of the root element of a sample XML document (instance of CityLibraryImpl). It then obtains the collection inside the root element that's used to add the nested elements (BookImpl in this case). Instances of BookImpl are created using the ObjectFactory class. Attributes of instances of BookImpl are added using the setter methods of the corresponding Book-Impl instances. Once an instance of BookImpl is created and its attributes set, the instance is added to the collection of the container CityLibraryImpl instance. This way multiple BookImpl instances can be added to the CityLibraryImpl instance. Once the object structure is created, obtaining the structure's corresponding XML representation is a simple matter of invoking a method on the Marshaller instance, and passing the reference of the CityLibraryImpl (root element) as a parameter.

Final Thoughts
By this time, hopefully, we have come to terms with how JAXB can be used in a J2EE-based enterprise application. Even in a simple example like the one described in this article, where can we see this being used? Say, for example, there is a book search capability that allows nearby libraries to search for a list of books in CityLibrary that matches a specific criterion (for example, books by a certain author). The results of the search can be easily returned in an XML format using code that is similar to the marshallIt method in our example. In more sophisticated examples, a J2EE application can accept XML documents (conforming to the XML Schema from which Java artifacts have been generated a priori) and then use JAXB to create Java objects that can then be easily used in order to perform application-specific processing.

An application's domain object model is an ideal candidate to be modeled in an XML Schema. Using JAXB, the transformation between the XML representation and its corresponding Java object tree can be simplified. This will allow XML information exchange between various application tiers and even between communicating applications - a very simple piece of work.

Conclusion
This two-part series attempted to expose you to the world of JAXB. The conceptual introduction in the first part is concluded in the second part with an illustrative example of the usage of JAXB in a J2EE-based application.

The bridge between XML and Java has really been narrowed with the advent of JAXB, and I hope that this article series helps to illustrate this to the JDJ reader community.

Resources

  • JAXB User's Guide: http://java.sun.com/xml/jaxb/users-guide/jaxb-using.html
  • JAXB Specification: http://java.sun.com/xml/downloads/jaxb.html
  • JAXB API Specification: http://java.sun.com/webservices/docs/1.3/api/index.html
  • JAXB Reference Implementation: http://java.sun.com/webservices/downloads/webservicespack.html

    (Note: The Reference Implementa-tion of JAXB comes packaged inside the Java Web Services Developer's Pack [JWSDP]. Once this is installed, the JAXB compile time and runtime libraries are available in the <install-root>\jaxb directory).

  • About Tilak Mitra
    Tilak Mitra is a Certified Senior IT Architect at IBM. He specializes in mid- to large-range enterprise and application architectures based on J2EE, MQ, and other EAI technologies. You can reach him at tmitra@us.ibm.com.

    LATEST JAVA STORIES & POSTS
    Unit testing is hard. There I said it. Although I have been developing software for the past 18 years I still find that putting my applications through their paces via unit testing is difficult. I have learned the lesson (I'm sure like many of you) the hard way. Unit testing is p...
    Continuent has announced support and enhancements to MySQL Server 5.1.30 GA release, the 5.1 production version of the open source database. MySQL 5.1.30 is recommended for use on production systems by the MySQL build team at Sun Microsystems. Continuent Tungsten provides advance...
    As a software journalist, there are times when certain vendors will shut the door on reporting opportunities that might represent too much of an "inside view" of their technology or their organization. I've been to more developer events than I can remember where I've been handed ...
    Active Endpoints has announced the general availability of ActiveVOS 6.0.2, in response to ever increasing demands for improved process performance and efficiencies. ActiveVOS is an all-in-one, 100% standards-based orchestration and business process management system (BPM) that p...
    Just because the web has been open so far doesn't mean that it will stay that way. Flash and Silverlight, arguably the two market-leading technology toolkits for rich media applications are not open. Make no mistake - Microsoft and Adobe aim to have their proprietary plug-ins, ak...
    Doing network I/O on the user interface (UI) thread is bad. Most developers know that and can tell you why; unfortunately, it’s still done. At this year's JavaOne, one of the keynote JavaFX demos bombed because the network was slow, something that would be forgivable had the en...
    SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
    SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
    Click to Add our RSS Feeds to the Service of Your Choice:
    Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
    myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
    Publish Your Article! Please send it to editorial(at)sys-con.com!

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


    SYS-CON FEATURED WHITEPAPERS

    SPONSORED BY INFRAGISTICS
    In every field of design one of the first things students do is learn from the work of others. They ...
    There are many forces that influence technological evolution. After a decade of building enterprise ...
    2008 is going to be an important year for Rich Internet Applications. Most organizations are deliver...
    The OpenAjax Alliance is developing an Ajax industry wishlist for future browsers, using a dedicated...
    Infragistics announced the availability of two Community Technology Preview (CTP) User Interface (UI...
    The YUI development team has released version 2.5.2; you can download the new release from SourceFor...
    ADS BY GOOGLE