Welcome!

Java Authors: Elizabeth White, Liz McMillan, Jason Bloomberg, Roger Strukhoff, Pat Romanski

Related Topics: Java

Java: Article

Using JAXB in Enterprise J2EE Applications

Incorporate XML data and processing functions Part 1

It has been well proven over the past few years that the best form of information exchange (in a typical B2B and B2C environment) is through XML. There are various XML-based standards (schema) for both the horizontal and vertical market sectors and there are ongoing efforts to move toward a standardized format in the various industry sectors.

With the proliferation of an XML-based information exchange, the industry is bound to write lots of Java code to consume XML Schema-based documents. Java Architecture for XML Binding (JAXB) provides a convenient way to bind an XML Schema to a representation in Java code, making it easy for developers to incorporate XML data and processing functions in applications based on Java technology without having to know much about the details of XML parsing.

How It Works
The use of JAXB starts from an XML Schema. Typically in an enterprise application, an XML Schema is defined that constitutes the business domain objects and their interrelationships.

The JAXB (binding) compiler creates a set of classes and interfaces from the XML Schema (see Figure 1). These sets of classes and interfaces are referenced and used in the application. The application developer has a rich set of JAXB APIs that he or she uses to convert a Java object tree/ structure (made up of the instances of classes generated by the binding compiler) to an XML document (that conforms to the XML Schema). The process of converting an XML document into a Java object tree is as seamless and easy as the former and the beauty of it all is that the developer does not have to write a single line of XML parsing routines in either of the conversion processes.

The process of converting a Java Object Tree to an XML document is known as marshalling, whereas the reverse process of converting an XML document to a Java Object Tree is called unmarshalling.

The process of creating the classes and interfaces from the XML Schema utilizes the JAXB binding compiler (xjc.bat or xjc.sh) that's included with the installation (see Resources section).

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

The -p option specifies the Java package for the generated classes and interfaces while the -d option specifies the working directory.

Once the classes and interfaces are generated, they can be used in the enterprise application. There are two typical usage scenarios.

1.  Unmarshal an XML document to a Java object tree

  • To achieve this, an instance of a JAXBContext object needs to be created:

    JAXBContext jContext = JAXBContext.newInstance("<package name>") ;

    where package name contains the JAXB generated classes.

  • An unmarshaller instance is created:

    Unmarshaller unmarshaller = jContext.createUnmarshaller() ;

  • The XML document is read in and a handle to the root Java object in the XML document is obtained:

    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.

    Once a handle to the Library object instance is obtained, we're in the Java universe! The developer can use the power of Java to traverse through the object tree and use the same in the application, as required.

    2.  Marshal a Java object tree to an XML document
    A JAXB implementation-provided class called ObjectFactory is used to create instances of the classes and interfaces that are generated by the JAXB binding compiler (during the generation process). This class uses the Factory pattern to create instances of the generated classes and this is the only way the class instances may be created.

    Consider a small example in which a Library contains a list of Books in which each book has a title and a price field. The steps to create an XML document from the Java object tree are as follows:

  • Obtain an instance of ObjectFactory:

    ObjectFactory factory = new ObjectFactory() ;

  • Create class instances:

    Library library = factory.createLibrary() ;
    Book bookOne = factory.createBook() ;
    bookOne.setTitle("Design Patterns") ;
    bookOne.setPrice("50.00") ;
    Book bookTwo = factory.createBook() ;
    bookTwo.setTitle("Analysis Patterns") ;
    bookTwo.setPrice("45.00") ;
    library.add(bookOne) ;
    library.add(bookTwo);

  • Create an instance of the Marshaller object (from JAXBContext object instance as in scenario 1):

    Marshaller marshaller = jContext.createMarshaller() ;

  • Marshal the Java object tree to an XML document:

    marshaller.marshal(library, new FileOutputStream("library.xml")) ;

    JAXB Customizations
    The power and flexibility of JAXB is further augmented by its customization feature that's added on top of the schema bindings. To add specific functionality to an application, JAXB binding customizations are used. These customizations are read and interpreted by the JAXB compiler. Customization is affected by annotating a schema with binding declarations that either override or extend the default bindings.

    Customization has four scopes:

  • Global: A customization defined with the <globalBindings> element has a global scope applicable to all schema elements and all other schemas that are imported into the schema in which this customization is defined.
  • Schema: A customization defined with a <schemaBindings> element has a schema scope and is only applicable to the schema in which the customization is defined.
  • Definition: A customization value in binding declarations of a type definition and global declaration has definition scope, which covers all schema elements that reference the type definition or the global declaration.
  • Component: A customization value in a binding declaration has component scope if the customization value applies only to the schema element that was annotated with the binding declaration.

    Although a detailed discussion about customization is beyond the scope of this article, it's worthwhile mentioning a few customization artifacts that are used more frequently in a typical JAXB usage scenario.

    Customization bindings can be made at a global level of declaration that applies to all the defined elements in the XML Schema. Listing 1 provides a typical global customization binding.

    Notice how in the listing defining the collectionType attribute tells the compiler that the type of collection used in the generated classes is of type ArrayList. The <xjc: serializable> element ensures that all the generated classes implement the Java Serializable marker interface. The <jxb: package> element's name attribute denotes the Java package in which the generated classes and interfaces are created.

    All these elements' attributes can be tuned and configured to suit the requirements of the application.

    Customization of the default binding can also be made at the element and its attribute's level. For example, an element can be adorned with its Javadoc by using annotations. Custom property names can also be specified that when defined, generate getter and setter methods for the property. This is illustrated in Listing 2. (Listing 2 can be downloaded from www.sys-con.com/java/sourcec.cfm.)

    Notice how in the listing the <jxb: javadoc> element is used to create the documentation for the generated class. The <jxb:property> element is used to name an instance variable inside the generated class (Library class in this case) and generate its getter and setter methods. The generated class hence will have two methods: getBookList() and setBookList(...).

    A detailed explanation of these bindings can be found in the Resources section (JAXB User's Guide).

    Thinking in Terms of JAXB
    In a typical enterprise application that's comprised of various application tiers, data is exchanged between these tiers to realize the business functionalities. It's a good design principle to create a data object model that can be used for inter-tier data exchange. This data object model is a good candidate to be represented in an XML Schema with JAXB customizations. With this design in place, data can be exchanged in either XML format or as Java objects while the JAXB libraries can be used to convert between XML and Java in a seamless fashion.

    Summary
    This article introduced the basic concepts of JAXB, how it works, and how it can be used in a Java-based enterprise application. It also provided a sneak peek at how JAXB customizations can be used to tailor an XML Schema to conform to the application requirements.

    Part 2 will take a concrete example of an XML Schema and discuss the process of generating the classes and interfaces from a valid XML document and also the reverse process of creating an XML document from a Java object tree. Stay tuned!

    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 Implementation 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.)

  • More Stories By 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 [email protected]

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.