|By Tilak Mitra||
|March 30, 2004 12:00 AM EST||
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)
- WebSphere Studio 5.1
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)
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).
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
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:
- Create a folder called JAXB and another called workspace under JAXB in the C:\ drive.
- Open WebSphere Studio and point the workspace to C:\JAXB\workspace.
- Select File>Import from the WebSphere Studio menu.
- Select the EAR file type to import (see Figure 1).
- Browse the file system and select the JAXBTestEAR.ear file. Click Finish.
- The imported project in the J2EE Perspectives, Project Navigator tab should look like Figure 2.
- Select External Tools from the WebSphere Studio menu as shown in Figure 3.
- 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.)
- Switch to the Resource tab and check the checkboxes. Highlight the $resource Scope Variable and then choose JAXBTest as the specific resource.
- 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.
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:
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:
- How to set up the usage of the external JAXB compiler from WebSphere Studio
- How to use the JAXB compiler to generate Java interfaces and classes
- How to create the Java classes from an XML document
- How to instantiate Java classes, set their attributes, and then generate the corresponding XML document (the reverse of the previous step)
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.
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:
- The JAXB compiler must be run to generate the Java object tree. (This step should already have been completed.)
- 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.
- 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.
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.)
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound effect on the world, and what should we expect to see over the next couple of years.
Nov. 27, 2015 02:30 AM EST Reads: 445
Discussions of cloud computing have evolved in recent years from a focus on specific types of cloud, to a world of hybrid cloud, and to a world dominated by the APIs that make today's multi-cloud environments and hybrid clouds possible. In this Power Panel at 17th Cloud Expo, moderated by Conference Chair Roger Strukhoff, panelists addressed the importance of customers being able to use the specific technologies they need, through environments and ecosystems that expose their APIs to make true change and transformation possible.
Nov. 27, 2015 02:00 AM EST Reads: 509
Microservices are a very exciting architectural approach that many organizations are looking to as a way to accelerate innovation. Microservices promise to allow teams to move away from monolithic "ball of mud" systems, but the reality is that, in the vast majority of organizations, different projects and technologies will continue to be developed at different speeds. How to handle the dependencies between these disparate systems with different iteration cycles? Consider the "canoncial problem" in this scenario: microservice A (releases daily) depends on a couple of additions to backend B (re...
Nov. 27, 2015 01:00 AM EST Reads: 418
Growth hacking is common for startups to make unheard-of progress in building their business. Career Hacks can help Geek Girls and those who support them (yes, that's you too, Dad!) to excel in this typically male-dominated world. Get ready to learn the facts: Is there a bias against women in the tech / developer communities? Why are women 50% of the workforce, but hold only 24% of the STEM or IT positions? Some beginnings of what to do about it! In her Day 2 Keynote at 17th Cloud Expo, Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, wil...
Nov. 27, 2015 01:00 AM EST Reads: 554
PubNub has announced the release of BLOCKS, a set of customizable microservices that give developers a simple way to add code and deploy features for realtime apps.PubNub BLOCKS executes business logic directly on the data streaming through PubNub’s network without splitting it off to an intermediary server controlled by the customer. This revolutionary approach streamlines app development, reduces endpoint-to-endpoint latency, and allows apps to better leverage the enormous scalability of PubNub’s Data Stream Network.
Nov. 27, 2015 01:00 AM EST Reads: 305
The cloud. Like a comic book superhero, there seems to be no problem it can’t fix or cost it can’t slash. Yet making the transition is not always easy and production environments are still largely on premise. Taking some practical and sensible steps to reduce risk can also help provide a basis for a successful cloud transition. A plethora of surveys from the likes of IDG and Gartner show that more than 70 percent of enterprises have deployed at least one or more cloud application or workload. Yet a closer inspection at the data reveals less than half of these cloud projects involve production...
Nov. 27, 2015 01:00 AM EST Reads: 458
Apps and devices shouldn't stop working when there's limited or no network connectivity. Learn how to bring data stored in a cloud database to the edge of the network (and back again) whenever an Internet connection is available. In his session at 17th Cloud Expo, Ben Perlmutter, a Sales Engineer with IBM Cloudant, demonstrated techniques for replicating cloud databases with devices in order to build offline-first mobile or Internet of Things (IoT) apps that can provide a better, faster user experience, both offline and online. The focus of this talk was on IBM Cloudant, Apache CouchDB, and ...
Nov. 27, 2015 12:45 AM EST Reads: 392
Container technology is shaping the future of DevOps and it’s also changing the way organizations think about application development. With the rise of mobile applications in the enterprise, businesses are abandoning year-long development cycles and embracing technologies that enable rapid development and continuous deployment of apps. In his session at DevOps Summit, Kurt Collins, Developer Evangelist at Built.io, examined how Docker has evolved into a highly effective tool for application delivery by allowing increasingly popular Mobile Backend-as-a-Service (mBaaS) platforms to quickly crea...
Nov. 27, 2015 12:00 AM EST Reads: 332
I recently attended and was a speaker at the 4th International Internet of @ThingsExpo at the Santa Clara Convention Center. I also had the opportunity to attend this event last year and I wrote a blog from that show talking about how the “Enterprise Impact of IoT” was a key theme of last year’s show. I was curious to see if the same theme would still resonate 365 days later and what, if any, changes I would see in the content presented.
Nov. 26, 2015 10:00 PM EST Reads: 393
Cloud computing delivers on-demand resources that provide businesses with flexibility and cost-savings. The challenge in moving workloads to the cloud has been the cost and complexity of ensuring the initial and ongoing security and regulatory (PCI, HIPAA, FFIEC) compliance across private and public clouds. Manual security compliance is slow, prone to human error, and represents over 50% of the cost of managing cloud applications. Determining how to automate cloud security compliance is critical to maintaining positive ROI. Raxak Protect is an automated security compliance SaaS platform and ma...
Nov. 26, 2015 04:00 PM EST Reads: 382
Internet of @ThingsExpo, taking place June 7-9, 2016 at Javits Center, New York City and Nov 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 18th International @CloudExpo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world and ThingsExpo New York Call for Papers is now open.
Nov. 26, 2015 03:30 PM EST Reads: 526
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York and Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound cha...
Nov. 26, 2015 03:15 PM EST Reads: 521
We are rapidly moving to a brave new world of interconnected smart homes, cars, offices and factories known as the Internet of Things (IoT). Sensors and monitoring devices will touch every part of our lives. Let's take a closer look at the Internet of Things. The Internet of Things is a worldwide network of objects and devices connected to the Internet. They are electronics, sensors, software and more. These objects connect to the Internet and can be controlled remotely via apps and programs. Because they can be accessed via the Internet, these devices create a tremendous opportunity to inte...
Nov. 26, 2015 02:15 PM EST Reads: 499
Today air travel is a minefield of delays, hassles and customer disappointment. Airlines struggle to revitalize the experience. GE and M2Mi will demonstrate practical examples of how IoT solutions are helping airlines bring back personalization, reduce trip time and improve reliability. In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect with GE, and Dr. Sarah Cooper, M2Mi’s VP Business Development and Engineering, explored the IoT cloud-based platform technologies driving this change including privacy controls, data transparency and integration of real time context with p...
Nov. 26, 2015 01:00 PM EST Reads: 392
We all know that data growth is exploding and storage budgets are shrinking. Instead of showing you charts on about how much data there is, in his General Session at 17th Cloud Expo, Scott Cleland, Senior Director of Product Marketing at HGST, showed how to capture all of your data in one place. After you have your data under control, you can then analyze it in one place, saving time and resources.
Nov. 26, 2015 12:00 PM EST Reads: 151
The Internet of Things (IoT) is growing rapidly by extending current technologies, products and networks. By 2020, Cisco estimates there will be 50 billion connected devices. Gartner has forecast revenues of over $300 billion, just to IoT suppliers. Now is the time to figure out how you’ll make money – not just create innovative products. With hundreds of new products and companies jumping into the IoT fray every month, there’s no shortage of innovation. Despite this, McKinsey/VisionMobile data shows "less than 10 percent of IoT developers are making enough to support a reasonably sized team....
Nov. 26, 2015 11:00 AM EST Reads: 446
Just over a week ago I received a long and loud sustained applause for a presentation I delivered at this year’s Cloud Expo in Santa Clara. I was extremely pleased with the turnout and had some very good conversations with many of the attendees. Over the next few days I had many more meaningful conversations and was not only happy with the results but also learned a few new things. Here is everything I learned in those three days distilled into three short points.
Nov. 26, 2015 10:00 AM EST Reads: 290
DevOps is about increasing efficiency, but nothing is more inefficient than building the same application twice. However, this is a routine occurrence with enterprise applications that need both a rich desktop web interface and strong mobile support. With recent technological advances from Isomorphic Software and others, rich desktop and tuned mobile experiences can now be created with a single codebase – without compromising functionality, performance or usability. In his session at DevOps Summit, Charles Kendrick, CTO and Chief Architect at Isomorphic Software, demonstrated examples of com...
Nov. 26, 2015 09:45 AM EST Reads: 370
As organizations realize the scope of the Internet of Things, gaining key insights from Big Data, through the use of advanced analytics, becomes crucial. However, IoT also creates the need for petabyte scale storage of data from millions of devices. A new type of Storage is required which seamlessly integrates robust data analytics with massive scale. These storage systems will act as “smart systems” provide in-place analytics that speed discovery and enable businesses to quickly derive meaningful and actionable insights. In his session at @ThingsExpo, Paul Turner, Chief Marketing Officer at...
Nov. 26, 2015 09:30 AM EST Reads: 379
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
Nov. 26, 2015 09:00 AM EST Reads: 479