Welcome!

Java IoT Authors: Elizabeth White, Yeshim Deniz, Zakia Bouachraoui, Liz McMillan, William Schmarzo

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.

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

  • 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
    Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
    Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
    Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
    René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
    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...
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
    Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
    If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
    Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
    When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...