Java IoT Authors: Elizabeth White, Zakia Bouachraoui, Yeshim Deniz, Pat Romanski, Liz McMillan

Related Topics: Java IoT

Java IoT: Article

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.

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.

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.

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.


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

  • 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.

    IoT & Smart Cities Stories
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
    IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
    The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
    Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
    Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
    Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...