Welcome!

Java Authors: Dana Gardner, Brian Vandegrift, Carmen Gonzalez, Pat Romanski, Elizabeth White

Related Topics: Websphere

Websphere: Article

Using JAXB to Develop Enterprise Applications

JAXB offers power, ease, and flexibility

JAXB (Java Architecture for XML Binding) provides a convenient way to bind an XML Schema to a representation in Java code and makes it easy for developers to incorporate XML data and processing functions into applications based on Java technology without having to know much about XML itself.

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

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

This article will show developers how to utilize the power, ease, and flexibility of JAXB from within the WebSphere Studio Application Developer (referred to as WebSphere Studio), while developing real-world enterprise applications. With JAXB, developers no longer need to learn the intricacies of XML parsing techniques!

What You Need to Know
Although developers need not worry about XML parsing techniques anymore, they may need to do some reading up.

JAXB is built upon XML Schema, so a sound understanding of XML Schema is imperative in order to harness the power of JAXB. Business domain objects and their structural relationships can be well represented through an XML Schema, provided you have a good understanding of its power. The essence of JAXB lies in its customization of the XML Schema for Java objects. These customizations follow the rules of XML Schema. Adding JAXB customizations to a business domain object model (represented in XML Schema) is simple once the hard work of creating the schema is accomplished.

This article assumes you understand:

  • XML Schemas (the more detailed the better)
  • JAXB
  • WebSphere Studio 5.1
Software and Packages Used
You must have the following products to complete the steps in this article:
  • WebSphere Studio Application Developer 5.1
  • Java Web Services Developer's Pack (JWSDP v1.3)
While we are all familiar with WebSphere Studio, JWSDP requires a little more introduction.

JWSDP from Sun Microsystems is a free integrated toolkit you can use to build, test, and deploy XML applications, Web services, and Web applications with the latest Web services technologies and standards implementations. JAXB is an essential part of this package. JWSDP 1.3 must be downloaded and installed (see the Development Environment Setup section for a detailed explanation of the process).

JAXB Basics
In object-oriented programming (OOP) there are two pivotal concepts: classes and objects. Classes provide the structure for software concepts or entities, whereas objects are live instances of the classes. A similar analogy can be used in XML representation. An XML Schema can be conceptualized as the allowable structure and constructs that can be used in the creation of an XML document (which conforms to the schema). The schema (in XML) and classes (in OOP) are the conceptual building blocks, whereas documents (in XML) and objects (in OOP) are live instances that conform to their respective conceptual building blocks.

Working with Java objects and classes is fundamentally different from working with XML. JAXB brings in the idea of data binding, which creates a correspondence between the XML schemas and the Java classes, and then utilizes the mapping to convert XML documents to and from Java classes. The JAXB schema compiler creates Java classes and interfaces based on the structure of the XML Schema. JAXB libraries are used in marshaling and unmarshaling. Marshaling is the process of turning one or more Java objects into an XML document, whereas unmarshaling is the reverse process - creating a Java object from an XML document.

To use JAXB in a Java application the first step is to run the JAXB compiler (XJC) to create the Java classes and interfaces. For every element in the XML Schema, one or two Java interfaces and corresponding implementation classes (which implement the interfaces) are generated. The implementation classes are generated in a package that is separate from the one in which the interfaces are generated. Other than the interfaces and the implementation classes, JAXB-specific classes are generated to perform marshaling and unmarshaling, and to create instances of the implementation classes, among other things. (Note: The implementation classes are only instantiated through a factory class generated by the JAXB compiler). The two classes that are primarily used in working with JAXB-created Java objects are:

  • JAXBContext: Used for marshaling, unmarshaling, and validating XML documents
  • ObjectFactory: Used to instantiate the various implementation classes
Development Environment Setup
The first step is to download and install the JWSDP. As a part of JWSDP, the JAXB compile and runtime libraries and executables are installed. The next step is to download the JAXBTestEAR.zip file from www.sys-con.com/websphere/sourcec.cfm and extract the contents into the C:\temp folder. Next, create a new workspace and import the JAXBTestEAR file:
  1. Create a folder called JAXB and another called workspace under JAXB in the C:\ drive.
  2. Open WebSphere Studio and point the workspace to C:\JAXB\workspace.
  3. Select File>Import from the WebSphere Studio menu.
  4. Select the EAR file type to import (see Figure 1).
  5. Browse the file system and select the JAXBTestEAR.ear file. Click Finish.
  6. The imported project in the J2EE Perspectives, Project Navigator tab should look like Figure 2.
With the initial setup complete, the JAXB compiler needs to be set up as an External Tool through the WebSphere Studio menu.
  1. Select External Tools from the WebSphere Studio menu as shown in Figure 3.
  2. Click New to create a new configuration. In the Main tab, key in the Name, Location, Working Directory, and Arguments as shown in Figure 4. (Browse the File system and Workspace in order to obtain the values.)
  3. Switch to the Resource tab and check the checkboxes. Highlight the $resource Scope Variable and then choose JAXBTest as the specific resource.
  4. Click Apply to save the configurations. Click Run to run the JAXB compiler (xjc.bat) and generate the Java classes and interfaces. The output in the output console will resemble Figure 5.
This completes the setup of the development environment inside WebSphere Studio.

Example Scenario
The example we will develop is a simple GUI menuing system. A widget is a conceptual element that defines the whole set of drawing components that constitute a graphical user interface. Examples of widgets are rectangles, squares, circles, and any other drawable visual component. Our simplistic GUI consists of three visual components in the form of rectangles, squares, and circles. The Widgets component encapsulates a list of the visual components (rectangles, squares, and circles) in any random order. A client can construct the visual components from a given XML document and then retrieve the details of each visual component (to be used in any way the client requires).

Listing 1 illustrates the XML Schema (for the example scenario) in some detail. The xs:annotation element is a container for the xs:appinfo and xs:documentation elements, which contain additional information. These two elements are dedicated to holding machine-processable (xs:appinfo) information and human-readable documentation (xs:documentation).

The section highlighted in blue denotes the JAXB-specific global customizations of the schema that are applicable to the entire schema file. The section highlighted in red denotes the JAXB-specific customizations in which the package where the generated files will be placed is defined (in this case, com.ibm.domainobjects).

In the globalBindings section the collectionType = java.util.ArrayList is highlighted in blue. It denotes that any Collections that are created inside the Java objects all conform to the List interface in Java and are actual instances of ArrayList.

The xjc:serializable element makes sure that all the generated classes are serializable. (This is particularly important when objects are sent and received over the wire while data transfer between various application tiers is performed.)

A superClass called Shape is also defined. This denotes that all the elements defined in this schema have a common superclass called Shape. I show this here in order to illustrate that the classes that are created from the schema can also refer to external classes, i.e., classes that are not created by the JAXB compiler.

The definition of the Widgets element shows that there is a property called "Widgets" that is defined. Had this property not been defined, the binding compiler would have autogenerated a name for the list of choices (for the rectangles, squares, and circles). The autogeneration usually takes the names of the subelements and combines them with "Or". Hence the accessor name for the list would have been something like:

java.util.List getRectangleOrSquareOrCircle();

Clearly this is not meaningful. The jxb:property name="Widgets" denotes that the accessor method will be getWidgets, which is clearly much more intuitive than the autogenerated name.

In the example, I will demonstrate:

  1. How to set up the usage of the external JAXB compiler from WebSphere Studio
  2. How to use the JAXB compiler to generate Java interfaces and classes
  3. How to create the Java classes from an XML document
  4. How to instantiate Java classes, set their attributes, and then generate the corresponding XML document (the reverse of the previous step)
Various other customizing facets can be used in an XML Schema. The detailed specification for JAXB Customizations is found in the Resources section in the links for the JAXB Specification, Customizing JAXB Schemas, and Using JAXB.

Using the JAXB Generated Classes
The JAXB compiler is run only once. There is no need to run it again if the schema is not changed. However, if the schema undergoes any changes, then the JAXB compiler preprocessing step must be executed again in order to regenerate the Java interfaces and classes. In this event, it is advisable to delete all of the generated classes from a previous run of the JAXB compiler before running this step again. This is particularly helpful in cases in which elements in the schema are deleted. The generated classes from the new run of the compiler do not delete the old generated classes and hence some unused classes from the previous version of the schema will be left behind.

Once all the classes are generated, the fun begins, with the bulk of the tedious (if you consider it so) setup work already completed. It is time to use the generated classes in order to convert XML documents into Java classes and vice versa. We will concentrate on a client class called JAXBTester. This class demonstrates two activities. It first reads in a given XML document from which it creates the Java object structure/tree.

Analysis of JAXBTester
JAXBTester has three methods. A brief explanation of each of the methods is in order.

  • createContext: Creates an instance of the JAXBContext class from which we can get a handle to an instance of the Unmarshaller and Marshaller instances.
  • unmarshallIt: Accepts an XML document (which in our case is the "schema.xml" file found in the schema folder under WebContent). It creates an instance of the UIWidgets class (the root element in the XML document), then invokes the getWidgets accessor method on the UIWidgets instance and iterates through the list of contained Widgets, retrieving the various Widget-specific attributes in each iteration.
  • marshallIt: Illustrates how we can instantiate any element in the XML Schema (for which there are generated Java objects), set the various attribute values, and then add each object to its container. An instance of ObjectFactory is used to create the various instances of the Java objects, for example RectangleImpl, CircleImpl, etc. The getWidgets method on the instance of UIWidgetsImpl returns a handle to an instance of a live List to which the child elements (instances of RectangleImpl, SquareImpl, and CircleImpl) can be added. Once the object structure is created, a single method call on the instance of the Marshaller generates the XML representation of the object structure.

    Notice how not a single line of XML-specific code needs to be coded by the developer; the specifics of the conversion are all contained inside the generated classes.

    Running the Sample
    Before running the client class several steps must be followed in sequence:

    1. The JAXB compiler must be run to generate the Java object tree. (This step should already have been completed.)
    2. The import statements that are commented out in the JAXBTester must be uncommented. The method bodies of unmarshallIt and marshallIt that are commented out need to be uncommented prior to compilation of JAXBTester. These portions are commented out because the classes that are referenced (both in the import statements and inside the methods) are all generated classes. When the EAR file was imported, these generated classes did not exist; hence, prior to Step 1 JAXBTester would not have compiled.
    3. The value of the absPathToXML, which denotes the path to the schema.xml file, must be changed (if required) to reflect the path to the file in the file system.
    Now you're all set to run the sample and see the results for yourself.

    Conclusion
    This article introduced you to the basics of JAXB. The most important aspect of this article was the demonstration of how JAXB can be used in a J2EE application and how the all development can be achieved from our friendly and most loved IDE - WebSphere Studio.

    The best way to learn JAXB is to get very familiar and comfortable with XML Schema and then learn the tricks of JAXB customizations. The best way to learn XML Schema is to read a book on it, and then apply the concepts in real-world scenarios, exploiting the various features. (The O'Reilly book XML Schema is my favorite.)

    Resources

  • The Java Web Services Developer Pack 1.3: http://java.sun.com/webservices/downloads/webservicespack.html
  • Data Binding with JAXB: www-106.ibm.com/developerworks/xml/edu/x-dw-xjaxb-i.html
  • The JAXB Specification: http://java.sun.com/xml/downloads/jaxb.html
  • Customizing JAXB Schemas: http://java.sun.com/xml/jaxb/users-guide/jaxb-custom.html
  • Using JAXB: http://java.sun.com/xml/jaxb/users-guide/jaxb-using.html
  • Java Architecture for XML Binding (JAXB): http://java.sun.com/developer/technicalArticles/WebServices/jaxb/index.html
  • 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.